Files
texrra-engine/scripts/check-native-device.py

145 lines
7.5 KiB
Python

#!/usr/bin/env python3
"""Independent actual PDF device/mag/true oracle; unchanged physical tolerances.
Every synthetic input is identical for native and reference execution. External
TeX is used only here, never by the product. Retain all source/PDF/aux evidence.
"""
import argparse
import hashlib
import importlib.util
import json
import os
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def module(name, file):
spec = importlib.util.spec_from_file_location(name, ROOT/'scripts'/file)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
INK = module('native_page_ink', 'check-native-pages.py')
WORDS = module('native_page_words', 'check-native-paragraphs.py')
def cases():
fixture = ROOT/'examples/native-bootstrap/device.tex'
yield 'original-device-fixture', fixture.read_text(), fixture.parent, 3, ['cmr10', 'cmmi7']
fonts = (ROOT/'examples/native-bootstrap/math-fonts.tex').read_text()
for mag in [500, 1000, 1095, 1200, 2000, 4096]:
for unit in ['pt', 'truept']:
source = (fonts + f'\\mag={mag}\\pdfpagewidth=180{unit}\\pdfpageheight=140{unit}'
+ f'\\pdfhorigin=10{unit}\\pdfvorigin=12{unit}'
+ r'\hoffset=2pt\voffset=3pt\count0=1\immediate\openout1=device.aux'
+ r'\setbox0=\vbox{\hbox{Native AV office $x_i^j+y$}\kern2pt\hrule height1pt depth2pt'
+ r'\write1{SHIP=\number\count0;MAG=\number\mag}}\shipout\copy0'
+ r'{\pdfpagewidth=0pt\pdfpageheight=0pt\hoffset=-1pt\voffset=2pt'
+ r'\count0=2\shipout\box0}'
+ r'\pdfpagewidth=999pt\pdfpageheight=888pt\pdfhorigin=123pt'
+ '\\immediate\\closeout1\\end\n')
yield f'mag-{mag}-{unit}', source, fixture.parent, 2, ['cmr10', 'cmmi7']
for mag in [1, 32768]:
# Keep the actual TeX font size below its 2048pt limit at mag=1.
font_size = 2 if mag == 1 else 10
source = (r'\catcode123=1\catcode125=2' + f'\\mag={mag}'
+ f'\\font\\physical=cmr10 at{font_size}truept\\physical'
+ r'\pdfpagewidth=12truept\pdfpageheight=12truept'
+ r'\pdfhorigin=1truept\pdfvorigin=1truept\count0=1'
+ r'\immediate\openout1=device.aux\shipout\hbox{A'
+ r'\vrule width1truept height2truept depth.5truept'
+ r'\write1{SHIP=\number\count0;MAG=\number\mag}}'
+ '\\immediate\\closeout1\\end\n')
yield f'mag-boundary-{mag}', source, fixture.parent, 1, ['cmr10']
def mediaboxes(path):
# Poppler resolves both classic and compressed object/xref layouts.
text = INK.run(['pdftotext', '-bbox', path, '-'], path.parent)
return [[0.0, 0.0, float(w), float(h)] for w, h in re.findall(
r'<page\s+width="([-.\d]+)"\s+height="([-.\d]+)"', text)]
def audit(binary, out, item):
name, source, inputs, count, expected_fonts = item
d = out/name
n, r = d/'native', d/'reference'
n.mkdir(parents=True, exist_ok=True)
r.mkdir(parents=True, exist_ok=True)
file = d/'source.tex'
file.write_text(source)
# Preserve the fixture's project input bytes alongside the copied main
# source; native project lookup uses its actual source directory.
(d/'math-fonts.tex').write_bytes((ROOT/'examples/native-bootstrap/math-fonts.tex').read_bytes())
before = hashlib.sha256(file.read_bytes()).hexdigest()
run = INK.run
(n/'cli.log').write_text(run([binary, 'native', '--job', '--initex', '--etex',
'--resource-manifest', n/'resources.json', file, n/'job.pdf'], n))
(r/'reference.tex').write_text('\\pdfoutput=1\\pdfcompresslevel=0\\pdfobjcompresslevel=0\n'
+ f'\\input "{file.as_posix()}"\n')
(r/'cli.log').write_text(run(['pdftex', '-ini', '-etex', '-interaction=nonstopmode',
'-halt-on-error', 'reference.tex'], r,
{**os.environ, 'TEXINPUTS': str(inputs)+os.pathsep+os.environ.get('TEXINPUTS', '')}))
pdfs = [n/'job.pdf', r/'reference.pdf']
media = [mediaboxes(p) for p in pdfs]
page_counts = [len(m) for m in media]
paper_equal = (page_counts == [count, count] and all(a == b
for am, bm in zip(*media) for a, b in zip(am, bm)))
words = [WORDS.words(p) for p in pdfs]
text_equal = ([[w[0] for w in p] for p in words[0]] == [[w[0] for w in p] for p in words[1]])
flat = [[w for p in pages for w in p] for pages in words]
errors = {k: max(abs(a[1][k]-b[1][k]) for a, b in zip(*flat))
for k in ['xMin', 'xMax', 'yMin', 'yMax']} if text_equal and all(flat) else None
ink = []
if paper_equal:
for page in range(1, count+1):
v = INK.ink_report(INK.raster(pdfs[0], n/f'page-{page}', page),
INK.raster(pdfs[1], r/f'page-{page}', page))
v['page'] = page
ink.append(v)
aux = [p.read_bytes() for p in [n/'device.aux', r/'device.aux']]
trace = json.loads((n/'resources.json').read_text())
resources = all(any(v['path'].endswith(font+suffix) for v in trace['reads'])
for font in expected_fonts for suffix in ['.tfm', '.pfb'])
source_unchanged = hashlib.sha256(file.read_bytes()).hexdigest() == before
passed = (paper_equal and text_equal and errors is not None and max(errors.values()) <= .02
and len(ink) == count and all(v['passed'] for v in ink) and aux[0] == aux[1]
and bool(aux[0]) and resources and source_unchanged)
result = dict(id=name, passed=passed, page_counts=page_counts, media_boxes=media, paper_equal=paper_equal,
text_equal=text_equal, word_counts=[len(v) for v in flat], max_word_box_errors_bp=errors,
ink=ink, aux_equal=aux[0] == aux[1], aux_hex=aux[0].hex(),
expected_fonts=expected_fonts, actual_resources_verified=resources, source_sha256=before, source_unchanged=source_unchanged)
(d/'audit.json').write_text(json.dumps(result, indent=2)+'\n')
return result
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--binary', type=Path, required=True)
p.add_argument('--output-dir', type=Path, required=True)
args = p.parse_args()
out = args.output_dir.resolve()
out.mkdir(parents=True, exist_ok=True)
results = []
for item in cases():
result = audit(args.binary.resolve(), out, item)
results.append(result)
print(result['id'], 'passed' if result['passed'] else 'FAILED', result['max_word_box_errors_bp'], flush=True)
report = dict(passed=all(r['passed'] for r in results), cases=len(results),
pages=sum(r['page_counts'][0] for r in results), results=results,
binary_sha256=hashlib.sha256(args.binary.resolve().read_bytes()).hexdigest(),
reference_version=INK.run(['pdftex', '--version'], out).splitlines()[0],
tolerances=dict(word_box_bp=.02, media_box_bp=0, dpi=144,
ink_threshold=200, coverage_radius_pixels=1, bbox_pixels=1, max_xor_ratio=.01),
scope='Actual native per-shipout paper/origin/offset/mag/true and late I/O; full PDF configuration and format startup remain incomplete.')
(out/'audit.json').write_text(json.dumps(report, indent=2)+'\n')
if not report['passed']:
raise SystemExit(1)
if __name__ == '__main__':
main()