#!/usr/bin/env python3 """Re-group Teacher_Answers pages using the PDF's own running heads. The scanned images' OCR occasionally misreads a chapter header, but the PDF's text layer has clean running heads ("56 Chapter 5, Lesson 1"). This script reads those heads, reassembles the per-chapter Markdown from the existing page sections, and writes fresh lesson headings and index counts. """ from __future__ import annotations import re import subprocess from pathlib import Path ROOT = Path(__file__).resolve().parent.parent ANSWERS = ROOT / "Teacher_Answers" PDF = ROOT / "Other" / "Teacher's Guide_Answers.pdf" PAGE_RE = re.compile(r'(

.*?

)') HEAD_RE = re.compile( r"Chapter\s+(\d+)\s*,\s*(Lesson\s*\d{1,2}\b|Algebra\s+Review|Review)" ) SET_RE = re.compile(r"\(page[s]?\s*(\d+)", re.S) def book_map() -> dict[int, tuple[int, str]]: mapping: dict[int, tuple[int, str]] = {} for path in sorted((ROOT / "Markdown").glob("Chapter_*.md")): number = int(re.search(r"Chapter_(\d+)", path.name).group(1)) page = None section = "" for line in path.read_text(encoding="utf-8").splitlines(): marker = re.match(r"", line) if marker: page = int(marker.group(1)) mapping.setdefault(page, (number, section)) continue heading = re.match( r"^## (Lesson \d+|Summary and Review|Review|Algebra Review)", line ) if heading and page: section = heading.group(1) if section in ("Summary and Review", "Review"): section = "Review" elif section.startswith("Lesson"): section = "Lesson " + section.split()[1] mapping[page] = (number, section) return mapping def pdf_headers() -> dict[int, str]: text = subprocess.run( ["pdftotext", "-layout", str(PDF), "-"], capture_output=True, text=True ).stdout headers = {} for number, page in enumerate(text.split("\f"), 1): lines = [line.strip() for line in page.splitlines() if line.strip()][:3] headers[number] = " ".join(lines) return headers def normalize_section(value: str) -> str | None: match = re.search(r"(Lesson\s*\d{1,2}\b|Algebra\s+Review|Review)", value) if not match: return None section = match.group(1) if section in ("Review", "Algebra Review"): return section number = re.search(r"\d+", section) return f"Lesson {int(number.group())}" if number else None def split_pages(path: Path) -> list[dict]: text = path.read_text(encoding="utf-8") parts = PAGE_RE.split(text) pages = [] for index in range(1, len(parts), 3): content = parts[index + 2] content = "\n".join( line for line in content.splitlines() if not line.startswith("## ") ) pages.append( { "number": int(parts[index + 1]), "marker": parts[index], "content": content.strip("\n"), } ) return pages def main() -> int: headers = pdf_headers() mapping = book_map() pages = [] for path in sorted(ANSWERS.glob("Chapter_*.md")): pages.extend(split_pages(path)) # De-duplicate by page number, preferring the copy with the most text. unique: dict[int, dict] = {} for page in pages: old = unique.get(page["number"]) if old is None or len(page["content"]) > len(old["content"]): unique[page["number"]] = page pages = [unique[number] for number in sorted(unique)] if not pages: print("no page markers found; this copy is already realigned") return 0 previous_chapter = previous_section = None for page in pages: header = headers.get(page["number"], "") found = HEAD_RE.search(header) chapter = int(found.group(1)) if found else None section = normalize_section(found.group(2)) if found else None quoted = [int(n) for n in SET_RE.findall(page["content"])] # The quoted textbook pages identify the lesson more reliably than a # running head that may lag a page behind. for value in quoted: if value in mapping: if chapter is None: chapter = mapping[value][0] if section is None: section = mapping[value][1] break if chapter is None: chapter = previous_chapter or 1 if section is None: if chapter != previous_chapter: section = "Lesson 1" else: section = previous_section or "Lesson 1" page["chapter"], page["section"] = chapter, section previous_chapter, previous_section = chapter, section topics = {} for line in (ROOT / "Markdown" / "README.md").read_text(encoding="utf-8").splitlines(): match = re.match( r"\|\s*\[Chapter_(\d+)\.md\]\([^)]+\)\s*\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|", line, ) if match: topics[int(match.group(1))] = match.group(3).strip() bodies: dict[int, list[str]] = {} seen: dict[int, set[str]] = {} last_lesson: dict[int, int] = {} def add_heading(chapter: int, section: str) -> None: if not section or section in seen.setdefault(chapter, set()): return if section.startswith("Lesson"): number = int(section.split()[1]) # Lessons run in order; an out-of-sequence quote is an OCR slip. if number != last_lesson.get(chapter, 0) + 1: return last_lesson[chapter] = number seen[chapter].add(section) bodies.setdefault(chapter, []).append("## " + section) current = pages[0]["chapter"] bodies.setdefault(current, []) for page in pages: if page["chapter"] != current: current = page["chapter"] bodies.setdefault(current, []) add_heading(current, page["section"]) bodies[current].append(page["marker"]) for line in page["content"].splitlines(): if line.startswith("### Set"): value = SET_RE.search(line) if value: target = mapping.get(int(value.group(1))) if target: add_heading(current, target[1]) bodies[current].append(line) for number, blocks in sorted(bodies.items()): title = topics.get(number, f"Chapter {number}") preamble = [ f"# Chapter {number} — Teacher’s Guide Answers", "", f"Answers and teaching commentary for **Chapter {number}: {title}**, " "transcribed from the scanned *Teacher’s Guide*. Diagrams are cropped " "from the same page scans.", "", "> **OCR note.** The text was recognized automatically and has not been " "corrected line by line; formulas and symbols may be imperfect. Check " "the original PDF for exact wording.", "", f"**Homework:** [Chapter {number} exercises](../Markdown/Chapter_{number:02d}.md) · " f"[Selected answers](../Answers/Chapter_{number:02d}_Answers.html) · " "[Teacher’s answers PDF](../Other/Teacher's%20Guide_Answers.pdf)", "", ] text = "\n".join(preamble) + "\n" + "\n\n".join(blocks) + "\n" # The answers read as one list; printed page numbers are not content. text = re.sub(r'

