Repository Public MIT Research preview
1#!/usr/bin/env python32"""Static and post-build checks of the LaTeX decks (sessions at status draft or beyond).34Static: \\input targets, figure sources, citation keys, bibliography fields, session setup vs metadata,5French frame titles, no raster \\includegraphics, shared macros defined.6Post-build (when dist/build/SXX/slides/SXX.log exists): no errors, no undefined references or citations,7no missing glyphs, no font fallback, no vertical overflow, plausible page count.8"""9from __future__ import annotations1011import argparse12import re13import sys1415from atlaslib import DIST_DIR, ROOT, Report, expand_inputs, load_course, load_yaml, select_sessions, session_dir1617REQUIRED_MACROS = ["AtlasTitleSlide", "AtlasSection", "AtlasConcept", "AtlasDefinition", "AtlasDiagram",18 "AtlasDemo", "AtlasCode", "AtlasCompare", "AtlasQuiz", "AtlasWarning", "AtlasTakeaway",19 "AtlasReferences", "AtlasClosingSlide", "AtlasRoadmap", "AtlasTriple", "AtlasTerminal"]20ENGLISH_TITLE = re.compile(r"\b(the|and|what|how|with|your|overview|summary|introduction to|takeaways?|"21 r"references|outline|agenda|questions\?)\b", re.I)222324def check_macros(rep: Report) -> None:25 src = "".join(p.read_text(encoding="utf-8") for p in (ROOT / "latex").rglob("*") if p.suffix in {".sty", ".tex", ".cls"})26 for m in REQUIRED_MACROS:27 if not re.search(r"\{\\?%s\}|\\%s\b" % (m, m), src):28 rep.error(f"latex/: shared macro or environment {m} is not defined")293031def check_session(s: dict, rep: Report) -> None:32 d = session_dir(s)33 sid = s["id"]34 main = d / "slides" / "main.tex"35 if not main.exists():36 rep.error(f"{sid}: slides/main.tex missing")37 return38 raw = main.read_text(encoding="utf-8")39 for target in re.findall(r"\\input\{(sections/[^}]+)\}", raw):40 if not (main.parent / target).with_suffix(".tex").exists():41 rep.error(f"{sid}: broken \\input{{{target}}}")42 tex = expand_inputs(main)43 if "\\documentclass{atlas-beamer}" not in tex.replace(" ", ""):44 rep.error(f"{sid}: deck must use \\documentclass{{atlas-beamer}}")45 m = re.search(r"\\AtlasSessionSetup\{([^}]*)\}\{([^}]*)\}\{([^}]*)\}\s*\{([^}]*)\}", tex)46 meta = load_yaml(d / "metadata.yaml")47 if not m:48 rep.error(f"{sid}: \\AtlasSessionSetup missing")49 else:50 if m.group(1) != sid or m.group(2) != meta["part"] or m.group(4).strip() != meta["title"]:51 rep.error(f"{sid}: \\AtlasSessionSetup (id/part/title) disagrees with metadata.yaml")52 for _id, stem in re.findall(r"\\AtlasDiagram(?:\[[^\]]*\])?\{([^}]*)\}\{([^}]*)\}", tex):53 local = d / "figures" / "src" / f"{stem}.tex"54 shared = ROOT / "assets" / "shared-diagrams" / f"{stem}.tex"55 if not local.exists() and not shared.exists():56 rep.error(f"{sid}: figure source {stem}.tex not found")57 if not stem.startswith(_id):58 rep.error(f"{sid}: figure ID {_id} does not match source file {stem}")59 if re.search(r"\\includegraphics", tex):60 rep.error(f"{sid}: \\includegraphics found — figures must be \\AtlasDiagram from editable source "61 "(third-party screenshots need an explicit, documented exception)")62 bib = (d / "slides" / "references.bib").read_text(encoding="utf-8") if (d / "slides" / "references.bib").exists() else ""63 entries = dict(re.findall(r"@\w+\{([^,]+),(.*?)\n\}", bib, flags=re.S))64 cited = {k.strip() for grp in re.findall(r"\\(?:no)?cite\{([^}]*)\}", tex) for k in grp.split(",")}65 for key in sorted(cited - set(entries)):66 rep.error(f"{sid}: citation {key} has no entry in references.bib")67 for key in sorted(set(entries) - cited):68 rep.warn(f"{sid}: bibliography entry {key} is never cited")69 for key, body in entries.items():70 for fld in ("url", "urldate", "year", "title"):71 if not re.search(rf"\b{fld}\s*=", body):72 rep.error(f"{sid}: bibliography entry {key} lacks {fld}")73 for title in re.findall(r"\\begin\{frame\}(?:\[[^\]]*\])?\{([^}]*)\}", tex):74 if ENGLISH_TITLE.search(title):75 rep.error(f"{sid}: frame title looks English: {title!r}")76 sizes = [float(x) for x in re.findall(r"\\fontsize\{([\d.]+)\}", tex)]77 if any(x < 7 for x in sizes):78 rep.error(f"{sid}: \\fontsize below 7 pt in deck source (≈ 15 pt projected)")79 if re.search(r"\\(tiny|scriptsize)\b", tex):80 rep.error(f"{sid}: \\tiny or \\scriptsize used in deck source; use the Atlas type scale")8182 log = DIST_DIR / "build" / sid / "slides" / f"{sid}.log"83 if not log.exists():84 rep.warn(f"{sid}: no build log — run `make slides SESSION={sid}` for post-build checks")85 return86 text = log.read_text(encoding="utf-8", errors="replace")87 if re.search(r"^! |Fatal error", text, flags=re.M):88 rep.error(f"{sid}: LaTeX errors in build log")89 for kind, pat in (("undefined reference/citation", r"(?:Reference|Citation) `[^']+' .*undefined"),90 ("missing glyph", r"Missing character:"), ("font fallback", r"Latin Modern fallback")):91 n = len(re.findall(pat, text))92 if n:93 rep.error(f"{sid}: {n} × {kind} in build log")94 vboxes = [float(x) for x in re.findall(r"Overfull \\vbox \(([\d.]+)pt too high\)", text)]95 if vboxes:96 rep.error(f"{sid}: {len(vboxes)} slide(s) overflow vertically (max {max(vboxes):.1f} pt)")97 hboxes = [float(x) for x in re.findall(r"Overfull \\hbox \(([\d.]+)pt too wide\)", text)]98 wide = [x for x in hboxes if x > 3]99 if wide:100 rep.error(f"{sid}: {len(wide)} horizontal overflow(s) above 3 pt (max {max(wide):.1f} pt)")101 rep.note(f"{sid}: build log clean — {len(hboxes)} hbox ≤ 3 pt, 0 vbox")102103104def main() -> int:105 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)106 ap.add_argument("--session")107 args = ap.parse_args()108 rep = Report("latex")109 check_macros(rep)110 for s in select_sessions(load_course(), args.session):111 check_session(s, rep)112 return rep.finish()113114115if __name__ == "__main__":116 sys.exit(main())117