#!/usr/bin/env python3 """Use the clean appendix answers for an Algebra Review when they are complete. The teacher's guide Algebra Reviews are formula-heavy and OCR badly. The appendix's selected answers for the same review are clean LaTeX. Replace the OCR section only when the clean set covers every numbered exercise; otherwise leave the (complete, if rough) OCR text in place. """ from __future__ import annotations import re from pathlib import Path ROOT = Path(__file__).resolve().parent.parent TEACHER = ROOT / "Teacher_Answers" ANSWERS = ROOT / "Answers" BOOK = ROOT / "Markdown" def section(text: str) -> str | None: match = re.search(r"^## Algebra Review.*$", text, re.M) if not match: return None following = re.search(r"^## ", text[match.end():], re.M) end = match.end() + following.start() if following else len(text) return text[match.start():end].rstrip() + "\n" def answer_numbers(text: str) -> set[int]: body = section(text) if not body: return set() return {int(n) for n in re.findall(r"^\*\*(\d+)\.\*\*", body, re.M)} def question_numbers(chapter: str) -> set[int]: path = BOOK / f"Chapter_{chapter}.md" if not path.exists(): return set() text = path.read_text(encoding="utf-8") start = re.search(r"^## Algebra Review.*$", text, re.M) if not start: return set() exercises = re.search(r"^## Exercises\s*$", text[start.end():], re.M) if not exercises: return set() tail = text[start.end() + exercises.end():] end = re.search(r"^## ", tail, re.M) if end: tail = tail[:end.start()] return {int(n) for n in re.findall(r"^(\d+)\.\s+\$", tail, re.M)} def main() -> int: for teacher_path in sorted(TEACHER.glob("Chapter_*.md")): chapter = re.search(r"Chapter_(\d+)", teacher_path.name).group(1) answers_path = ANSWERS / f"Chapter_{chapter}_Answers.md" if not answers_path.exists(): continue questions = question_numbers(chapter) answers = answer_numbers(answers_path.read_text(encoding="utf-8")) if not questions or not answers or not questions.issubset(answers): print(f"Chapter {chapter}: skipped ({len(answers)}/{len(questions)} answers)") continue teacher_text = teacher_path.read_text(encoding="utf-8") old = section(teacher_text) clean = section(answers_path.read_text(encoding="utf-8")) if not old or not clean: continue teacher_path.write_text(teacher_text.replace(old, clean), encoding="utf-8") print(f"Chapter {chapter}: replaced with clean answers ({len(questions)})") return 0 if __name__ == "__main__": raise SystemExit(main())