\s*', "", text) text = re.sub(r"\n{3,}", "\n\n", text) (ANSWERS / f"Chapter_{number:02d}.md").write_text(text, encoding="utf-8") old = ANSWERS / "Chapter_00.md" if old.exists(): old.unlink() counts = {number: sum(1 for page in pages if page["chapter"] == number) for number in bodies} rows = [ f"| {number} | {topics.get(number, '')} | " f"[Chapter](../Markdown/Chapter_{number:02d}.md) · " f"[Answers](Chapter_{number:02d}.md) |" for number in sorted(bodies) ] readme = "\n".join( [ "# Teacher’s Guide — Answers", "", "The complete answers to the exercises, with the teacher’s commentary, " "transcribed from the scanned *Teacher’s Guide* and split one page per " "chapter. Diagrams are cropped from the scans.", "", "> **OCR note.** This is machine-recognized text. Formulas and symbols " "may be imperfect; check the original PDF for exact wording.", "", "The source is [Teacher's Guide_Answers.pdf](../Other/Teacher's%20Guide_Answers.pdf) " "(288 pages).", "", "See also: [Selected answers](../Answers/index.md) · " "[Textbook](../Markdown/index.md) · " "[Study guides](../Study_Guides/index.md).", "", "## Chapters", "", "| Chapter | Topic | Homework & answers |", "|---|---|---|", *rows, "", "## Source", "", "Generated by `site_builder/extract_teacher_answers.py` and grouped with " "`site_builder/realign_teacher_answers.py`.", "", ] ) (ANSWERS / "README.md").write_text(readme, encoding="utf-8") print("chapters:", {number: counts[number] for number in sorted(bodies)}) return 0 if __name__ == "__main__": raise SystemExit(main())