#!/usr/bin/env python3 """Run original publisher samples in independent reference and native jobs.""" import argparse import hashlib import json import os import re import shutil import stat import subprocess import zipfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path, PurePosixPath ROOT = Path(__file__).resolve().parent.parent CASES = [ ("arxiv", "preprint", None, "template.tex"), ("plos-one", "journal-single-column", "plos", "plos_latex_template.tex"), ("springer-nature", "journal", "springer-journal", "sn-article-template/sn-article.tex"), ("elsevier-cas-sc", "journal-single-column", "elsevier-cas", "els-cas-templates/cas-sc-sample.tex"), ("elsevier-cas-dc", "journal-two-columns", "elsevier-cas", "els-cas-templates/cas-dc-sample.tex"), ("ieee-transactions", "journal-two-columns", "ieee", "IEEEtran/bare_jrnl.tex"), ("aps-revtex-reprint", "journal-two-columns", "revtex", "revtex/sample/aps/apssamp.tex"), ("aapm-revtex", "journal-two-columns", "revtex", "revtex/sample/aapm/aapmsamp.tex"), ("aip-revtex-jmp", "journal-single-column", "revtex", "revtex/sample/aip/aipsamp.tex"), ("sor-revtex-jor", "journal-single-column", "revtex", "revtex/sample/sor/sorsamp.tex"), ("oup-contemporary-large", "journal-two-columns", "oup-authoring-template", "oup-authoring-template/oup-authoring-template.tex"), ("springer-lncs", "conference", "springer-lncs", "samplepaper.tex"), ("ieee-conference", "conference", "ieee", "IEEEtran/bare_conf.tex"), ("acl", "conference", "acl", "acl-style-files-master/acl_latex.tex"), ("cvpr-2026", "conference", "cvpr-2026", "author-kit-CVPR2026-v1-latex-/main.tex"), ("neurips-2025", "conference", "neurips-2025", "Styles/neurips_2025.tex"), ("acm-acmsmall", "journal-single-column", "acmart", "acmart/samples/acmsmall.tex"), ("acm-acmtog", "journal-two-columns", "acmart", "acmart/samples/acmtog.tex"), ("acm-sigconf", "conference", "acmart", "acmart/samples/sigconf.tex"), ] EPS_FIGURES = { "springer-nature": ["fig.eps"], "aps-revtex-reprint": ["fig_1.eps", "fig_2.eps", "vid_1a.eps", "vid_1b.eps"], "aapm-revtex": ["fig_1.eps", "fig_2.eps"], "aip-revtex-jmp": ["fig_1.eps", "fig_2.eps"], "sor-revtex-jor": ["fig_1.eps", "fig_2.eps"], "springer-lncs": ["fig1.eps"], } def sha(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def inputs(directory): return {p.relative_to(directory).as_posix(): sha(p) for p in sorted(directory.rglob("*")) if p.is_file()} def unpack(path, directory): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): name = PurePosixPath(info.filename) if name.is_absolute() or ".." in name.parts or "\\" in info.filename: raise ValueError(f"unsafe path in {path}: {info.filename}") if stat.S_ISLNK(info.external_attr >> 16): raise ValueError(f"unexpected symlink in {path}: {info.filename}") archive.extractall(directory) def run(command, cwd, env, label, evidence, *, timeout=90): with (evidence / f"{label}.stdout.log").open("wb") as output, \ (evidence / f"{label}.stderr.log").open("wb") as errors: try: status = subprocess.run(command, cwd=cwd, env=env, stdout=output, stderr=errors, timeout=timeout).returncode except subprocess.TimeoutExpired: status = 124 return {"command": list(map(str, command)), "exit_code": status, "label": label} def prepare_acmart(directory, evidence): """Extract the published class and samples with the package's DocStrip installers.""" upstream = directory / "acmart" samples = upstream / "samples" workspace = evidence / "docstrip" sample_workspace = workspace / "samples" sample_workspace.mkdir(parents=True) env = {**os.environ, "TEXINPUTS": os.pathsep, "SOURCE_DATE_EPOCH": "1783900800"} latex = ["pdflatex", "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape", "-recorder"] commands = [] for original, work, installer, sources in ( (upstream, workspace, "acmart.ins", ["acmart.dtx"]), (samples, sample_workspace, "samples.ins", ["samples.dtx", "acmengage.dtx"]), ): for name in [installer, *sources]: shutil.copyfile(original / name, work / name) result = run([*latex, installer], work, env, installer, evidence) if result["exit_code"]: raise RuntimeError(f"ACM sample extraction failed: {evidence / installer}") commands.append(result) generated = {} for source, destination in [ (workspace / "acmart.cls", samples / "acmart.cls"), *[(sample_workspace / name, samples / name) for name in ("acmsmall.tex", "acmtog.tex", "sigconf.tex")], *[(upstream / name, samples / name) for name in ("ACM-Reference-Format.bst", "acm-jdslogo.png")], ]: if destination.exists(): raise ValueError(f"ACM installer output already exists: {destination}") shutil.copyfile(source, destination) generated[destination.relative_to(directory).as_posix()] = sha(destination) return {"commands": commands, "sample_inputs": generated} def diagnostics(evidence, label): lines = [] for stream in ("stderr", "stdout"): log = (evidence / f"{label}.{stream}.log").read_text(errors="replace") lines.extend(line for line in log.splitlines() if line.startswith(("error:", "!", "pdftex:", "I couldn't", "I found no"))) return lines[:15] def prepare_figures(name, template, entry, evidence, args): if not args.ghostscript or name not in EPS_FIGURES: return [] directory = template / Path(entry).parent output = evidence / "converted-eps" output.mkdir() env = {**os.environ, "SOURCE_DATE_EPOCH": "1783900800"} results = [] for file_name in EPS_FIGURES[name]: source = directory / file_name stem = source.stem pdf = output / f"{stem}-eps-converted-to.pdf" assert source.is_file() and not (directory / pdf.name).exists() source_sha256 = sha(source) result = run(["epstopdf", f"--gscmd={args.ghostscript}", f"--outfile={pdf}", source], output, env, stem, output) assert result["exit_code"] == 0 and pdf.is_file(), result with pdf.open("rb") as stream: assert stream.read(5) == b"%PDF-", pdf assert sha(source) == source_sha256 results.append({"source": file_name, "source_sha256": source_sha256, "pdf_path": str(pdf), "pdf_sha256": sha(pdf), **result}) return results def compile_sample(template, entry, evidence, args, engine, figures): work = evidence / "work" evidence.mkdir() shutil.copytree(template, work) frozen = inputs(work) assert frozen == inputs(template) and entry in frozen cwd = work / Path(entry).parent for figure in figures: pdf = Path(figure["pdf_path"]) assert sha(pdf) == figure["pdf_sha256"] shutil.copyfile(pdf, cwd / pdf.name) prefix = "texrra-oracle" jobname = Path(entry).stem output = cwd / f"{prefix}.pdf" assert not output.exists() job_directory = evidence / "job" if engine == "reference" else cwd produced_pdf = job_directory / f"{jobname}.pdf" if engine == "reference" else output aux = job_directory / f"{jobname}.aux" env = {**os.environ, "TEXINPUTS": os.pathsep, "TEXRRA_STATE_DIR": str(evidence / "state"), "BSTINPUTS": f"{cwd}/bst//{os.pathsep}{cwd}{os.pathsep}", "BIBINPUTS": f"{cwd}{os.pathsep}", "SOURCE_DATE_EPOCH": "1783900800"} if args.texmf_overlay: env["TEXMFHOME"] = str(args.texmf_overlay) if args.font_map: env["TEXFONTMAPS"] = str(args.font_map.parent) + os.pathsep if engine == "reference": # TeX exposes the job name to the document. Keep it identical to the # native run and put generated files outside the copied input tree. job_directory.mkdir() env["TEXFORMATS"] = f"{args.reference_format.parent}{os.pathsep}" latex = ["pdftex", f"-fmt={args.reference_format.name}", "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape", "-recorder", f"-jobname={jobname}", f"-output-directory={job_directory}", Path(entry).name] else: latex = [args.binary, "native", "--job", "--etex", "--step-limit", "600000000", "--input-policy", "tex", "--load-format", args.native_format] if args.texmf_overlay: latex.extend(["--texmf-root", args.texmf_overlay]) latex.extend(["--texmf-root", "/usr/share/texlive/texmf-dist", "--texmf-root", "/var/lib/texmf", Path(entry).name, output.name]) commands = [] aux_checksums = [] for idx in range(1, args.max_passes + 1): label = f"latex-{idx}" command = latex if engine == "native": command = [*latex[:-2], "--resource-manifest", evidence / f"{label}.resources.json", "--layout-manifest", evidence / f"{label}.layout.json", *latex[-2:]] step = run(command, cwd, env, label, evidence, timeout=args.latex_timeout) recorder = job_directory / f"{jobname}.fls" if engine == "reference" and recorder.is_file(): shutil.copyfile(recorder, evidence / f"{label}.fls") commands.append(step) if step["exit_code"]: break if aux.is_file(): shutil.copyfile(aux, evidence / f"{label}.aux") aux_checksums.append(sha(aux) if aux.is_file() else None) if idx == 1 and aux.is_file() and b"\\bibdata{" in aux.read_bytes(): step = run(["bibtex", jobname], job_directory, env, "bibtex", evidence) commands.append(step) if step["exit_code"]: break if idx >= 3 and aux_checksums[-1] is not None and aux_checksums[-1] == aux_checksums[-2]: break changed = [name for name, digest in frozen.items() if not (work / name).is_file() or sha(work / name) != digest] last = commands[-1] built = last["exit_code"] == 0 and produced_pdf.is_file() if built and engine == "reference": shutil.copyfile(produced_pdf, output) logfile = job_directory / f"{jobname if engine == 'reference' else prefix}.log" log = logfile.read_text(errors="replace") if logfile.is_file() else "" pdf = {} if built: pdf = {"sha256": sha(output), "bytes": output.stat().st_size} for cmd in ("pdfinfo", "pdffonts"): run([cmd, output.name], cwd, env, cmd, evidence) run(["pdftotext", "-bbox-layout", output.name, evidence / "word-boxes.html"], cwd, env, "pdf-word-boxes", evidence) info = (evidence / "pdfinfo.stdout.log").read_text(errors="replace") pages = re.search(r"^Pages:\s+(\d+)", info, re.M) pdf["pages"] = int(pages.group(1)) if pages else None return {"commands": commands, "diagnostics": diagnostics(evidence, last["label"]), "job_name": jobname, "aux_file": aux.name, "packaged_files_changed_in_work_directory": { name: {"before": frozen[name], "after": sha(work / name) if (work / name).is_file() else None} for name in changed }, "entry_sha256": frozen[entry], "aux_sha256_per_pass": aux_checksums, "aux_converged": len(aux_checksums) >= 2 and aux_checksums[-1] is not None and aux_checksums[-1] == aux_checksums[-2], "undefined_reference_warnings": [ line for line in log.splitlines() if re.search(r"\bundefined (references|citations)\b|\b(?:Reference|Citation)\b.*\bundefined\b", line, re.I) ], "pdf_built": built, "pdf": pdf} def main(): parser = argparse.ArgumentParser(description=__doc__) for key in ("archives", "output", "binary", "native-format", "reference-format"): parser.add_argument(f"--{key}", type=lambda p: Path(p).resolve(), required=True) parser.add_argument("--texmf-overlay", type=lambda p: Path(p).resolve()) parser.add_argument("--font-map", type=lambda p: Path(p).resolve()) parser.add_argument("--ghostscript", type=lambda p: Path(p).resolve(strict=True), help="Ghostscript executable for explicit conversion of the original EPS figures") parser.add_argument("--max-passes", type=int, choices=range(4, 13), default=4) parser.add_argument("--latex-timeout", type=int, default=90, metavar="SECONDS", help="maximum time per LaTeX pass (default: 90 seconds)") parser.add_argument("--case", action="append", choices=[item[0] for item in CASES], help="run selected cases; omit to run the complete matrix") args = parser.parse_args() if args.latex_timeout <= 0: parser.error("--latex-timeout must be positive") if args.font_map and args.font_map.name != "pdftex.map": parser.error("--font-map must name a pdftex.map file") selected = [item for item in CASES if not args.case or item[0] in args.case] archives = {item[2] for item in selected if item[2]} registry = json.loads((ROOT / "scripts/publisher-template-matrix.json").read_text()) config = {name: registry[name] for name in registry if name in archives} if config.keys() != archives: raise ValueError(f"publisher archives missing from registry: {archives - config.keys()}") sources = args.output / "inputs" sources.mkdir(parents=True) for archive, (digest, url) in config.items(): path = args.archives / f"{archive}.zip" if sha(path) != digest: raise ValueError(f"archive bytes differ from the pinned SHA-256: {path}") unpack(path, sources / archive) archive_preparation = {} if "acmart" in config: archive_preparation["acmart"] = prepare_acmart( sources / "acmart", args.output / "preparation/acmart") if args.texmf_overlay and not args.texmf_overlay.is_dir(): raise ValueError(f"missing overlay: {args.texmf_overlay}") additions = inputs(args.texmf_overlay) if args.texmf_overlay else {} font_map_sha256 = sha(args.font_map) if args.font_map else None def case(item): name, category, archive, entry = item template = sources / archive if archive else ROOT / "fixtures/arxiv-template" evidence = args.output / name evidence.mkdir() frozen = inputs(template) row = {"name": name, "category": category, "archive": archive, "entry": entry, "inputs": frozen} figures = prepare_figures(name, template, entry, evidence, args) row["converted_eps"] = figures for engine in ("reference", "native"): row[engine] = compile_sample(template, entry, evidence / engine, args, engine, figures) assert inputs(template) == frozen assert all(entry not in row[engine]["packaged_files_changed_in_work_directory"] for engine in ("reference", "native")) (evidence / "report.json").write_text(json.dumps(row, indent=2) + "\n") print(name, row["reference"]["pdf_built"], row["native"]["pdf_built"], flush=True) return row with ThreadPoolExecutor(max_workers=2) as pool: results = list(pool.map(case, selected)) report = {"schema": 1, "scope": "compile and collect evidence; PDF creation alone is not fidelity", "archives": config, "native_binary_sha256": sha(args.binary), "native_format_sha256": sha(args.native_format), "reference_format_sha256": sha(args.reference_format), "texmf_overlay": additions, "font_map_sha256": font_map_sha256, "latex_timeout_seconds": args.latex_timeout, "archive_preparation": archive_preparation, "templates": results} assert not args.texmf_overlay or inputs(args.texmf_overlay) == additions assert not args.font_map or sha(args.font_map) == font_map_sha256 (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") if __name__ == "__main__": main()