109 lines
6.0 KiB
Python
109 lines
6.0 KiB
Python
"""Compare retained Qt canvas renders with fixed-extent TinyTeX renders.
|
|
|
|
Run after the rectangle/segment tests have written *-canvas.png to the work directory.
|
|
No tight crops or fitted translations: both renderers use the declared 7 x 5 cm
|
|
extent, with 100 pixels/cm. The one-pixel edge tolerance is a prototype check,
|
|
not a stakeholder-approved product acceptance threshold.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
|
|
from PIL import Image, ImageChops, ImageDraw, ImageFilter
|
|
|
|
|
|
def run_checked(arguments, cwd):
|
|
result = subprocess.run(arguments, cwd=cwd, capture_output=True, text=True)
|
|
if result.returncode:
|
|
raise RuntimeError(result.stdout + result.stderr)
|
|
|
|
|
|
def compare(work, evidence, pdflatex, pdftoppm, fixtures, output_stem, source_directory=None):
|
|
corpus = source_directory or Path(__file__).resolve().parents[1] / "examples" / "explicit-coordinates"
|
|
work.mkdir(parents=True, exist_ok=True)
|
|
evidence.mkdir(parents=True, exist_ok=True)
|
|
rows = []
|
|
metrics = {}
|
|
for name in fixtures:
|
|
source = corpus / f"{name}.tex"
|
|
# Compile the untouched original from its own directory first.
|
|
run_checked([pdflatex, "-interaction=nonstopmode", "-halt-on-error",
|
|
f"-output-directory={work}", str(source)], corpus)
|
|
text = source.read_bytes().decode("utf-8")
|
|
picture = text[text.index(r"\begin{tikzpicture}"):text.index(r"\end{tikzpicture}")
|
|
+ len(r"\end{tikzpicture}")]
|
|
# Only the page wrapper changes. The complete original picture, including
|
|
# its invisible fixed extent, is placed at page origin without cropping.
|
|
calibrated = work / f"{name}-calibrated.tex"
|
|
calibrated.write_text(
|
|
"\\documentclass{article}\n\\usepackage{tikz}\n"
|
|
"\\pdfhorigin=0pt \\pdfvorigin=0pt\n"
|
|
"\\begin{document}\n\\setbox0=\\hbox{%\n" + picture + "%\n}\n"
|
|
"\\pdfpagewidth=7cm \\pdfpageheight=5cm\n"
|
|
"\\shipout\\box0\n\\end{document}\n", encoding="utf-8")
|
|
run_checked([pdflatex, "-interaction=nonstopmode", "-halt-on-error", calibrated.name], work)
|
|
prefix = work / f"{name}-pdf"
|
|
run_checked([pdftoppm, "-singlefile", "-r", "254", "-png",
|
|
str(calibrated.with_suffix(".pdf")), str(prefix)], work)
|
|
for log in (work / f"{name}.log", calibrated.with_suffix(".log")):
|
|
diagnostics = log.read_text(encoding="utf-8", errors="replace")
|
|
if any(term in diagnostics for term in ("! ", "Undefined control", "undefined references",
|
|
"undefined citations", "not found")):
|
|
raise RuntimeError(f"Unexpected diagnostics in {log}")
|
|
canvas = Image.open(work / f"{name}-canvas.png").convert("RGB")
|
|
pdf = Image.open(prefix.with_suffix(".png")).convert("RGB")
|
|
# Poppler may ceil a fractional page dimension by one background pixel.
|
|
if pdf.width not in (700, 701) or pdf.height not in (500, 501):
|
|
raise AssertionError(f"Unexpected fixed-extent raster size: {pdf.size}")
|
|
background = Image.new("RGB", pdf.size, "white")
|
|
background.paste(canvas, (0, 0))
|
|
canvas = background
|
|
mask_canvas = canvas.convert("L").point(lambda value: 255 if value < 128 else 0)
|
|
mask_pdf = pdf.convert("L").point(lambda value: 255 if value < 128 else 0)
|
|
if mask_canvas.getbbox() is None or mask_pdf.getbbox() is None:
|
|
raise AssertionError("A renderer produced an empty image")
|
|
# Every dark edge pixel must have a counterpart within one pixel. This
|
|
# detects translation, wrong size, scale, axis, or missing/extra boxes.
|
|
unmatched_canvas = ImageChops.subtract(mask_canvas, mask_pdf.filter(ImageFilter.MaxFilter(3)))
|
|
unmatched_pdf = ImageChops.subtract(mask_pdf, mask_canvas.filter(ImageFilter.MaxFilter(3)))
|
|
count_canvas = unmatched_canvas.width * unmatched_canvas.height - unmatched_canvas.histogram()[0]
|
|
count_pdf = unmatched_pdf.width * unmatched_pdf.height - unmatched_pdf.histogram()[0]
|
|
metrics[name] = {"pdf_pixels": list(pdf.size), "pixels_per_centimeter": 100,
|
|
"edge_tolerance_pixels": 1,
|
|
"unmatched_canvas_pixels": count_canvas, "unmatched_pdf_pixels": count_pdf}
|
|
if count_canvas or count_pdf:
|
|
raise AssertionError(json.dumps(metrics[name]))
|
|
row = Image.new("RGB", (2130, 550), "#eeeeee")
|
|
draw = ImageDraw.Draw(row)
|
|
draw.text((15, 12), name + ": Qt canvas | TinyTeX | aligned overlay", fill="black")
|
|
overlay = Image.blend(canvas, pdf, 0.5)
|
|
for index, image in enumerate((canvas, pdf, overlay)):
|
|
row.paste(image, (index * 710 + 5, 40))
|
|
rows.append(row)
|
|
for start in range(0, len(rows), 2):
|
|
sheet = Image.new("RGB", (2130, min(2, len(rows)-start) * 550), "white")
|
|
for index, row in enumerate(rows[start:start+2]):
|
|
sheet.paste(row, (0, index * 550))
|
|
suffix = "" if start == 0 else f"-{start//2+1}"
|
|
sheet.save(evidence / f"{output_stem}{suffix}.png")
|
|
(evidence / f"{output_stem}.json").write_text(
|
|
json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
|
|
print(json.dumps(metrics, indent=2))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--work", type=Path, required=True)
|
|
parser.add_argument("--evidence", type=Path, required=True)
|
|
parser.add_argument("--pdflatex", required=True)
|
|
parser.add_argument("--pdftoppm", required=True)
|
|
parser.add_argument("--fixtures", nargs="+", default=["boxes-initial", "boxes-touching"])
|
|
parser.add_argument("--output-stem", default="rectangle-comparison-2026-10-21")
|
|
parser.add_argument("--source-directory", type=Path)
|
|
options = parser.parse_args()
|
|
compare(options.work.resolve(), options.evidence.resolve(), options.pdflatex, options.pdftoppm,
|
|
options.fixtures, options.output_stem,
|
|
options.source_directory.resolve() if options.source_directory else None)
|