# SPDX-License-Identifier: MIT """OCR the image-only pinned PDFs into reference/text/.txt (page by page). nice taskset -c 24-31 python -I scripts/ocr_references.py [stem ...] Toshiba's TLCS-900/H CPU book chapters and the 900/900L/900H differences book are scans (CCITT stencils, no text layer), so `pdftotext` returns nothing. This renders each page with `pdftoppm` (300 dpi, grey) and runs `tesseract` on it, one process at a time, writing a form feed between pages so page numbers can be counted. Output is for grepping only; every fact cited from it is checked against the page image. """ from __future__ import annotations import json import os import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def ocr(pdf: Path, out: Path) -> None: pages = int(next(line.split()[1] for line in subprocess.run( ["pdfinfo", str(pdf)], capture_output=True, text=True, check=True).stdout.splitlines() if line.startswith("Pages:"))) # fmt: skip env = dict(os.environ, OMP_THREAD_LIMIT="1") chunks = [] with tempfile.TemporaryDirectory(dir=ROOT / "reference") as tmp: for page in range(1, pages + 1): stem = Path(tmp) / f"p{page}" subprocess.run(["pdftoppm", "-r", "300", "-gray", "-f", str(page), "-l", str(page), "-singlefile", "-png", str(pdf), str(stem)], check=True) # fmt: skip text = subprocess.run(["tesseract", f"{stem}.png", "-", "--psm", "6"], capture_output=True, text=True, env=env, check=False).stdout # fmt: skip chunks.append(f"=== page {page} ===\n{text}") Path(f"{stem}.png").unlink() out.write_text("\f".join(chunks), encoding="utf-8") def main() -> int: entries = json.loads((ROOT / "scripts" / "pinned_files.json").read_text(encoding="utf-8")) wanted = set(sys.argv[1:]) for entry in entries: if not entry.get("ocr"): continue pdf = ROOT / entry["path"] if wanted and pdf.stem not in wanted: continue out = ROOT / "reference" / "text" / (pdf.stem + ".txt") # pdftotext leaves only form feeds for an image-only PDF: that counts as empty. if out.exists() and len(out.read_text(encoding="utf-8", errors="replace").split()) > 100: continue print(f"ocr {pdf.name}", flush=True) out.parent.mkdir(parents=True, exist_ok=True) ocr(pdf, out) return 0 if __name__ == "__main__": sys.exit(main())