#!/usr/bin/env python3 """Build Markdown chapter files from the scanned Teacher's Guide answers. Pipeline per page: 1. render the PDF page at 300 dpi; 2. OCR it with Tesseract (TSV, so every word has a box); 3. rebuild the two-column reading order from the boxes; 4. find diagram regions (ink outside the text boxes) and crop them; 5. split the text by chapter banners and write Teacher_Answers/Chapter_NN.md. The OCR is intentionally left close to the scan: formulas and symbols are not rewritten, and every page links back to the PDF for checking. Usage: python3 site_builder/extract_teacher_answers.py # all pages python3 site_builder/extract_teacher_answers.py --pages 1-8 """ from __future__ import annotations import argparse import csv import os import re import shutil import subprocess import sys import tempfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np from PIL import Image from scipy import ndimage ROOT = Path(__file__).resolve().parent.parent PDF = ROOT / "Other" / "Teacher's Guide_Answers.pdf" OUT = ROOT / "Teacher_Answers" FIGURES = OUT / "figures" HEADER_FRACTION = 0.06 DPI = 200 SCALE = DPI / 300.0 # --------------------------------------------------------------------------- # OCR helpers # --------------------------------------------------------------------------- def run(cmd: list[str]) -> None: proc = subprocess.run(cmd, capture_output=True, text=True, env={**os.environ, "OMP_THREAD_LIMIT": "1"}) if proc.returncode != 0: raise RuntimeError(f"{cmd[0]} failed: {proc.stderr.strip()}") def ocr_tsv(image: Path, base: Path, psm: str = "1") -> list[dict]: run(["tesseract", str(image), str(base), "--psm", psm, "tsv"]) with open(base.with_suffix(".tsv"), newline="", encoding="utf-8") as handle: return list(csv.DictReader(handle, delimiter="\t", quoting=csv.QUOTE_NONE)) def detect_gutter(gray: np.ndarray) -> int | None: """Find the white valley between the two text columns.""" height, width = gray.shape ink = (gray < 180).sum(axis=0) low, high = int(width * 0.36), int(width * 0.64) band = ink[low:high] gutter = low + int(np.argmin(band)) if band.min() > height * 0.02: return None return gutter def ocr_columns(image: Image.Image, gray: np.ndarray, base: Path) -> list[dict]: """OCR left and right columns separately so the reading order is exact.""" gutter = detect_gutter(gray) if gutter is None: return ocr_tsv(base.with_suffix(".png"), base, "3") height, width = gray.shape rows: list[dict] = [] for index, (x0, x1) in enumerate(((0, gutter + 8), (gutter - 8, width))): crop = base.with_name(f"{base.name}-c{index}.png") image.crop((x0, 0, x1, height)).save(crop) for row in ocr_tsv(crop, base.with_name(f"{base.name}-c{index}"), "4"): row["left"] = str(int(row["left"]) + x0) # Keep the two columns' block numbering apart so their lines do # not get merged when the rows are combined. row["block_num"] = str(int(row["block_num"]) + index * 1000) rows.append(row) return rows def normalize_heading(text: str) -> str: """Repair the small OCR slips that matter for chapter/lesson detection.""" text = text.replace("1O", "10").replace("1o", "10").replace("l0", "10").replace("IO", "10") text = re.sub(r"\b(Lesson|Chapter)(\d)", r"\1 \2", text) return re.sub(r"\s+", " ", text).strip() def normalize_section(text: str) -> str | None: match = re.search(r"(Algebra\s+Review|Review|Lesson\s*[0-9sSgG&lI|oO]+)", text) if not match: return None section = match.group(1) if section in ("Review", "Algebra Review"): return section digits = re.sub(r"^Lesson\s*", "", section) mapping = {"s": "5", "S": "5", "g": "9", "G": "9", "&": "6", "l": "1", "I": "1", "|": "1", "o": "0", "O": "0"} number = "".join(mapping.get(char, char) for char in digits if char.isdigit() or char in mapping) if not number.isdigit(): return None return f"Lesson {int(number)}" def parse_header(text: str) -> tuple[int | None, str | None]: match = re.search(r"Chapter\s+(\d+)\s*,\s*(.+)", text) if not match: return None, None return int(match.group(1)), normalize_section(match.group(2)) def build_lines(rows: list[dict], width: int, height: int) -> list[dict]: grouped: dict[tuple[int, int, int], dict] = {} for row in rows: if row["level"] != "5" or not row["text"].strip(): continue key = (int(row["block_num"]), int(row["par_num"]), int(row["line_num"])) line = grouped.setdefault( key, {"x0": 10**9, "y0": 10**9, "x1": 0, "y1": 0, "words": [], "word_boxes": [], "block": key[0], "par": key[1]}, ) x, y, w, h = map(int, (row["left"], row["top"], row["width"], row["height"])) line["x0"] = min(line["x0"], x) line["y0"] = min(line["y0"], y) line["x1"] = max(line["x1"], x + w) line["y1"] = max(line["y1"], y + h) line["words"].append((x, row["text"])) line["word_boxes"].append((x, y, w, h, row["text"])) lines = [] for line in grouped.values(): line["text"] = " ".join(text for _, text in sorted(line["words"])) line["col"] = 0 if (line["x0"] + line["x1"]) / 2 < width / 2 else 1 line["head_text"] = normalize_heading(line["text"]) line["banner"] = bool(re.match(r"^Chapter\s+\d+\s*,", line["head_text"])) # A page header includes a page number; a section banner does not. stripped = re.sub(r"Chapter\s+\d+\s*,", " ", line["head_text"]) stripped = re.sub(r"\b(?:Lesson\s+\d+|Algebra\s+Review|Review)\b", " ", stripped) numbered = bool(re.search(r"\d", stripped)) line["header"] = ( line["y1"] < height * HEADER_FRACTION and (numbered or not line["banner"]) ) lines.append(line) lines.sort(key=lambda l: (l["col"], l["y0"], l["x0"])) return lines # --------------------------------------------------------------------------- # Diagrams # --------------------------------------------------------------------------- def find_figures(gray: np.ndarray, lines: list[dict]) -> list[dict]: height, width = gray.shape ink = gray < 180 text = np.zeros_like(ink) for line in lines: if line["header"]: continue text[ max(0, line["y0"] - 5):line["y1"] + 5, max(0, line["x0"] - 5):line["x1"] + 5, ] = True figure_ink = ink & ~text figure_ink[:120, :] = False figure_ink[-60:, :] = False figure_ink[:, :60] = False figure_ink[:, -60:] = False labels, count = ndimage.label(figure_ink, np.ones((3, 3))) sizes = ndimage.sum(figure_ink, labels, range(1, count + 1)) objects = ndimage.find_objects(labels) boxes = [] for index, slc in enumerate(objects, 1): if slc is None: continue y0, y1 = slc[0].start, slc[0].stop x0, x1 = slc[1].start, slc[1].stop area = sizes[index - 1] w, h = x1 - x0, y1 - y0 if area < 1500 * SCALE * SCALE or w < 55 * SCALE or h < 45 * SCALE: continue if area / (w * h) > 0.55: # solid bars, banner backgrounds continue boxes.append([x0, y0, x1, y1]) changed = True while changed: changed = False merged = [] while boxes: box = boxes.pop() for other in boxes: if not ( box[2] + 25 * SCALE < other[0] or other[2] + 25 * SCALE < box[0] or box[3] + 25 * SCALE < other[1] or other[3] + 25 * SCALE < box[1] ): other[0] = min(other[0], box[0]) other[1] = min(other[1], box[1]) other[2] = max(other[2], box[2]) other[3] = max(other[3], box[3]) changed = True break else: merged.append(box) boxes = merged # Diagrams are labelled with short text (A, B, 60°, ...) that Tesseract # treats as text and that the ink mask therefore removes. Grow each box to # include nearby short labels so the crops are not decapitated. def include_labels(box): x0, y0, x1, y1 = box for line in lines: if line["header"]: continue for wx, wy, ww, wh, text in line.get("word_boxes", []): if ( wx + ww < x0 - 70 * SCALE or wx > x1 + 70 * SCALE or wy + wh < y0 - 70 * SCALE or wy > y1 + 70 * SCALE ): continue text = text.strip() if ( 0 < len(text) <= 3 and not text.endswith((".", ",", ";", ":")) and re.fullmatch(r"[A-Za-z0-9°'′]+", text) ): x0 = min(x0, wx) y0 = min(y0, wy) x1 = max(x1, wx + ww) y1 = max(y1, wy + wh) return [x0, y0, x1, y1] def text_coverage(box, lines): x0, y0, x1, y1 = box area = (x1 - x0) * (y1 - y0) covered = 0 for line in lines: if line["header"]: continue ix0, iy0 = max(x0, line["x0"]), max(y0, line["y0"]) ix1, iy1 = min(x1, line["x1"]), min(y1, line["y1"]) if ix1 > ix0 and iy1 > iy0: covered += (ix1 - ix0) * (iy1 - iy0) return covered / area if area else 0 figures = [] for box in boxes: x0, y0, x1, y1 = include_labels(box) w, h = x1 - x0, y1 - y0 # A crop mostly covered by text is a layout false positive, not a diagram. if text_coverage((x0, y0, x1, y1), lines) > 0.15: continue if w < 60 * SCALE or h < 45 * SCALE or w * h < 5000 * SCALE * SCALE: continue if w / h > 10 or h / w > 10: continue if w > 0.92 * width and h > 0.92 * height: continue figures.append( { "x0": x0, "y0": y0, "x1": x1, "y1": y1, "col": 0 if (x0 + x1) / 2 < width / 2 else 1, } ) figures.sort(key=lambda f: (f["col"], f["y0"], f["x0"])) return figures # --------------------------------------------------------------------------- # Page -> blocks # --------------------------------------------------------------------------- NUMBERED = re.compile(r"^[^\w]*\d{1,3}\s*[.)]\s+") def is_numbered(text: str) -> bool: return bool(NUMBERED.match(text)) def split_paragraphs(group: list[dict]) -> list[list[dict]]: """Split a Tesseract paragraph when several numbered answers share it.""" paragraphs: list[list[dict]] = [] current: list[dict] = [] for line in group: if current and is_numbered(line["text"]): paragraphs.append(current) current = [] if current and line["y0"] - current[-1]["y1"] > 34: paragraphs.append(current) current = [] current.append(line) if current: paragraphs.append(current) return paragraphs def page_blocks(lines: list[dict], figures: list[dict]) -> list[dict]: blocks: list[dict] = [] for col in (0, 1): col_lines = [line for line in lines if not line["header"] and line["col"] == col] col_figs = [figure for figure in figures if figure["col"] == col] items = [("line", line) for line in col_lines] + [("fig", figure) for figure in col_figs] if not items: continue items.sort(key=lambda item: (item[1]["y0"], item[1]["x0"])) group: list[dict] = [] def flush() -> None: if not group: return pars: dict[tuple[int, int], list[dict]] = {} for line in group: pars.setdefault((line["block"], line["par"]), []).append(line) for key in sorted(pars, key=lambda k: min(l["y0"] for l in pars[k])): for paragraph in split_paragraphs(pars[key]): blocks.append({"kind": "para", "lines": paragraph}) group.clear() for kind, obj in items: if kind == "fig": flush() blocks.append({"kind": "fig", "obj": obj}) elif obj["banner"]: flush() blocks.append({"kind": "heading", "obj": obj}) else: group.append(obj) flush() return blocks # --------------------------------------------------------------------------- # Text cleanup # --------------------------------------------------------------------------- def clean_paragraph(lines: list[dict]) -> str: text = "" for index, line in enumerate(lines): piece = line["text"].strip() if index and text.endswith("-") and piece[:1].islower(): text = text[:-1] + piece else: text = (text + " " + piece).strip() return re.sub(r"\s+", " ", text) def markdown_paragraph(text: str) -> str: text = re.sub(r"^(\*)(\d+)\.", r"\\\1\2\\.", text) text = re.sub(r"^([^\w*]*)(\d+)\.", r"\1\2\\.", text) return text def banner_heading(text: str) -> str: text = normalize_heading(text) section = normalize_section(text) if section: return section return re.sub(r"^Chapter\s+\d+\s*,\s*", "", text).strip() def section_heading(text: str) -> str | None: if re.match(r"^Set\s+[IVX1l|]+\s*\(page", text): text = re.sub(r"^Set\s*\|", "Set I", text) text = re.sub(r"^Set\s+(?:Il|1l|I1)\b", "Set II", text) return text return None # --------------------------------------------------------------------------- # Per-page processing # --------------------------------------------------------------------------- def process_page(number: int, image_path: Path, tmp: Path) -> dict: base = tmp / f"page-{number:03d}" image = Image.open(image_path).convert("RGB") gray = np.array(image.convert("L")) height, width = gray.shape rows = ocr_columns(image, gray, base) lines = build_lines(rows, width, height) header = " ".join(line["head_text"] for line in lines if line["header"]) chapter, section = parse_header(header) figures = find_figures(gray, lines) for index, figure in enumerate(figures, 1): pad = int(45 * SCALE) crop = image.crop( ( max(0, figure["x0"] - pad), max(0, figure["y0"] - pad), min(image.width, figure["x1"] + pad), min(image.height, figure["y1"] + pad), ) ) name = f"tg_p{number:03d}_f{index}.jpg" crop.save(FIGURES / name, quality=88, optimize=True) figure["name"] = name return { "page": number, "chapter": chapter, "section": section, "blocks": page_blocks(lines, figures), } # --------------------------------------------------------------------------- # Assembly # --------------------------------------------------------------------------- def page_marker(number: int) -> str: return ( f'
' f'p. {number}
' ) def assemble(pages: list[dict], topics: dict[int, str], total_pages: int) -> None: bodies: dict[int, list[str]] = {} ranges: dict[int, list[int]] = {} current: int | None = None seen: dict[int, set[str]] = {} def add_heading(chapter: int, text: str) -> None: text = text.strip() if not text or text in seen.setdefault(chapter, set()): return seen[chapter].add(text) bodies.setdefault(chapter, []).append("## " + text) for page in sorted(pages, key=lambda p: p["page"]): current = page["chapter"] or current or 1 marker_done = False # Running heads repeat the current lesson on every page; add the # heading the first time that lesson appears, then de-duplicate. section = page["section"] if section and section not in seen.get(current, set()): bodies.setdefault(current, []).append(page_marker(page["page"])) add_heading(current, section) marker_done = True for block in page["blocks"]: if block["kind"] == "heading": found = re.search(r"Chapter\s+(\d+)", block["obj"]["head_text"]) if found: current = int(found.group(1)) if not marker_done: bodies.setdefault(current, []).append(page_marker(page["page"])) marker_done = True add_heading(current, banner_heading(block["obj"]["head_text"])) continue if not marker_done: bodies.setdefault(current, []).append(page_marker(page["page"])) marker_done = True if block["kind"] == "fig": figure = block["obj"] bodies.setdefault(current, []).append( f"![Diagram from page {page['page']}](figures/{figure['name']})\n\n" f"*Diagram from page {page['page']}.*" ) continue text = clean_paragraph(block["lines"]) if not text or text.upper() == "ANSWERS TO EXERCISES": continue heading = section_heading(text) if heading: bodies.setdefault(current, []).append("### " + heading) else: bodies.setdefault(current, []).append(markdown_paragraph(text)) ranges.setdefault(current, []).append(page["page"]) previous_page_chapter = page["chapter"] or previous_page_chapter OUT.mkdir(exist_ok=True) for number, blocks in sorted(bodies.items()): title = topics.get(number, f"Chapter {number}") pages_for_chapter = ranges.get(number, []) first = min(pages_for_chapter) if pages_for_chapter else 0 last = max(pages_for_chapter) if pages_for_chapter else 0 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. Each " "page number links to the original PDF page for checking.", "", f"Back to [Chapter {number}](../Markdown/Chapter_{number:02d}.md) · " f"[Selected answers](../Answers/Chapter_{number:02d}_Answers.html) · " "[Teacher’s answers PDF](../Other/Teacher's%20Guide_Answers.pdf)", "", ] (OUT / f"Chapter_{number:02d}.md").write_text( "\n".join(preamble) + "\n\n" + "\n\n".join(blocks) + "\n", encoding="utf-8" ) rows = [] for number in sorted(bodies): title = topics.get(number, "") count = len(ranges.get(number, [])) rows.append(f"| {number} | {title} | {count} | [Open](Chapter_{number:02d}.md) |") 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; the page links go to the original PDF so any answer " "can be checked.", "", f"The source is [Teacher's Guide_Answers.pdf](../Other/Teacher's%20Guide_Answers.pdf) " f"({total_pages} pages).", "", "See also: [Selected answers](../Answers/index.md) · " "[Textbook](../Markdown/index.md) · " "[Study guides](../Study_Guides/index.md).", "", "## Chapters", "", "| Chapter | Topic | Pages | Answers |", "|---|---|---|---|", *rows, "", "## Source", "", "Generated by `site_builder/extract_teacher_answers.py`.", "", ] ) (OUT / "README.md").write_text(readme, encoding="utf-8") # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def chapter_topics() -> dict[int, str]: text = (ROOT / "Markdown" / "README.md").read_text(encoding="utf-8") topics = {} for line in text.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() return topics def parse_pages(value: str | None, total: int) -> list[int]: if not value: return list(range(1, total + 1)) if "-" in value: first, last = value.split("-", 1) return list(range(int(first), int(last) + 1)) return [int(value)] def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--pages", help="page range, e.g. 1-8") parser.add_argument("--jobs", type=int, default=min(6, os.cpu_count() or 4)) args = parser.parse_args() if not PDF.exists(): sys.stderr.write(f"missing {PDF}\n") return 1 if not shutil.which("tesseract") or not shutil.which("pdftoppm"): sys.stderr.write("tesseract and poppler-utils (pdftoppm) are required\n") return 1 info = subprocess.run(["pdfinfo", str(PDF)], capture_output=True, text=True).stdout total = int(re.search(r"^Pages:\s+(\d+)", info, re.M).group(1)) pages = parse_pages(args.pages, total) OUT.mkdir(exist_ok=True) FIGURES.mkdir(exist_ok=True) for old in FIGURES.glob("*.jpg"): old.unlink() tmp = Path(tempfile.mkdtemp(prefix="teacher-answers-")) try: print(f"• rendering {len(pages)} pages at {DPI} dpi") run( [ "pdftoppm", "-r", str(DPI), "-png", "-f", str(min(pages)), "-l", str(max(pages)), str(PDF), str(tmp / "page"), ] ) images = { int(re.search(r"page-(\d+)", path.name).group(1)): path for path in tmp.glob("page-*.png") } print(f"• OCR + layout ({args.jobs} jobs)") with ThreadPoolExecutor(max_workers=args.jobs) as pool: results = list(pool.map(lambda n: process_page(n, images[n], tmp), pages)) print("• writing Markdown") assemble(results, chapter_topics(), total) finally: shutil.rmtree(tmp, ignore_errors=True) print(f"• done: {OUT}") return 0 if __name__ == "__main__": raise SystemExit(main())