Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
keras-team
GitHub Repository: keras-team/keras-io
Path: blob/master/scripts/autogen_utils.py
3273 views
1
import re
2
import string
3
import markdown
4
import copy
5
import pathlib
6
import os
7
8
9
def save_file(path, content):
10
parent = pathlib.Path(path).parent
11
if not os.path.exists(parent):
12
os.makedirs(parent)
13
f = open(path, "w", encoding="utf8")
14
f.write(content)
15
f.close()
16
17
18
def process_outline_title(title):
19
title = re.sub(r"`(.*?)`", r"<code>\1</code>", title)
20
title = re.sub(r"\[(.*?)\]\(.*?\)", r"\1", title)
21
return title
22
23
24
def turn_title_into_id(title):
25
title = title.lower()
26
title = title.replace("&amp", "amp")
27
title = title.replace("&", "amp")
28
title = title.replace("<code>", "")
29
title = title.replace("</code>", "")
30
title = title.translate(str.maketrans("", "", string.punctuation))
31
title = title.replace(" ", "-")
32
return title
33
34
35
def make_outline(md_source):
36
lines = md_source.split("\n")
37
outline = []
38
in_code_block = False
39
for line in lines:
40
if line.startswith("```"):
41
in_code_block = not in_code_block
42
if in_code_block:
43
continue
44
if line.startswith("# "):
45
title = line[2:]
46
title = process_outline_title(title)
47
outline.append(
48
{
49
"title": title,
50
"url": "#" + turn_title_into_id(title),
51
"depth": 1,
52
}
53
)
54
if line.startswith("## "):
55
title = line[3:]
56
title = process_outline_title(title)
57
outline.append(
58
{
59
"title": title,
60
"url": "#" + turn_title_into_id(title),
61
"depth": 2,
62
}
63
)
64
if line.startswith("### "):
65
title = line[4:]
66
title = process_outline_title(title)
67
outline.append(
68
{
69
"title": title,
70
"url": "#" + turn_title_into_id(title),
71
"depth": 3,
72
}
73
)
74
return outline
75
76
77
def render_markdown_to_html(md_content):
78
return markdown.markdown(
79
md_content,
80
extensions=[
81
"fenced_code",
82
"tables",
83
"codehilite",
84
"mdx_truly_sane_lists",
85
"smarty",
86
],
87
extension_configs={
88
"codehilite": {
89
"guess_lang": False,
90
},
91
"smarty": {
92
"smart_dashes": True,
93
"smart_quotes": False,
94
"smart_angled_quotes": False,
95
"smart_ellipses": False,
96
},
97
},
98
)
99
100
101
def set_active_flag_in_nav_entry(entry, relative_url):
102
entry = copy.copy(entry)
103
if relative_url.startswith(entry["relative_url"]):
104
entry["active"] = True
105
else:
106
entry["active"] = False
107
children = [
108
set_active_flag_in_nav_entry(child, relative_url)
109
for child in entry.get("children", [])
110
]
111
entry["children"] = children
112
return entry
113
114