#!/usr/bin/env python3 """Check lesson Markdown, native MathML, image paths, and chapter/lesson parity. Run after editing sources, before or after build.py. This checks rendering structure; it does not certify the mathematical truth of the OCR transcription. """ import json import re import subprocess import sys import xml.etree.ElementTree as ET from pathlib import Path ROOT = Path(__file__).resolve().parent.parent IMAGE = re.compile(r"!\[[^\]]*\]\(([^)]+)\)") MATH = re.compile(r"", re.S) def main(): records = [] for student in sorted((ROOT / "Markdown").glob("Chapter_??_Lesson_??.md")): for folder in ("Markdown", "Teacher_Answers"): source = ROOT / folder / student.name text = source.read_text() errors = [] result = subprocess.run( ["pandoc", "-f", "markdown-implicit_figures", "-t", "html5", "--math-method=mathml", "--wrap=none", str(source)], capture_output=True, text=True, ) if result.returncode or result.stderr: errors.append(result.stderr.strip() or "Pandoc conversion failed") maths = MATH.findall(result.stdout) for math in maths: try: ET.fromstring(math) except ET.ParseError as error: errors.append(f"Invalid MathML: {error}") for target in IMAGE.findall(text): if not (source.parent / target).is_file(): errors.append(f"Missing image: {target}") if "\ufffd" in text: errors.append("Unicode replacement character in source") chapter, lesson = map(int, re.findall(r"\d+", student.stem)) full = (ROOT / folder / f"Chapter_{chapter:02d}.md").read_text() match = re.search(rf"^## Lesson {lesson}\b[^\n]*", full, re.M) if not match: errors.append("Chapter source is missing this lesson heading") else: end = re.search(r"^## Lesson \d+\b", full[match.end():], re.M) stop = match.end() + end.start() if end else len(full) if full[match.start():stop].strip() not in text: errors.append("Lesson copy differs from chapter source") records.append({ "file": str(source.relative_to(ROOT)), "mathml_expressions": len(maths), "image_references": len(IMAGE.findall(text)), "errors": errors, }) print(json.dumps({ "lesson_files": len(records), "mathml_expressions": sum(x["mathml_expressions"] for x in records), "image_references": sum(x["image_references"] for x in records), "errors": sum(len(x["errors"]) for x in records), "results": records, }, indent=2)) return int(any(x["errors"] for x in records)) if __name__ == "__main__": sys.exit(main())