#!/usr/bin/env python3 """Build the self-contained Saxon Math Intermediate 3 static edition.""" from __future__ import annotations import html import json import os import re import shutil from pathlib import Path from urllib.parse import quote import markdown import pymupdf import pymupdf4llm ROOT = Path(__file__).resolve().parent SOURCE = ROOT / "Saxon Math 3.pdf" SITE = ROOT / "site" PDF = SITE / "PDF" MD = SITE / "Markdown" ASSETS = SITE / "assets" INV_TITLES = [ "Pictographs and Bar Graphs", "Working with Money", "More About Pictographs", "Scale Maps", "Probability Games", "Bar Graphs", "Symmetry, Part 1", "More About Geometric Solids", "Symmetry, Part 2", "Evaluating Estimates", "Planning a Design", ] def clean_title(raw: str) -> str: raw = re.sub(r"Lesson\s+\d+\s+\d+", "", raw) raw = re.sub(r"\s*•\s*", " · ", raw).strip(" ·\n ") return re.sub(r"\s+", " ", raw) def discover(book): lessons, investigations = [], [] for zero in range(21, 608): raw = book[zero].get_text()[:450] hit = re.search(r"L\s+E\s+S\s+S\s+O\s+N\s+(.+?)Power\s*Up", raw, re.S) if hit: lessons.append(dict(number=len(lessons) + 1, start=zero, title=clean_title(hit.group(1)))) hit = re.search(r"I\s+N\s+V\s+E\s+S\s+T\s+I\s+G\s+A\s+T\s+I\s+O\s+N", raw) if hit and "Focus on" in raw[:300]: # A few pages repeat the decorative heading; one investigation # begins after each group of ten lessons. if not investigations or investigations[-1]["start"] != zero: investigations.append(dict(number=len(investigations) + 1, start=zero, title=INV_TITLES[len(investigations)])) assert len(lessons) == 110, len(lessons) assert len(investigations) == 11, len(investigations) assert [x["start"] for x in lessons][0] == 27 assert [x["start"] for x in investigations][-1] == 606 units = [dict(kind="front", title="Front matter", start=0, end=21, stem="Front_Matter"), dict(kind="intro", title="Problem Solving Overview", start=21, end=27, stem="Introduction")] for sec in range(1, 12): group = lessons[(sec - 1) * 10:sec * 10] inv = investigations[sec - 1] section_end = lessons[sec * 10]["start"] if sec < 11 else 608 section = dict(kind="section", number=sec, title=f"Section {sec}: Lessons {group[0]['number']}–{group[-1]['number']}", start=group[0]["start"], end=section_end, stem=f"Section_{sec:02d}") units.append(section) for idx, lesson in enumerate(group): lesson_end = group[idx + 1]["start"] if idx < 9 else inv["start"] units.append(dict(kind="lesson", number=lesson["number"], section=sec, title=f"Lesson {lesson['number']}: {lesson['title']}", start=lesson["start"], end=lesson_end, stem=f"Lesson_{lesson['number']:03d}")) units.append(dict(kind="investigation", number=sec, section=sec, title=f"Investigation {sec}: {inv['title']}", start=inv["start"], end=section_end, stem=f"Investigation_{sec:02d}")) units += [dict(kind="back", title="English/Spanish Math Glossary", start=608, end=637, stem="Glossary"), dict(kind="back", title="Index", start=637, end=len(book), stem="Book_Index")] for unit in units: assert unit["start"] < unit["end"] return units def page_label(zero: int) -> str: return str(zero - 20) if zero >= 21 else f"PDF {zero + 1}" def mathml_expression(match: re.Match) -> str: """Mark up unambiguous arithmetic without guessing at broken fractions.""" expression = match.group(0) bits = re.split(r"\s*([+−×÷=<>])\s*", expression) content = "".join( f"{html.escape(bit)}" if bit in "+−×÷=<>" else f"{bit}" for bit in bits if bit ) return f'{content}' MATH_EXPRESSION = re.compile( r"(?]\s*\d+(?:,\d{3})*(?:\.\d+)?){1,4}" r"(?![\w./])" ) def clean_picture_text(match: re.Match) -> str: """Keep meaningful diagram labels, not the parser's HTML comments/noise.""" content = re.sub(r"", "\n", match.group(1), flags=re.I) content = re.sub(r"<[^>]+>", "", content) lines = [re.sub(r"\s+", " ", line).strip() for line in content.splitlines()] lines = [line for line in lines if line] # Dot leaders, lone punctuation, and shape-font debris are not useful text. if sum(c.isalnum() for line in lines for c in line) < 3: return "\n\n" return "\n\n" + " \n".join(lines) + "\n\n" def render_page(raw: str, zero: int) -> str: raw = raw.replace("\x00", "").replace("\ufffd", "") # Drop running page furniture from the PDF, not lesson numbers in content. raw = re.sub(r"(?m)^\*\*(?:\d+|[ivxlcdm]+)\*\*\s+\*\*_Saxon Math_\*\*\s+_Intermediate 3_\s*$", "", raw) raw = re.sub(r"(?m)^\*\*(?:Lesson \d+|Investigation \d+)\s+(?:\d+|[ivxlcdm]+)\*\*\s*$", "", raw) raw = re.sub(r"(?m)^\*\*?(?:Lesson \d+|Investigation \d+|Problem Solving Overview|Glossary|Index|Table of Contents|How to Use Your Textbook|Letter from the Author)\s+\*\*(?:\d+|[ivxlcdm]+)\*\*\s*$", "", raw) raw = re.sub(r"(?m)^(?:Lesson \d+|Investigation \d+|Problem Solving Overview|Glossary|Index|Table of Contents|How to Use Your Textbook|Letter from the Author)\s+\*\*(?:\d+|[ivxlcdm]+)\*\*\s*$", "", raw) if zero < 21: raw = re.sub(r"(?m)^\*\*[ivxlcdm]+\*\*\s*$", "", raw) raw = re.sub(r"(.*?)", clean_picture_text, raw, flags=re.S) raw = re.sub(r"(?m)^#{0,4}\s*\*\*New C\*\*\s*\*\*~~oncepts?~~\*\*\s*$", lambda m: "#### New Concepts" if "oncepts" in m.group().lower() else "#### New Concept", raw) raw = re.sub(r"(?m)^#{0,4}\s*\*\*Power\*\*\s*\*\*~~Up~~\*\*\s*$", "#### Power Up", raw) raw = re.sub(r"(?m)^#{0,4}\s*\*\*Writt\*\*\s*\*\*~~en Practice~~\*\*", "#### Written Practice", raw) raw = raw.replace("~~", "") # false strike-through from ruling lines in the scan raw = re.sub(r"\*\*New C\*\*\s+\*\*oncept(s?)\*\*", lambda m: "New Concept" + m.group(1), raw) raw = raw.replace("**Power** **Up**", "Power Up") raw = raw.replace("**Writt** **en Practice**", "Written Practice") raw = raw.replace("Writt en Practice", "Written Practice") # Some running footers were inside the extractor's picture-text blocks, # so remove them after those blocks have been normalized too. raw = re.sub(r"(?m)^(?:Lesson \d+|Investigation \d+|Glossary|Index|Problem Solving Overview)\s+\*\*\d+\*\*\s*$", "", raw) raw = re.sub(r"(?m)^\*\*\d+\*\*\s+\*\*_Saxon Math_\*\*[^\n]*?3_\s*$", "", raw) # These operators have clear semantics. Leave ambiguous OCR fractions and # diagrams to their extracted figures / source PDF rather than invent math. raw = "\n".join( line if "](" in line or "![" in line else MATH_EXPRESSION.sub(mathml_expression, line) for line in raw.splitlines() ) raw = re.sub(r"\n{4,}", "\n\n\n", raw).strip() return raw + "\n" def rel_url(path: Path, from_dir: Path) -> str: return "/".join(quote(part) for part in Path(os.path.relpath(path, from_dir)).parts) def shell(title, body, prefix="", description=""): esc = html.escape return f''' {esc(title)} · Saxon Math Intermediate 3
{body}
''' def main(): for directory in (PDF, MD, ASSETS): directory.mkdir(parents=True, exist_ok=True) figures = MD / "figures" figures.mkdir(exist_ok=True) book = pymupdf.open(SOURCE) units = discover(book) # The full edition belongs to the deployable site. Hard linking avoids a # second 90 MB allocation locally; copying the site remains self-contained. full = PDF / "Saxon_Math_3_Full.pdf" if not full.exists(): try: os.link(SOURCE, full) except OSError: shutil.copy2(SOURCE, full) print("Extracting Markdown pages...", flush=True) pages = [] for zero in range(len(book)): if zero == 0 or zero == len(book) - 1: # blank cover/back leaf raw = "[Blank page in the source PDF.]" else: raw = pymupdf4llm.to_markdown( book, pages=[zero], show_progress=False, use_ocr=False, write_images=True, image_path=str(figures.resolve()), image_format="png", ) # The extractor writes absolute local paths. Markdown and HTML live # side by side, so a relative figures/ path works for both. raw = raw.replace(str(figures.resolve()) + "/", "figures/") raw = raw.replace(os.path.relpath(figures, Path.cwd()) + "/", "figures/") raw = raw.replace("![](figures/", "![Illustration from the book](figures/") if not raw.strip(): raw = "[No extractable text on this page; consult the PDF.]" pages.append(render_page(raw, zero)) if (zero + 1) % 100 == 0: print(f" {zero + 1}/{len(book)}", flush=True) reading = [u for u in units if u["kind"] != "section"] for n, u in enumerate(units): stem = u["stem"] title = u["title"] page_range = (f"printed pp. {page_label(u['start'])}–{page_label(u['end']-1)}" if u["start"] >= 21 else f"PDF pp. {u['start']+1}–{u['end']}") chunk = "\n\n".join(pages[u["start"]:u["end"]]) intro = f"# {title}\n\n*[Original PDF](../PDF/{stem}.pdf)*\n\n" (MD / f"{stem}.md").write_text(intro + chunk, encoding="utf-8") part = pymupdf.open() part.insert_pdf(book, from_page=u["start"], to_page=u["end"]-1) part.save(PDF / f"{stem}.pdf", garbage=4, deflate=True) part.close() u["page_range"] = page_range u["pdf"] = f"PDF/{stem}.pdf" u["md"] = f"Markdown/{stem}.md" u["html"] = f"Markdown/{stem}.html" crumb = f'Book / ' if "section" in u and u["kind"] != "section": crumb += f'Section {u["section"]} / ' crumb += html.escape(title) nav = "" if u in reading: ri = reading.index(u) for key, neighbor in (("Previous", reading[ri-1] if ri else None), ("Next", reading[ri+1] if ri+1 < len(reading) else None)): if neighbor: nav += f'{key}: {html.escape(neighbor["title"])}' body = f'''

