"""Graham 1978 (JNT 10, 83-94) -- rebuild the real page image from the scan strips. Why: the PDF's text layer is OCR *output*, not embedded glyphs (it renders "Academic Press" as "Academic Pray", "log(z2/z1)" as "1% 21", and drops every displayed equation). So the text layer cannot be evidence about a formula. The page raster can. Each page is 18 horizontal 1-bit TIFF strips placed by an explicit `cm` matrix; stacking them in placement order recovers the page. The positioned text layer is used ONLY as a map (which strip band holds the Theorem / Corollary), never as a source of a formula. Usage: python graham-page.py [--crop y0 y1] """ import io import re import sys import pypdf from PIL import Image def page_image(pdf_path, index): r = pypdf.PdfReader(pdf_path) page = r.pages[index] content = page.get_contents().get_data().decode("latin-1") # placement: q 0 0 cm /imN Do Q places = [] for m in re.finditer( r"q\s+([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) cm\s*/(\S+) Do", content, ): a, b, c, d, e, f, name = m.groups() places.append((float(f), name)) imgs = {} for im in page.images: pil = Image.open(io.BytesIO(im.data)) imgs[im.name.lstrip("/").split(".")[0]] = pil.convert("L") # top of the page = largest f places.sort(key=lambda t: -t[0]) width = max(p.width for p in imgs.values()) total = sum(p.height for _, n in places for p in [imgs[n]]) canvas = Image.new("L", (width, total), 255) y = 0 for _, name in places: strip = imgs[name] canvas.paste(strip, (0, y)) y += strip.height return canvas, total def text_lines(pdf_path, index): """y-position (top-down px) of each text fragment, for locating bands only.""" r = pypdf.PdfReader(pdf_path) page = r.pages[index] out = [] def visit(text, cm, tm, font_dict, font_size): t = (text or "").strip() if not t: return # device space: tm is in text space scaled by cm y_pts = cm[5] + tm[5] * cm[3] if cm else tm[5] out.append((round(y_pts, 2), t)) page.extract_text(visitor_text=visit) return out def main(): pdf = sys.argv[1] idx = int(sys.argv[2]) out = sys.argv[3] canvas, total = page_image(pdf, idx) if "--crop" in sys.argv: k = sys.argv.index("--crop") y0, y1 = int(sys.argv[k + 1]), int(sys.argv[k + 2]) canvas = canvas.crop((0, y0, canvas.width, y1)) canvas.save(out) print(f"saved {out} size={canvas.size} page_height_px={total}") # map: which band holds which keyword (band = 151 px, matching the strips) for y_pts, t in text_lines(pdf, idx): if re.search(r"THEOREM|COROLLARY|Barban|log|Lemma", t, re.I): px = int((650 - y_pts) * (1706 / 410.0)) print(f" band {px // 151:2d} y~{px:5d}px {t[:70]!r}") if __name__ == "__main__": main()