# SPDX-License-Identifier: MIT """Fetch the pinned references into reference/ (git-ignored), or check them. python -I scripts/fetch_references.py # download what is missing python -I scripts/fetch_references.py --verify # check sizes and SHA-256s only python -I scripts/fetch_references.py --ocr # also OCR scanned PDFs (ocrmypdf, slow) Every entry of scripts/pinned_files.json names a URL, a SHA-256 and a size. A file is kept only if its hash matches; a mismatch is moved to trash/ (never deleted) and reported. Downloads use plain curl under its own name: a site that refuses that is not worked around (docs/sources.md). Nothing fetched is executed. An entry with "extract" is a RAR archive unpacked (by unrar) beside itself. After a download each PDF is turned into text (`pdftotext -layout`) under reference/text/; a scanned PDF with no text layer gets an OCR sidecar there with --ocr. """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PINS = ROOT / "scripts" / "pinned_files.json" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def check(entry: dict) -> str: path = ROOT / entry["path"] if not path.exists(): return "missing" if path.stat().st_size != entry["size"] or sha256(path) != entry["sha256"]: return "mismatch" return "ok" def set_aside(path: Path) -> None: trash = ROOT / "trash" / time.strftime("%Y%m%d-%H%M%S") trash.mkdir(parents=True, exist_ok=True) shutil.move(str(path), trash / path.name) def fetch(entry: dict) -> str: path = ROOT / entry["path"] path.parent.mkdir(parents=True, exist_ok=True) part = path.with_suffix(path.suffix + ".part") subprocess.run(["curl", "-sS", "-L", "--fail", "-m", "900", "-o", str(part), entry["url"]], check=True) part.replace(path) state = check(entry) if state != "ok": set_aside(path) return state def unpack(entry: dict) -> None: path = ROOT / entry["path"] target = path.with_suffix("") if entry.get("extract") and not target.exists() and shutil.which("unrar"): target.mkdir(parents=True) subprocess.run(["unrar", "x", "-idq", "-o-", str(path), str(target) + "/"], check=False) def pdfs(entry: dict) -> list[Path]: path = ROOT / entry["path"] if entry.get("extract"): return sorted(path.with_suffix("").rglob("*.pdf")) return [path] if path.suffix == ".pdf" else [] def to_text(entry: dict, ocr: bool) -> None: for pdf in pdfs(entry): text = ROOT / "reference" / "text" / (pdf.stem + ".txt") text.parent.mkdir(parents=True, exist_ok=True) if not text.exists() and shutil.which("pdftotext"): subprocess.run(["pdftotext", "-layout", str(pdf), str(text)], check=False) scanned = text.exists() and text.stat().st_size < 64 * max(1, pdf.stat().st_size // 200_000) if ocr and scanned and shutil.which("ocrmypdf"): out = ROOT / "reference" / "ocr" / pdf.name out.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["nice", "ocrmypdf", "-q", "-j", "2", "--force-ocr", "--sidecar", str(text), str(pdf), str(out)], check=False) # fmt: skip def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="check only, download nothing") parser.add_argument("--ocr", action="store_true", help="OCR scanned PDFs after download") args = parser.parse_args() entries = json.loads(PINS.read_text(encoding="utf-8")) bad = 0 for entry in entries: state = check(entry) if state == "mismatch" and not args.verify: set_aside(ROOT / entry["path"]) state = "missing" if state == "missing" and not args.verify: state = fetch(entry) if state == "ok" and not args.verify: unpack(entry) to_text(entry, args.ocr) bad += state != "ok" print(f"{state:8} {entry['path']}") print(f"{bad} problem(s) among {len(entries)} pinned files") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())