#!/usr/bin/env python3 """Audit actual native --job shipouts against the same unmodified TeX input. Every physical PDF page is checked at the existing 0.02bp/144dpi tolerances. Auxiliary output, fonts and actual resource reads are retained as evidence. """ import argparse import hashlib import importlib.util import json import os import re import subprocess from pathlib import Path def run(args, cwd, env=None): r = subprocess.run([str(a) for a in args], cwd=cwd, env=env, capture_output=True, text=True, timeout=90) if r.returncode: raise RuntimeError(r.stdout + '\n' + r.stderr) return r.stdout + r.stderr def raster(pdf, base, page): run(['pdftoppm', '-f', page, '-l', page, '-singlefile', '-gray', '-r', '144', pdf, base], pdf.parent) data = base.with_suffix('.pgm').read_bytes() m = re.match(rb'P5\s+(\d+)\s+(\d+)\s+255\s', data) assert m width, height = map(int, m.groups()) pixels = data[m.end():] assert len(pixels) == width * height return width, height, {i for i, value in enumerate(pixels) if value < 200} def ink_report(a, b): assert a[:2] == b[:2] width, height, ni = a ri = b[2] assert ni and ri, 'each declared fixture page must contain actual ink' def unmatched(x, y): return sum(not any(0 <= i % width + dx < width and 0 <= i // width + dy < height and i + dy * width + dx in y for dy in [-1, 0, 1] for dx in [-1, 0, 1]) for i in x) def bbox(x): return [min(i % width for i in x), min(i // width for i in x), max(i % width for i in x), max(i // width for i in x)] un, ur = unmatched(ni, ri), unmatched(ri, ni) nb, rb = bbox(ni), bbox(ri) xor = len(ni ^ ri) return dict(passed=un == ur == 0 and all(abs(x-y) <= 1 for x, y in zip(nb, rb)) and xor <= len(ri)*.01, raster_size=[width, height], native_ink=len(ni), reference_ink=len(ri), different_pixels=xor, unmatched_native=un, unmatched_reference=ur, native_bbox=nb, reference_bbox=rb) def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--binary', type=Path, required=True) p.add_argument('--fixture', type=Path, required=True) p.add_argument('--output-dir', type=Path, required=True) p.add_argument('--expected-pages', type=int, required=True) p.add_argument('--json', type=Path, required=True) args = p.parse_args() root = Path(__file__).resolve().parents[1] fixture, binary, out = args.fixture.resolve(), args.binary.resolve(), args.output_dir.resolve() out.mkdir(parents=True, exist_ok=True) native, reference = out/'native', out/'reference' native.mkdir(exist_ok=True) reference.mkdir(exist_ok=True) source = fixture.read_bytes() (native/'cli.log').write_text(run([binary, 'native', '--job', '--initex', '--etex', '--resource-manifest', native/'resources.json', fixture, native/'job.pdf'], native)) (reference/'reference.tex').write_text('\\pdfoutput=1\n' + f'\\input "{fixture.as_posix()}"\n') (reference/'cli.log').write_text(run(['pdftex', '-ini', '-etex', '-interaction=nonstopmode', '-halt-on-error', 'reference.tex'], reference, {**os.environ, 'TEXINPUTS': str(fixture.parent)+os.pathsep+os.environ.get('TEXINPUTS', '')})) pdfs = [native/'job.pdf', reference/'reference.pdf'] counts = [int(re.search(r'Pages:\s*(\d+)', run(['pdfinfo', pdf], out))[1]) for pdf in pdfs] spec = importlib.util.spec_from_file_location('paragraph_word_gate', root/'scripts/check-native-paragraphs.py') gate = importlib.util.module_from_spec(spec) spec.loader.exec_module(gate) word_pages = [gate.words(pdf) for pdf in pdfs] text_equal = [[w[0] for w in page] for page in word_pages[0]] == [[w[0] for w in page] for page in word_pages[1]] words = [[w for page in pages for w in page] for pages in word_pages] errors = ({key: max(abs(a[1][key]-b[1][key]) for a, b in zip(*words)) for key in ['xMin', 'xMax', 'yMin', 'yMax']} if text_equal and all(words) else None) ink = [] if counts == [args.expected_pages]*2: for page in range(1, args.expected_pages+1): row = ink_report(raster(pdfs[0], native/f'page-{page}', page), raster(pdfs[1], reference/f'page-{page}', page)) row['page'] = page ink.append(row) fonts = [run(['pdffonts', pdf], out) for pdf in pdfs] expected_fonts = ['CMR10', 'CMMI10', 'CMMI7'] aux = [(directory/'pages.aux').read_bytes() for directory in [native, reference]] trace = json.loads((native/'resources.json').read_text()) actual_reads = trace['reads'] required = [fixture.name, 'math-fonts.tex', 'cmr10.tfm', 'cmmi7.tfm', 'cmr10.pfb', 'cmmi7.pfb'] resources = all(any(r['path'].endswith(name) for r in actual_reads) for name in required) passed = (counts == [args.expected_pages]*2 and text_equal and errors is not None and max(errors.values()) <= .02 and len(ink) == args.expected_pages and all(row['passed'] for row in ink) and all(all(name in f for name in expected_fonts) for f in fonts) and bool(aux[0]) and aux[0] == aux[1] and resources and fixture.read_bytes() == source) report = dict(passed=passed, source_sha256=hashlib.sha256(source).hexdigest(), source_unchanged=fixture.read_bytes() == source, pages=counts, word_counts=list(map(len, words)), page_word_counts=[[len(page) for page in pages] for pages in word_pages], text_equal=text_equal, max_word_box_errors_bp=errors, ink=ink, expected_fonts=expected_fonts, native_fonts=fonts[0], reference_fonts=fonts[1], aux_equal=aux[0] == aux[1], aux_hex=aux[0].hex(), actual_resources_verified=resources, native_reads=len(actual_reads), tolerances=dict(word_box_bp=.02, dpi=144, ink_threshold=200, coverage_radius_pixels=1, bbox_pixels=1, max_xor_ratio=.01), scope='Actual online native --job pages/output/shipout, captured paper/origin/magnification and real deferred auxiliary I/O; not complete pdfTeX configuration or format conformance') args.json.parent.mkdir(parents=True, exist_ok=True) args.json.write_text(json.dumps(report, indent=2)+'\n') print(json.dumps({k:v for k,v in report.items() if k not in ['native_fonts', 'reference_fonts']}, indent=2)) if not passed: raise SystemExit(1) if __name__ == '__main__': main()