-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildsite.py
More file actions
2558 lines (2197 loc) · 75.9 KB
/
buildsite.py
File metadata and controls
2558 lines (2197 loc) · 75.9 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from pathlib import Path
import argparse
import subprocess
import shutil
import re
import json
import fnmatch
import html
import tempfile
from urllib.parse import quote, unquote, urlsplit, urlunsplit, urlencode
from bs4 import BeautifulSoup
PROJECT_TITLE = "ECE 4252/6252 – FunML Lecture Notes"
SCRIPT_ROOT = Path(__file__).resolve().parent
EXCLUDED_TEX_FILENAMES = {"lect1213_extra.tex"}
EXCLUDED_TEX_PATH_PARTIALS = {"lect1213_extra", "funml_l12_l13_ext", "funml_l12_gmmclustering"}
INCLUDEGRAPHICS_WIDTH_SCALE = 0.60
# A few late-semester note titles map to slide decks with different lecture
# numbers than the notes themselves.
MEDIA_KEY_TITLE_OVERRIDES = {
"self-supervised learning": "Lecture26",
"anomaly detection": "Lecture24",
"uncertainty quantification in neural networks": "Lecture27",
"data and label efficient learning - active learning": "Lecture25",
}
# Transformers slides are not currently published in this repo.
SLIDES_DISABLED_TITLE_OVERRIDES = {
"machine learning - transformers",
"machine learning: transformers",
}
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;
}
img {
display: block;
margin: 10px auto;
}
table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
border: 1px solid #cfd7e3;
margin: 12px 0 18px;
background: #fff;
}
th, td {
border: 1px solid #cfd7e3;
padding: 8px 10px;
vertical-align: top;
text-align: left;
word-break: break-word;
}
thead th {
background: #f5f8fc;
}
* {
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;
}
.lecture-tags {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 8px;
margin: 8px 0 18px;
padding: 10px 12px;
border: 1px solid #e2e8f0;
border-radius: 10px;
background: #f8fafc;
}
.lecture-tags-label {
font-weight: 700;
color: #475569;
font-size: 13px;
margin-right: 4px;
}
.lecture-tag {
display: inline-block;
padding: 3px 10px;
border-radius: 999px;
background: #e0e7ff;
color: #3730a3;
font-size: 12.5px;
text-decoration: none;
border: 1px solid #c7d2fe;
white-space: nowrap;
transition: background 0.15s, color 0.15s;
}
.lecture-tag:hover {
background: #6366f1;
color: #fff;
border-color: #6366f1;
}
.lecture-tag.is-active {
background: #4f46e5;
color: #fff;
border-color: #4f46e5;
}
.lecture-handouts {
margin: 32px 0 12px;
padding: 18px 22px;
border: 1px solid #e2e8f0;
border-radius: 12px;
background: #fefce8;
}
.lecture-handouts h2 {
margin: 0 0 12px;
font-size: 18px;
color: #713f12;
}
.lecture-handouts .handout-list {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 8px;
}
.lecture-handouts .handout-list li {
display: flex;
align-items: baseline;
gap: 8px;
font-size: 14px;
}
.lecture-handouts a {
color: #1e3a8a;
text-decoration: none;
}
.lecture-handouts a:hover {
text-decoration: underline;
}
.handout-kind {
display: inline-block;
padding: 1px 7px;
border-radius: 4px;
font-size: 10.5px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
background: #e5e7eb;
color: #374151;
flex-shrink: 0;
}
.handout-kind-paper { background: #fee2e2; color: #991b1b; }
.handout-kind-reading { background: #dbeafe; color: #1e3a8a; }
.handout-kind-video { background: #fce7f3; color: #9d174d; }
.handout-kind-interactive { background: #d1fae5; color: #065f46; }
.handout-kind-dataset { background: #ede9fe; color: #5b21b6; }
.interactive-notebook {
margin: 14px 0 18px;
padding: 12px;
border: 1px solid #d7dfeb;
border-radius: 12px;
background: linear-gradient(180deg, #f9fbff 0%, #f4f7fb 100%);
}
.interactive-notebook h3 {
margin: 0 0 6px;
}
.interactive-notebook p {
margin: 0 0 10px;
color: #334155;
}
.interactive-notebook-frame {
width: 100%;
border: 1px solid #cfd7e3;
border-radius: 10px;
overflow: hidden;
background: #fff;
}
.interactive-notebook-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 10px;
}
.interactive-notebook-link {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 40px;
padding: 0 14px;
border: 1px solid #cbd5e1;
border-radius: 999px;
background: #fff;
color: #0f172a;
text-decoration: none;
font-weight: 600;
}
.interactive-notebook-link:hover,
.interactive-notebook-link:focus-visible {
border-color: #2563eb;
color: #1d4ed8;
}
.notebook-page {
max-width: 980px;
margin: 0 auto;
}
.notebook-page-header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 20px;
}
.notebook-page-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.notebook-page-link {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 40px;
padding: 0 14px;
border: 1px solid #cbd5e1;
border-radius: 999px;
background: #fff;
color: #0f172a;
text-decoration: none;
font-weight: 600;
}
.notebook-page-link:hover,
.notebook-page-link:focus-visible {
border-color: #2563eb;
color: #1d4ed8;
}
.notebook-cell {
margin: 0 0 18px;
border: 1px solid #d7dfeb;
border-radius: 12px;
overflow: hidden;
background: #fff;
}
.notebook-cell-label {
padding: 8px 12px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
color: #475569;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
}
.notebook-cell-body {
padding: 14px 16px;
}
.notebook-code {
margin: 0;
padding: 14px 16px;
overflow-x: auto;
background: #0f172a;
color: #e2e8f0;
font-size: 14px;
line-height: 1.55;
white-space: pre;
}
.notebook-output {
margin: 0;
padding: 14px 16px;
border-top: 1px solid #e2e8f0;
background: #f8fafc;
color: #0f172a;
font-size: 14px;
line-height: 1.55;
white-space: pre-wrap;
}
"""
MATHJAX_CONFIG = """<script>
window.MathJax = {
tex: {
macros: {
R: "\\\\mathbb{R}",
N: "\\\\mathbb{N}",
Z: "\\\\mathbb{Z}",
C: "\\\\mathbb{C}",
E: "\\\\mathbb{E}",
Var: "\\\\operatorname{Var}",
Cov: "\\\\operatorname{Cov}",
Tr: "\\\\operatorname{Tr}",
}
}
};
</script>"""
INTERACTIVE_NOTEBOOK_RESIZE_SCRIPT = """<script>
function setupInteractiveNotebookFrame(frame) {
if (!frame) {
return;
}
const fallbackHeight = Math.max(
420,
parseInt(frame.dataset.defaultHeight || frame.style.height || "0", 10) || 420
);
function measureHeight() {
try {
const doc = frame.contentDocument;
if (!doc) {
return fallbackHeight;
}
const body = doc.body;
const root = doc.documentElement;
const measured = Math.max(
body ? body.scrollHeight : 0,
body ? body.offsetHeight : 0,
root ? root.scrollHeight : 0,
root ? root.offsetHeight : 0
);
return Math.max(420, measured || fallbackHeight);
} catch (_err) {
return fallbackHeight;
}
}
function applyHeight() {
frame.style.height = `${measureHeight()}px`;
}
function watchFrameDocument() {
try {
const doc = frame.contentDocument;
if (!doc || !doc.body) {
return;
}
if (frame.__interactiveResizeObserver) {
frame.__interactiveResizeObserver.disconnect();
}
const observer = new MutationObserver(applyHeight);
observer.observe(doc.body, {
attributes: true,
childList: true,
subtree: true,
});
frame.__interactiveResizeObserver = observer;
frame.contentWindow.addEventListener("resize", applyHeight);
} catch (_err) {
// Ignore cross-document access failures and keep the fallback height.
}
}
frame.addEventListener("load", () => {
applyHeight();
watchFrameDocument();
[120, 400, 900].forEach((delay) => window.setTimeout(applyHeight, delay));
});
if (frame.contentDocument && frame.contentDocument.readyState === "complete") {
applyHeight();
watchFrameDocument();
}
}
window.addEventListener("DOMContentLoaded", () => {
document
.querySelectorAll(".interactive-notebook-frame")
.forEach(setupInteractiveNotebookFrame);
});
</script>"""
LECTURE_TAGS_SCRIPT = """<script>
(function() {
// When a keyword tag is clicked, trigger the parent index page's global
// search box for that keyword so the standard search results dropdown
// appears. Falls back to navigating to ../index.html?q=... if this page
// is opened standalone (not inside the lecture iframe).
document.addEventListener("click", function(e) {
const tag = e.target.closest && e.target.closest(".lecture-tag");
if (!tag) return;
e.preventDefault();
const kw = tag.dataset.keyword || tag.textContent.trim();
if (!kw) return;
let parentDoc = null;
try {
if (window.parent && window.parent !== window) parentDoc = window.parent.document;
} catch (_) { parentDoc = null; }
const input = parentDoc && parentDoc.getElementById("global-search");
if (input) {
input.value = kw;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.focus();
// Mark the active tag for visual feedback
const tagsBox = tag.closest(".lecture-tags");
if (tagsBox) {
const prev = tagsBox.querySelector(".lecture-tag.is-active");
if (prev) prev.classList.remove("is-active");
tag.classList.add("is-active");
}
} else {
// Standalone (no parent search box): fall back to query-string search
window.location.href = "../index.html?q=" + encodeURIComponent(kw);
}
});
})();
</script>"""
def run(cmd):
print(" ".join(cmd))
subprocess.check_call(cmd)
def parse_bibliography_paths(tex_path: Path, tex_text: str):
bibliography_files = []
seen = set()
def add_candidate(path_str: str):
base = path_str.strip()
if not base:
return
candidates = []
raw_path = Path(base)
if raw_path.is_absolute():
candidates.append(raw_path)
else:
candidates.append(tex_path.parent / raw_path)
candidates.append(Path(base))
if raw_path.suffix.lower() != ".bib":
if raw_path.is_absolute():
candidates.append(Path(f"{base}.bib"))
else:
candidates.append(tex_path.parent / f"{base}.bib")
candidates.append(Path(f"{base}.bib"))
for candidate in candidates:
resolved = candidate.resolve()
if resolved.exists() and resolved not in seen:
seen.add(resolved)
bibliography_files.append(resolved)
return
for m in re.finditer(r"\\bibliography\{([^}]*)\}", tex_text):
for item in m.group(1).split(","):
add_candidate(item)
for m in re.finditer(r"\\addbibresource\{([^}]*)\}", tex_text):
add_candidate(m.group(1))
default_bib = (tex_path.parent / "references.bib").resolve()
if default_bib.exists() and default_bib not in seen:
seen.add(default_bib)
bibliography_files.append(default_bib)
return bibliography_files
def extract_inline_bib_entries(tex_text: str):
entries = []
ranges = []
for m in re.finditer(r"(?m)^[ \t]*@[A-Za-z][A-Za-z0-9_-]*\s*\{", tex_text):
start = m.start()
i = tex_text.find("{", start)
if i < 0:
continue
depth = 0
end = None
for j in range(i, len(tex_text)):
ch = tex_text[j]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
end = j + 1
break
if end is None:
continue
entries.append(tex_text[start:end].strip())
ranges.append((start, end))
if not ranges:
return tex_text, entries
chunks = []
prev = 0
for start, end in ranges:
chunks.append(tex_text[prev:start])
prev = end
chunks.append(tex_text[prev:])
cleaned = "".join(chunks)
return cleaned, entries
def sanitize_tex_for_citeproc(tex_text: str):
tex_text = re.sub(
r"(?m)^[ \t]*\\renewcommand\s*\{\\cite\}\s*(\[[^\]]*\])?\s*\{.*\}\s*$\n?",
"",
tex_text,
)
tex_text = re.sub(r"(?m)^[ \t]*\\bibliographystyle\{[^}]*\}\s*$\n?", "", tex_text)
tex_text = re.sub(r"(?m)^[ \t]*\\bibliography\{[^}]*\}\s*$\n?", "", tex_text)
tex_text = re.sub(r"(?m)^[ \t]*\\addbibresource\{[^}]*\}\s*$\n?", "", tex_text)
return tex_text
def normalize_fquote_blocks(tex_text: str):
# Replace custom fquote macro usage with portable LaTeX so pandoc renders
# quotes cleanly (avoids stray macro artifacts in output).
pattern = re.compile(
r"\\begin\{fquote\}(?:\[([^\]]*)\])?(?:\[([^\]]*)\])?\s*(.*?)\s*\\end\{fquote\}",
re.DOTALL,
)
def repl(match):
author = (match.group(1) or "").strip()
role = (match.group(2) or "").strip()
quote_body = match.group(3).strip()
footer = ""
if author and role:
footer = f" --- {author} ({role})"
elif author:
footer = f" --- {author}"
elif role:
footer = f" ({role})"
return f"\\begin{{quote}}\\textit{{{quote_body}}}{footer}\\end{{quote}}"
return pattern.sub(repl, tex_text)
def normalize_shortstack_blocks(tex_text: str):
# Pandoc may misinterpret \shortstack line breaks inside tabular cells and
# emit extra HTML table rows. Flatten stacked cell content into plain text
# so each LaTeX table cell stays a single HTML cell.
pattern = re.compile(r"\\shortstack\{([^{}]*)\}")
def repl(match):
content = match.group(1)
content = content.replace("\\\\", " ")
content = re.sub(r"\s+", " ", content).strip()
return content
return pattern.sub(repl, tex_text)
def extract_includegraphics_widths(tex_text: str):
# Extract width intents from LaTeX includegraphics commands so generated HTML
# can respect source sizing.
width_by_path = {}
width_by_basename = {}
pattern = re.compile(r"\\includegraphics(?:\s*\[([^\]]*)\])?\s*\{([^}]*)\}")
for match in pattern.finditer(tex_text):
options = (match.group(1) or "").strip()
raw_path = (match.group(2) or "").strip()
if not raw_path:
continue
width_pct = None
width_match = re.search(
r"width\s*=\s*([0-9]*\.?[0-9]+)\s*\\(?:line|text)width",
options,
re.IGNORECASE,
)
if width_match:
try:
width_pct = max(1.0, min(100.0, float(width_match.group(1)) * 100.0))
except ValueError:
width_pct = None
elif re.search(r"width\s*=\s*\\(?:line|text)width", options, re.IGNORECASE):
width_pct = 100.0
if width_pct is None:
continue
normalized = raw_path.replace("\\", "/").strip()
if normalized.startswith("./"):
normalized = normalized[2:]
normalized_key = unquote(normalized).lower()
basename_key = Path(normalized_key).name
width_by_path.setdefault(normalized_key, width_pct)
if basename_key:
width_by_basename.setdefault(basename_key, width_pct)
return width_by_path, width_by_basename
def normalize_backtick_quotes(text: str):
# Normalize LaTeX-style and mixed quote artifacts left after pandoc.
normalized = text
patterns = [
(r"``([^`<]+?)''", r"“\1”"),
(r"``([^`<]+?)\"", r"“\1”"),
(r"``([^`<]+?)”", r"“\1”"),
(r"``([^`<]+?)’’", r"“\1”"),
(r"“([^”\"<]+?)\"", r"“\1”"),
(r"“([^”<]+?)''", r"“\1”"),
(r"“([^”<]+?)’’", r"“\1”"),
]
for pattern, replacement in patterns:
normalized = re.sub(pattern, replacement, normalized)
return normalized
def normalize_course_numbers(text: str):
return re.sub(r"\b8803\b", "6252", text)
def extract_command_argument(text: str, command: str):
pattern = re.compile(rf"\\{re.escape(command)}\s*\{{", re.IGNORECASE)
match = pattern.search(text)
if not match:
return ""
brace_start = text.find("{", match.start())
if brace_start < 0:
return ""
depth = 0
for idx in range(brace_start, len(text)):
ch = text[idx]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return text[brace_start + 1:idx].strip()
return ""
def clean_title_candidate(raw_title: str):
title = (raw_title or "").strip()
if not title:
return ""
title = title.replace(r"\&", "&")
title = title.replace("\n", " ")
title = re.sub(r"\\\\(\[[^\]]*\])?", " ", title)
title = re.sub(r"\\(?:vspace|hspace)\*?\{[^{}]*\}", " ", title, flags=re.IGNORECASE)
prev = None
while prev != title:
prev = title
title = re.sub(
r"\\[A-Za-z@]+\*?(?:\[[^\]]*\])?\{([^{}]*)\}",
r"\1",
title,
)
title = re.sub(r"\\[A-Za-z@]+\*?", " ", title)
title = title.replace("{", " ").replace("}", " ")
title = re.sub(r"\[[^\]]*\]", " ", title)
title = title.replace("---", " - ").replace("--", " - ")
title = re.sub(r"\s+", " ", title).strip(" -:\t")
lecture_suffix = re.search(r"Lecture\s+\d+\s*[:\-]\s*(.+)", title, re.IGNORECASE)
if lecture_suffix:
suffix = lecture_suffix.group(1).strip(" -:\t")
if suffix:
title = suffix
if title.lower() in {"lecture title", "title"}:
return ""
if not re.search(r"[A-Za-z]{3,}", title):
return ""
return title
# Match "Module Name N: Subtitle" where N is a roman numeral. Used to keep
# the parsed (module, numeral, subtitle) data while rendering only the
# subtitle in the lecture page title and sidebar.
MODULE_TITLE_PAT = re.compile(
r"^\s*(?P<module>.+?)\s+(?P<numeral>I|II|III|IV|V|VI|VII|VIII|IX|X)\s*:\s*(?P<subtitle>.+?)\s*$"
)
ROMAN_TO_INT = {
"I": 1, "II": 2, "III": 3, "IV": 4, "V": 5,
"VI": 6, "VII": 7, "VIII": 8, "IX": 9, "X": 10,
}
def parse_module_title(title: str):
"""Return (module, numeral, position, subtitle) when title matches the
"Module Name N: Subtitle" pattern, else None."""
if not title:
return None
m = MODULE_TITLE_PAT.match(title)
if not m:
return None
numeral = m.group("numeral")
return (m.group("module").strip(), numeral, ROMAN_TO_INT[numeral], m.group("subtitle").strip())
def display_title(title: str):
"""Strip the 'Module N: ' prefix when present, returning only the subtitle.
Lecture pages, the sidebar, and filenames all use this short form so the
reader is not shown the module/numeral noise."""
parsed = parse_module_title(title)
return parsed[3] if parsed else title
def extract_title(tex_path):
text = normalize_course_numbers(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*\}"
)
for m in lecture_macro.finditer(text):
title = clean_title_candidate(m.group(2))
if title:
return display_title(title)
latex_title = clean_title_candidate(extract_command_argument(text, "title"))
if latex_title:
return display_title(latex_title)
header_title = clean_title_candidate(extract_command_argument(text, "lhead"))
if header_title:
return display_title(header_title)
m = re.search(r"Lecture\s+\d+[:\-]?\s*(.*)", text)
if m:
fallback = clean_title_candidate(m.group(0))
if fallback:
return display_title(fallback)
directory_fallback = clean_title_candidate(tex_path.parent.name.replace("_", " "))
if directory_fallback:
return directory_fallback
return tex_path.stem
def slugify_lecture_title(title: str):
# Produce filesystem-safe names from lecture titles.
clean = title.replace(r"\&", "and").replace("&", "and")
clean = re.sub(r"[^A-Za-z0-9]+", "-", clean)
clean = re.sub(r"-+", "-", clean).strip("-")
return clean or "Untitled"
def lecture_tex_filename(out_html_name: str):
return f"{Path(out_html_name).stem}.tex"
def normalize_lookup_text(value: str):
normalized = (value or "").strip().lower()
normalized = normalized.replace("–", "-").replace("—", "-")
normalized = re.sub(r"\s+", " ", normalized)
return normalized
def lecture_number_from_dir(lec_dir: Path):
name = lec_dir.name
for pattern in (r"funml[_-]?l\s*(\d+)", r"lecture\s*(\d+)"):
m = re.search(pattern, name, re.IGNORECASE)
if m:
return m.group(1)
return ""
def resolve_media_key(title: str, lecture_number: str, display_idx: int):
title_key = normalize_lookup_text(title)
override = MEDIA_KEY_TITLE_OVERRIDES.get(title_key)
if override:
return override
return f"Lecture{lecture_number}" if lecture_number else f"Lecture{display_idx}"
def slides_disabled_for_title(title: str):
return normalize_lookup_text(title) in SLIDES_DISABLED_TITLE_OVERRIDES
def lecture_dir_sort_key(lec_dir: Path):
num = lecture_number_from_dir(lec_dir)
if num:
return (0, int(num), lec_dir.name.lower())
return (1, 0, lec_dir.name.lower())
def is_excluded_tex_file(tex_path: Path):
lowered_name = tex_path.name.lower()
if lowered_name in EXCLUDED_TEX_FILENAMES:
return True
lowered_path = tex_path.as_posix().lower()
return any(fragment in lowered_path for fragment in EXCLUDED_TEX_PATH_PARTIALS)
def is_candidate_lecture_dir(lec_dir: Path):
name = lec_dir.name.lower()
patterns = (
r"^lecture\d+",
r"^lecturexx",
r"^funml[_-]?l\d+",
)
return any(re.search(pattern, name) for pattern in patterns)
def discover_lecture_dirs(src_root: Path):
discovered = {}
for tex_path in src_root.rglob("*.tex"):
try:
rel_parent = tex_path.parent.relative_to(src_root)
except ValueError:
continue
if len(rel_parent.parts) > 2:
continue
if any(part.lower() == "img" for part in rel_parent.parts):
continue
lec_dir = tex_path.parent
if not is_candidate_lecture_dir(lec_dir):
continue
discovered[lec_dir.resolve()] = lec_dir
return sorted(discovered.values(), key=lecture_dir_sort_key)
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 pick_preferred_lecture_tex(tex_files, lecture_number: str):
webpage_tex_files = [tex for tex in tex_files if "webpage" in tex.stem.lower()]
if webpage_tex_files:
return pick_main_tex(webpage_tex_files, lecture_number)
return pick_main_tex(tex_files, lecture_number)
def ensure_landing_page_assets(out_root: Path):
# If output is a fresh directory, seed it with the portal landing files.
for filename in ("index.html", "styles.css", "script.js"):
target = out_root / filename
if target.exists():
continue
source = SCRIPT_ROOT / filename
if source.exists():
shutil.copy2(source, target)
def build_single_html(
tex: Path,
out_html_path: Path,
out_root: Path,
src_root: Path,
title: str,
source_tex_name: str,
notebook_rules,
notebooks_dir: Path,
notebook_view_mode: str,
):
tex_text = normalize_course_numbers(tex.read_text(errors="ignore"))
includegraphics_width_by_path, includegraphics_width_by_basename = extract_includegraphics_widths(tex_text)
bibliography_files = parse_bibliography_paths(tex, tex_text)
tex_text, inline_bib_entries = extract_inline_bib_entries(tex_text)
tex_text = sanitize_tex_for_citeproc(tex_text)
tex_text = normalize_fquote_blocks(tex_text)
tex_text = normalize_shortstack_blocks(tex_text)
has_citations = bool(re.search(r"\\cite[a-zA-Z*]*\{", tex_text))
if has_citations and not bibliography_files and not inline_bib_entries:
print(f"Warning: {tex.name} contains citations but no .bib source was found.")
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"
tmp_bib = None
if inline_bib_entries:
tmp_bib = out_root / f"_{out_html_path.stem}.bib"
tmp_bib.write_text("\n\n".join(inline_bib_entries) + "\n")
bibliography_files.append(tmp_bib.resolve())
cmd = [
"pandoc",
str(tmp_tex),
"--mathjax",
"--from=latex",
"--to=html5",
"--number-sections",
"-o", str(tmp_html),
]
if bibliography_files:
cmd.extend(["--citeproc", "-M", "reference-section-title=References"])
for bib in bibliography_files:
cmd.extend(["--bibliography", str(bib)])
run(cmd)
body = tmp_html.read_text(errors="ignore")
body = normalize_backtick_quotes(body)