#!/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"
", "\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'''
Text is extracted from the book. For diagrams, worksheets, or unclear notation, check the original PDF.
Read whole section · Section PDF · Section Markdown
Stephen Hake · Student edition
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
Open a section to browse its lessons and investigation.
{''.join(cards)}Book search
Searches lesson and investigation text in this static edition.