#!/usr/bin/env python3 """Make plain-text copies of the fetched PDFs under reference/docs/text/. The January 1989 Information Manual has a text layer (pdftotext is enough). The data sheet, its addendum and the application notes are scans without one: each page is rendered at 200 dpi and read by tesseract, one thread, niced (the machine is shared). Appendix A's format diagrams are pictures in every copy: render the page and look at it (``pdftoppm -r 80 -f 174 -l 176 -png``). python -I scripts/ocr_reference.py # every PDF without a text copy python -I scripts/ocr_reference.py NAME.pdf # one of them Needs poppler-utils and tesseract. Output is git-ignored with the rest of reference/. """ from __future__ import annotations import os import subprocess import sys from pathlib import Path DOCS = Path(__file__).resolve().parents[1] / "reference" / "docs" TEXT = DOCS / "text" NICE = ["nice", "-n", "19"] def text_copy(pdf: Path) -> None: target = TEXT / (pdf.stem + ".txt") if target.exists() and target.stat().st_size: print(f"ok: {target.name}") return TEXT.mkdir(parents=True, exist_ok=True) subprocess.run([*NICE, "pdftotext", "-layout", str(pdf), str(target)], check=True) if target.stat().st_size > 2000: print(f"text layer: {target.name}") return pages = TEXT / (pdf.stem + ".pages") pages.mkdir(exist_ok=True) subprocess.run( [*NICE, "pdftoppm", "-r", "200", "-gray", "-png", str(pdf), str(pages / "p")], check=True ) environment = dict(os.environ, OMP_THREAD_LIMIT="1") parts = [] for image in sorted(pages.glob("p-*.png")): subprocess.run( [*NICE, "tesseract", str(image), str(image.with_suffix("")), "--psm", "6"], check=True, capture_output=True, env=environment, ) parts.append(f"\f[{image.stem}]\n" + image.with_suffix(".txt").read_text(encoding="utf-8")) target.write_text("".join(parts), encoding="utf-8") print(f"ocr: {target.name} ({len(parts)} pages)") def main() -> int: names = sys.argv[1:] pdfs = [DOCS / name for name in names] if names else sorted(DOCS.glob("*.pdf")) for pdf in pdfs: text_copy(pdf) return 0 if __name__ == "__main__": sys.exit(main())