{html.escape(title)}

Text is extracted from the book. For diagrams, worksheets, or unclear notation, check the original PDF.

{markdown.markdown(chunk, extensions=["tables", "fenced_code", "sane_lists"])}
''' (MD / f"{stem}.html").write_text(shell(title, body, "../", title), encoding="utf-8") if (n+1) % 25 == 0: print(f" built {n+1}/{len(units)} sections", flush=True) cards = [] for u in units: if u["kind"] == "section": children = [x for x in units if x.get("section") == u["number"]] links = "".join(f'''
  • {html.escape(x['title'])} PDF · MD
  • ''' for x in children) cards.append(f'''
    {u['number']:02d}{html.escape(u['title'])} 10 lessons + investigation⌄
    ''') def simple(u): return f'''
    {html.escape(u['title'])} PDF · MD
    ''' front = "".join(simple(x) for x in units if x["kind"] in ("front", "intro")) back = "".join(simple(x) for x in units if x["kind"] == "back") home = f'''

    Stephen Hake · Student edition

    Saxon Math Intermediate 3

    Read the complete book by section, lesson, or investigation. Each part has readable HTML, Markdown, and the original PDF pages.

    11 sections · 110 lessons · 11 investigations · 645 source pages

    Before the lessons

    {front}

    Sections & lessons

    Open a section to browse its lessons and investigation.

    {''.join(cards)}

    Reference

    {back}
    ''' (SITE / "index.html").write_text(shell("Book index", home, description="Saxon Math Intermediate 3: all sections, lessons, investigations, PDFs, and Markdown."), encoding="utf-8") md_index = "# Saxon Math Intermediate 3 — Markdown\n\n" for u in units: md_index += f"- [{u['title']}]({u['stem']}.md) · [PDF](../{u['pdf']})\n" (MD / "index.md").write_text(md_index, encoding="utf-8") (MD / "index.html").write_text(shell("Markdown files", f'

    Markdown files

    {markdown.markdown(md_index)}
    ', "../"), encoding="utf-8") search_docs = [] for u in units: if u["kind"] == "section": continue # avoid duplicate full-text matches text = re.sub(r"[#*_`|>\[\]()]", " ", " ".join(pages[u["start"]:u["end"]])) search_docs.append(dict(title=u["title"], url=u["html"], section=u.get("section"), text=re.sub(r"\s+", " ", text)[:40000])) (ASSETS / "search-index.json").write_text(json.dumps(search_docs, ensure_ascii=False), encoding="utf-8") search = '''

    Book search

    Search lessons

    Searches lesson and investigation text in this static edition.

    ''' (SITE / "search.html").write_text(shell("Search", search), encoding="utf-8") print(f"Done: {len(units)} PDF/Markdown/HTML units", flush=True) if __name__ == "__main__": main()