Spaces:
Sleeping
Sleeping
omkarenator
commited on
Commit
•
e1d7b62
1
Parent(s):
be766f5
Create stoc.py
Browse files
stoc.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import unidecode
|
3 |
+
|
4 |
+
DISABLE_LINK_CSS = """
|
5 |
+
<style>
|
6 |
+
a.toc {
|
7 |
+
color: inherit;
|
8 |
+
text-decoration: none; /* no underline */
|
9 |
+
}
|
10 |
+
</style>"""
|
11 |
+
|
12 |
+
|
13 |
+
class stoc:
|
14 |
+
def __init__(self):
|
15 |
+
self.toc_items = list()
|
16 |
+
|
17 |
+
def h1(self, text: str, write: bool = True):
|
18 |
+
if write:
|
19 |
+
st.write(f"# {text}")
|
20 |
+
self.toc_items.append(("h1", text))
|
21 |
+
|
22 |
+
def h2(self, text: str, write: bool = True):
|
23 |
+
if write:
|
24 |
+
st.write(f"## {text}")
|
25 |
+
self.toc_items.append(("h2", text))
|
26 |
+
|
27 |
+
def h3(self, text: str, write: bool = True):
|
28 |
+
if write:
|
29 |
+
st.write(f"### {text}")
|
30 |
+
self.toc_items.append(("h3", text))
|
31 |
+
|
32 |
+
def toc(self):
|
33 |
+
st.write(DISABLE_LINK_CSS, unsafe_allow_html=True)
|
34 |
+
st.sidebar.caption("Table of contents")
|
35 |
+
markdown_toc = ""
|
36 |
+
for title_size, title in self.toc_items:
|
37 |
+
h = int(title_size.replace("h", ""))
|
38 |
+
markdown_toc += (
|
39 |
+
" " * 2 * h
|
40 |
+
+ "- "
|
41 |
+
+ f'<a href="#{normalize(title)}" class="toc"> {title}</a> \n'
|
42 |
+
)
|
43 |
+
st.sidebar.write(markdown_toc, unsafe_allow_html=True)
|
44 |
+
|
45 |
+
@classmethod
|
46 |
+
def from_markdown(cls, text: str):
|
47 |
+
self = cls()
|
48 |
+
for line in text.splitlines():
|
49 |
+
if line.startswith("###"):
|
50 |
+
self.h3(line[3:], write=False)
|
51 |
+
elif line.startswith("##"):
|
52 |
+
self.h2(line[2:], write=False)
|
53 |
+
elif line.startswith("#"):
|
54 |
+
self.h1(line[1:], write=False)
|
55 |
+
st.write(text)
|
56 |
+
self.toc()
|
57 |
+
|
58 |
+
|
59 |
+
|
60 |
+
def normalize(s):
|
61 |
+
"""
|
62 |
+
Normalize titles as valid HTML ids for anchors
|
63 |
+
>>> normalize("it's a test to spot how Things happ3n héhé")
|
64 |
+
"it-s-a-test-to-spot-how-things-happ3n-h-h"
|
65 |
+
"""
|
66 |
+
|
67 |
+
# Replace accents with "-"
|
68 |
+
s_wo_accents = unidecode.unidecode(s)
|
69 |
+
accents = [s for s in s if s not in s_wo_accents]
|
70 |
+
for accent in accents:
|
71 |
+
s = s.replace(accent, "-")
|
72 |
+
|
73 |
+
# Lowercase
|
74 |
+
s = s.lower()
|
75 |
+
|
76 |
+
# Keep only alphanum and remove "-" suffix if existing
|
77 |
+
normalized = (
|
78 |
+
"".join([char if char.isalnum() else "-" for char in s]).strip("-").lower()
|
79 |
+
)
|
80 |
+
|
81 |
+
return normalized
|