#!/usr/bin/env python3 """Compare actual native accent ink with fresh INITEX output at 144dpi. Wide CMEX accents/vector lack equivalent Unicode metadata in the reference; this gate compares actual outlines/positions. Use accent-text.tex with the unchanged paragraph PDF gate for matching Unicode text and word boxes. """ import argparse import hashlib import json import os import re import subprocess from pathlib import Path def run(args, directory, env=None): r = subprocess.run([str(a) for a in args], cwd=directory, env=env, capture_output=True, text=True) if r.returncode: raise RuntimeError(r.stdout+'\n'+r.stderr) return r.stdout+r.stderr def raster(pdf, base): run(['pdftoppm', '-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, p in enumerate(pixels) if p < 200} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--binary', type=Path, required=True) parser.add_argument('--output-dir', type=Path, required=True) parser.add_argument('--json', type=Path, required=True) parser.add_argument('--fixture', type=Path, help='native math fixture; defaults to accents.tex') parser.add_argument('--expected-font', action='append', dest='expected_fonts', help='required embedded font name; repeat for a different font fixture') args = parser.parse_args() root = Path(__file__).resolve().parent.parent fixture = args.fixture.resolve() if args.fixture else root/'examples/native-bootstrap/accents.tex' stem = fixture.stem source = fixture.read_text() out = args.output_dir.resolve() out.mkdir(parents=True, exist_ok=True) (out/'reference.tex').write_text('\\pdfoutput=1 \\pdfpagewidth=612bp ' '\\pdfpageheight=792bp \\vsize=648bp \\topskip=10bp\n'+source) (out/'native-cli.txt').write_text(run([args.binary.resolve(), 'native', '--initex', '--etex', fixture, out/(stem+'.pdf')], out)) (out/'reference-cli.txt').write_text(run(['pdftex', '-ini', '-etex', '-interaction=nonstopmode', '-halt-on-error', 'reference.tex'], out, {**os.environ, 'TEXINPUTS':str(fixture.parent)+os.pathsep+os.environ.get('TEXINPUTS','')})) native = raster(out/(stem+'.pdf'), out/'native') reference = raster(out/'reference.pdf', out/'reference') assert native[:2] == reference[:2] width, height, ni = native ri = reference[2] assert ni and ri def unmatched(a, b): return sum(not any(i+dy*width+dx in b for dy in [-1,0,1] for dx in [-1,0,1]) for i in a) def bbox(a): return [min(i%width for i in a), min(i//width for i in a), max(i%width for i in a), max(i//width for i in a)] un, ur = unmatched(ni, ri), unmatched(ri, ni) different = len(ni ^ ri) nb, rb = bbox(ni), bbox(ri) pdfs = [out/(stem+'.pdf'), out/'reference.pdf'] pages = [int(re.search(r'Pages:\s*(\d+)',run(['pdfinfo', p], out))[1]) for p in pdfs] fonts = [run(['pdffonts', p], out) for p in pdfs] texts = [run(['pdftotext', '-layout', p, '-'], out) for p in pdfs] for name, text in zip(['native', 'reference'], texts): (out/(name+'.txt')).write_text(text) passed = (pages == [1,1] and un == ur == 0 and all(abs(a-b) <= 1 for a,b in zip(nb,rb)) and different <= len(ri)*.01 and all(all(name in f for name in (args.expected_fonts or ['CMR10','CMMI10','CMEX10'])) for f in fonts) and '\ufffd' not in texts[0]) result = dict(passed=passed,source_sha256=hashlib.sha256(source.encode()).hexdigest(), pages=pages,raster_size=[width,height],native_ink=len(ni),reference_ink=len(ri), different_pixels=different,unmatched_native=un,unmatched_reference=ur, native_bbox=nb,reference_bbox=rb,text_equal=texts[0]==texts[1], native_fonts=fonts[0],reference_fonts=fonts[1], tolerances=dict(dpi=144,ink_threshold=200,coverage_radius_pixels=1,bbox_pixels=1,max_xor_ratio=.01), scope='Absolute whole-page native math ink; no fitted offsets. Reference extension-font Unicode metadata can differ; matching-Unicode word boxes are gated separately.') args.json.parent.mkdir(parents=True,exist_ok=True) args.json.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n') print(json.dumps({k:v for k,v in result.items() if k not in ['native_fonts','reference_fonts']},indent=2)) if not passed: raise SystemExit(1) if __name__ == '__main__': main()