Files
gloamxun eb2cb561bd Add a reproducible TeX fidelity benchmark
Add scripts/tex-fidelity.py: page count, normalized word-sequence similarity and
per-page ink bounds from a 72 dpi grayscale render, using only the stdlib and
Poppler. Document the current arXiv score (0.848 word ratio, 3 pages) and its
limits.

Test count stays 1078.
2026-10-28 00:50:37 +08:00

145 lines
4.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Compare a TeX-produced PDF with a route-D PDF.
This is intentionally dependency-free (stdlib + poppler commands) so it can run
in the same Fedora/WSL environment as the engine:
python3 scripts/tex-fidelity.py --reference tex.pdf --candidate route.pdf
It reports page count, word-sequence similarity and per-page ink bounds. It is
a coarse regression signal, not a pixel-perfect visual diff.
"""
from __future__ import annotations
import argparse
import difflib
import json
import re
import subprocess
import tempfile
from pathlib import Path
def run(*args: str) -> bytes:
return subprocess.run(args, check=True, capture_output=True).stdout
def page_count(pdf: Path) -> int:
text = run("pdfinfo", str(pdf)).decode("utf-8", "replace")
match = re.search(r"^Pages:\s+(\d+)", text, re.MULTILINE)
return int(match.group(1)) if match else 0
def words(pdf: Path) -> list[str]:
text = run("pdftotext", "-layout", str(pdf), "-").decode("utf-8", "replace")
return re.findall(r"[A-Za-z0-9']+", text.lower())
def pgm(path: Path) -> tuple[int, int, bytes]:
data = path.read_bytes()
if not data.startswith(b"P5"):
raise ValueError(f"{path}: expected binary PGM")
fields: list[bytes] = []
index = 2
while len(fields) < 3:
while index < len(data) and data[index] in b" \t\r\n":
index += 1
if data[index : index + 1] == b"#":
index = data.index(b"\n", index) + 1
continue
start = index
while index < len(data) and data[index] not in b" \t\r\n":
index += 1
fields.append(data[start:index])
index += 1
width, height, _ = (int(field) for field in fields[:3])
return width, height, data[index : index + width * height]
def ink(pixels: bytes, width: int, height: int) -> dict[str, object]:
dark = 0
x0 = y0 = 1 << 30
x1 = y1 = -1
for index, value in enumerate(pixels):
if value >= 128:
continue
dark += 1
x = index % width
y = index // width
x0 = min(x0, x)
y0 = min(y0, y)
x1 = max(x1, x)
y1 = max(y1, y)
if dark == 0:
return {"dark_pixels": 0, "bbox": None}
return {
"dark_pixels": dark,
"bbox": [x0, y0, x1, y1],
"fraction": round(dark / (width * height), 6),
}
def render_pages(pdf: Path, directory: Path) -> list[Path]:
prefix = directory / "page"
run("pdftoppm", "-gray", "-r", "72", str(pdf), str(prefix))
return sorted(directory.glob("page-*.pgm"))
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--reference", required=True, type=Path)
parser.add_argument("--candidate", required=True, type=Path)
parser.add_argument("--json", type=Path)
args = parser.parse_args()
ref_words = words(args.reference)
cand_words = words(args.candidate)
ratio = (
difflib.SequenceMatcher(None, ref_words, cand_words, autojunk=False).ratio()
if ref_words or cand_words
else 0.0
)
report: dict[str, object] = {
"reference": str(args.reference),
"candidate": str(args.candidate),
"reference_pages": page_count(args.reference),
"candidate_pages": page_count(args.candidate),
"reference_words": len(ref_words),
"candidate_words": len(cand_words),
"word_sequence_ratio": round(ratio, 6),
"pages": [],
}
with tempfile.TemporaryDirectory(prefix="tex-fidelity-") as temp:
ref_dir = Path(temp) / "reference"
cand_dir = Path(temp) / "candidate"
ref_dir.mkdir()
cand_dir.mkdir()
ref_pages = render_pages(args.reference, ref_dir)
cand_pages = render_pages(args.candidate, cand_dir)
for index, (ref_page, cand_page) in enumerate(zip(ref_pages, cand_pages), 1):
ref_width, ref_height, ref_pixels = pgm(ref_page)
cand_width, cand_height, cand_pixels = pgm(cand_page)
reference_ink = ink(ref_pixels, ref_width, ref_height)
candidate_ink = ink(cand_pixels, cand_width, cand_height)
report["pages"].append(
{
"page": index,
"size": [ref_width, ref_height],
"candidate_size": [cand_width, cand_height],
"reference_ink": reference_ink,
"candidate_ink": candidate_ink,
}
)
text = json.dumps(report, indent=2)
if args.json:
args.json.write_text(text, encoding="utf-8")
print(text)
return 0
if __name__ == "__main__":
raise SystemExit(main())