-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildsite.py
More file actions
379 lines (319 loc) · 9.08 KB
/
buildsite.py
File metadata and controls
379 lines (319 loc) · 9.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
from pathlib import Path
import argparse
import subprocess
import shutil
import re
from bs4 import BeautifulSoup
PROJECT_TITLE = "ECE 4252/6252 – FunML Lecture Notes"
CSS = """
html, body {
margin: 0;
padding: 0;
width: 100%;
overflow-x: hidden;
}
body {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
line-height: 1.5;
overflow-wrap: anywhere;
}
main {
width: 100%;
max-width: none;
padding: 20px 24px;
margin: 0;
overflow-x: hidden;
box-sizing: border-box;
}
h1, h2, h3 {
line-height: 1.25;
}
nav {
background: #f6f8fa;
padding: 12px 16px;
border-bottom: 1px solid #ddd;
}
nav a {
margin-right: 12px;
text-decoration: none;
font-weight: 500;
}
img, video, svg, canvas, iframe, embed, object {
max-width: 100%;
height: auto;
}
table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
}
th, td {
word-break: break-word;
}
* {
box-sizing: border-box;
max-width: 100%;
}
pre, code {
white-space: pre-wrap;
word-break: break-word;
}
.math.display, .MathJax_Display {
max-width: 100%;
overflow: hidden;
}
"""
def run(cmd):
print(" ".join(cmd))
subprocess.check_call(cmd)
def extract_title(tex_path):
text = tex_path.read_text(errors="ignore")
# Prefer the title from \lecture{N}{Title}{...}{...} and skip template placeholders.
lecture_macro = re.compile(
r"\\lecture\{\s*([^}]*)\s*\}\{\s*([^}]*)\s*\}\{\s*([^}]*)\s*\}\{\s*([^}]*)\s*\}"
)
candidates = []
for m in lecture_macro.finditer(text):
title = m.group(2).strip()
if not title:
continue
if title.lower() == "lecture title":
continue
title = title.replace(r"\&", "&")
candidates.append(title)
if candidates:
return candidates[0]
m = re.search(r"Lecture\s+\d+[:\-]?\s*(.*)", text)
if m:
return m.group(0).strip()
return tex_path.stem
def lecture_number_from_dir(lec_dir: Path):
m = re.search(r"lecture\s*(\d+)", lec_dir.name, re.IGNORECASE)
return m.group(1) if m else ""
def pick_main_tex(tex_files, lecture_number: str):
def score(tex_path: Path):
name = tex_path.stem.lower()
points = 0
if "in-class" in name or "exercise" in name or "solution" in name:
points -= 100
if "add-on" in name or "addon" in name:
points -= 60
if name == "main":
points += 60
if lecture_number:
if f"lecture{lecture_number}" in name:
points += 40
if re.search(rf"\bl{lecture_number}\b", name):
points += 35
if f"l{lecture_number}_" in name:
points += 35
if "notes" in name:
points += 20
if "template" in name:
points += 10
return points
return sorted(tex_files, key=lambda p: (-score(p), p.name.lower()))[0]
def build_single_html(tex: Path, out_html_path: Path, out_root: Path, title: str):
tex_text = tex.read_text(errors="ignore")
tex_text = re.sub(r"\{\\bf\s+([^}]+)\}", r"\\textbf{\1}", tex_text)
tmp_tex = out_root / f"_{out_html_path.stem}.tex"
tmp_tex.write_text(tex_text)
tmp_html = out_root / f"_{out_html_path.stem}.html"
run([
"pandoc",
str(tmp_tex),
"--mathjax",
"--from=latex",
"--to=html5",
"--number-sections",
"--shift-heading-level-by=1",
"--number-offset=1",
"-o", str(tmp_html),
])
body = tmp_html.read_text(errors="ignore")
body, qanda_html = clean_lecture_body(body)
final_html = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>{title}</title>
<link rel="stylesheet" href="../assets/style.css"/>
<script defer src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
</head>
<body>
<main>
{body}
</main>
</body>
</html>
"""
out_html_path.write_text(final_html)
tmp_html.unlink()
tmp_tex.unlink()
return qanda_html
def clean_lecture_body(body_html: str):
soup = BeautifulSoup(body_html, "html.parser")
# Normalize local asset paths so spaces/special chars don't break on hosting.
for tag in soup.find_all(src=True):
src = tag.get("src", "")
if src and "://" not in src:
tag["src"] = src.replace(" ", "%20")
for tag in soup.find_all(href=True):
href = tag.get("href", "")
if href and "://" not in href:
tag["href"] = href.replace(" ", "%20")
# Remove repeated boilerplate block that appears at the top of many lectures.
boilerplate_keys = {
"contributors:",
"teaching assistants",
"disclaimer",
"license",
"errata",
}
for p in soup.find_all("p"):
strong = p.find("strong")
if not strong:
continue
key = strong.get_text(" ", strip=True).strip().lower()
if any(key.startswith(k) for k in boilerplate_keys):
p.decompose()
# Extract Q&A sections to publish them in Exercises instead of each lecture.
qanda_sections = []
for sec in soup.find_all("section"):
sec_id = (sec.get("id") or "").lower()
heading = sec.find(re.compile(r"^h[1-6]$"))
heading_text = heading.get_text(" ", strip=True).lower() if heading else ""
if "qanda" in sec_id or "q&a" in heading_text or "q and a" in heading_text:
qanda_sections.append(str(sec))
sec.decompose()
return str(soup), qanda_sections
def build_site(src_root: Path, out_root: Path, write_index: bool):
lectures_out = out_root / "lectures"
assets_out = out_root / "assets"
exercises_out = assets_out / "exercises"
lectures_out.mkdir(parents=True, exist_ok=True)
assets_out.mkdir(parents=True, exist_ok=True)
exercises_out.mkdir(parents=True, exist_ok=True)
# CSS for lecture pages
(assets_out / "style.css").write_text(CSS)
# Copy images
img_dir = src_root / "img"
if img_dir.exists():
shutil.copytree(img_dir, lectures_out / "img", dirs_exist_ok=True)
lecture_pages = []
qanda_entries = []
qanda_by_lecture = {}
# Ensure in-class exercise artifacts are not published.
for old in lectures_out.glob("*_exercise*.html"):
old.unlink()
for lec_dir in sorted(src_root.glob("Lecture*")):
if not lec_dir.is_dir():
continue
tex_files = list(lec_dir.glob("*.tex"))
if not tex_files:
continue
lecture_number = lecture_number_from_dir(lec_dir)
tex = pick_main_tex(tex_files, lecture_number)
title = extract_title(tex)
out_html = f"{lec_dir.name}.html"
qanda_sections = build_single_html(tex, lectures_out / out_html, out_root, title)
qanda_by_lecture[lec_dir.name] = qanda_sections
if qanda_sections:
qanda_entries.append((lec_dir.name, title, qanda_sections))
lecture_pages.append((title, out_html))
# Build a shared Exercises page using all extracted Q&A sections.
if qanda_entries:
qanda_blocks = []
for lecture_name, lecture_title, sections in qanda_entries:
section_html = "\n".join(sections)
qanda_blocks.append(
f"<section><h2>{lecture_name} - {lecture_title}</h2>{section_html}</section>"
)
exercises_body = "\n".join(qanda_blocks)
else:
exercises_body = "<p>No Q&A sections are currently available.</p>"
exercises_html = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>FunML Exercises (Q&A)</title>
<link rel="stylesheet" href="style.css"/>
<script defer src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
</head>
<body>
<main>
{exercises_body}
</main>
</body>
</html>
"""
(assets_out / "exercises.html").write_text(exercises_html)
# Build one exercises page per lecture so each lecture maps to its own Q&A.
for lecture_title, out_html in lecture_pages:
lecture_key = Path(out_html).stem
sections = qanda_by_lecture.get(lecture_key, [])
body = "\n".join(sections) if sections else "<p>No exercises posted for this lecture yet.</p>"
single_exercises_html = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Exercises</title>
<link rel="stylesheet" href="../style.css"/>
<script defer src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
</head>
<body>
<main>
{body}
</main>
</body>
</html>
"""
(exercises_out / f"{lecture_key}.html").write_text(single_exercises_html)
if write_index:
links = "\\n".join(
f'<li><a href="lectures/{f}">{t}</a></li>'
for t, f in lecture_pages
)
index_html = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>{PROJECT_TITLE}</title>
<link rel="stylesheet" href="assets/style.css"/>
</head>
<body>
<main>
<h1>{PROJECT_TITLE}</h1>
<ul>
{links}
</ul>
</main>
</body>
</html>
"""
(out_root / "index.html").write_text(index_html)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--src",
default="source/raw",
help="Path to extracted lecture source (default: source/raw)",
)
parser.add_argument(
"--out",
default=".",
help="Output root for the website (default: current dir)",
)
parser.add_argument(
"--write-index",
action="store_true",
help="Also generate index.html (off by default to avoid overwriting)",
)
args = parser.parse_args()
src_root = Path(args.src).resolve()
out_root = Path(args.out).resolve()
build_site(src_root, out_root, args.write_index)
print("✔ Lectures built → open lectures/*.html")
if __name__ == "__main__":
main()