#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """OCR the pinned scans that have no text layer into reference/text/ (tesseract). python -I scripts/ocr_scans.py # every PDF in reference/docs whose text layer is empty python -I scripts/ocr_scans.py console-and-pes-technical-data Pages are rendered with `pdftoppm -r 200 -gray` into reference/ocr// (git-ignored, like all of reference/) and read with `tesseract`; the joined text, one "=== page" header per page, goes to reference/text/.txt. Runs under `nice`. OCR text is a reading aid: cite the page image, not the OCR, when a figure or a number matters. """ from __future__ import annotations import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] DOCS = ROOT / "reference" / "docs" TEXT = ROOT / "reference" / "text" WORK = ROOT / "reference" / "ocr" def needs_ocr(pdf: Path) -> bool: text = TEXT / (pdf.stem + ".txt") return not text.exists() or text.stat().st_size < 200 def ocr(pdf: Path) -> None: work = WORK / pdf.stem work.mkdir(parents=True, exist_ok=True) subprocess.run(["nice", "pdftoppm", "-r", "200", "-gray", str(pdf), str(work / "p")], check=True) pages = sorted(work.glob("p-*.pgm")) for page in pages: if not page.with_suffix(".txt").exists(): subprocess.run(["nice", "tesseract", str(page), str(page.with_suffix(""))], check=True, capture_output=True) TEXT.mkdir(parents=True, exist_ok=True) with (TEXT / (pdf.stem + ".txt")).open("w", encoding="utf-8") as out: for page in pages: out.write(f"=== page {page.stem}\n") out.write(page.with_suffix(".txt").read_text(encoding="utf-8", errors="replace")) print(f"{pdf.name}: {len(pages)} pages") def main() -> int: names = sys.argv[1:] pdfs = [DOCS / f"{name}.pdf" for name in names] if names else [ pdf for pdf in sorted(DOCS.glob("*.pdf")) if needs_ocr(pdf)] for pdf in pdfs: ocr(pdf) return 0 if __name__ == "__main__": sys.exit(main())