Files
texrra-engine/scripts/build-pk-font-oracle.py
T

44 lines
3.3 KiB
Python

#!/usr/bin/env python3
"""Freeze independently decoded real pdfTeX Type3 masks for PK font tests.
Test generator only: pypdf parses real PDF glyph streams; the product PK
decoder is never called. Binary fixtures are the original installed PK files.
"""
from pathlib import Path
import argparse, hashlib, json, re, shutil, subprocess
from pypdf import PdfReader
import pypdf
ROOT=Path(__file__).resolve().parents[1]
def sha(data):return hashlib.sha256(data).hexdigest()
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output-dir',type=Path,required=True);a=p.parse_args();out=a.output_dir.resolve();out.mkdir(parents=True,exist_ok=True)
fixtures=ROOT/'crates/texrra-tex-core/tests/fixtures/pk';fixtures.mkdir(exist_ok=True)
texmf=Path(subprocess.check_output(['kpsewhich','--var-value=TEXMFDIST'],text=True).strip())
results={}
for name in ['cmr10','cmmi10','cmex10']:
d=out/name;d.mkdir(exist_ok=True)
source=(r'\catcode123=1\catcode125=2\pdfoutput=1\pdfcompresslevel=0\pdfobjcompresslevel=0\pdfmapfile{}\pdfpkresolution=600'
+f'\\font\\F={name}\\F'+r'\pdfpagewidth=1000pt\pdfpageheight=100pt\shipout\hbox{'
+''.join(f'\\char{i}\\kern0pt 'for i in range(128))+r'}\end')
(d/'source.tex').write_text(source)
r=subprocess.run(['pdftex','-ini','-etex','-interaction=nonstopmode','-halt-on-error','source.tex'],cwd=d,capture_output=True)
(d/'cli.log').write_bytes(r.stdout+r.stderr);r.check_returncode()
pdf=d/'source.pdf';reader=PdfReader(pdf,strict=True);font=next(iter(reader.pages[0]['/Resources']['/Font'].values())).get_object()
assert font['/Subtype']=='/Type3'
glyphs={}
for key,ref in font['/CharProcs'].items():
slot=int(str(key)[2:]);data=ref.get_data();header=re.match(rb'(-?[\d.]+) 0 (-?\d+) (-?\d+) (-?\d+) (-?\d+) d1\n',data);assert header
image=re.search(rb'/W (\d+)\s*/H (\d+)\s*/IM true\s*/BPC 1\s*/D \[1 0\]\s*ID ',data)
bitmap=b'';w=h=0
if image:
w,h=map(int,image.groups());length=((w+7)//8)*h;bitmap=data[image.end():image.end()+length]
assert data[image.end()+length:].startswith(b'\nEI\nQ\n')
glyphs[str(slot)]=dict(width_hundredths=round(float(header[1])*100),bbox=[int(v)for v in header.groups()[1:]],image_width=w,image_height=h,bitmap_sha256=sha(bitmap),bitmap_bytes=len(bitmap))
pk=texmf/f'fonts/pk/ljfour/public/cm/dpi600/{name}.pk';shutil.copyfile(pk,fixtures/f'{name}.600pk')
results[name]=dict(pk_sha256=sha(pk.read_bytes()),pk_source=str(pk),tfm_sha256=sha((ROOT/f'crates/texrra-tex-core/assets/{name}.tfm').read_bytes()),source_sha256=sha(source.encode()),pdf_sha256=sha(pdf.read_bytes()),font_matrix_scale=round(float(font['/FontMatrix'][0])*100000),font_bbox=[int(v)for v in font['/FontBBox']],glyphs=glyphs)
print(name,len(glyphs),'independent glyph masks',flush=True)
report=dict(reference_version=subprocess.check_output(['pdftex','--version'],text=True).splitlines()[0],pypdf_version=pypdf.__version__,method='Real pdfTeX PK Type3 charprocs independently decompressed by pypdf; product decoder never invoked',fonts=results)
(fixtures/'oracle.json').write_text(json.dumps(report,indent=2)+'\n')
if __name__=='__main__':main()