"""Compare the frozen ONNX reader with the early-print reader and native frak2021.""" import argparse from collections import Counter from hashlib import sha256 from io import BytesIO import json from pathlib import Path import subprocess import sys from zipfile import ZipFile from PIL import Image from safetensors.torch import save_file import torch from tesserocr import OEM, PSM, PyTessBaseAPI from folio_fraktur import FrakturReader from metrics import score def write(path, value): path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n") def export(args): freeze = json.loads((args.run / "freeze.json").read_text()) weights = args.run / "best.pt" if not freeze["selected"] or sha256(weights.read_bytes()).hexdigest() != freeze["sha256"]: raise ValueError("Checkpoint does not match the validation freeze") vocab = json.loads((args.pack / "vocabulary.json").read_text()) dest = args.output / "portable" dest.mkdir(parents=True, exist_ok=True) write(dest / "config.json", dict(format="folio-fraktur-line-v1", height=40, alphabet=vocab)) save_file(torch.load(weights, map_location="cpu", weights_only=True), str(dest / "model.safetensors")) subprocess.run([sys.executable, str(args.exporter), str(dest), str(dest)], check=True) write(args.output / "weight-digests.json", {p.name:sha256(p.read_bytes()).hexdigest() for p in sorted(dest.iterdir()) if p.is_file()}) return dest, vocab def main(args): dest, vocab = export(args) new = FrakturReader(dest) old = FrakturReader(args.early) # Verify agreement with training-time decoding before opening reserved labels. va = list(map(json.loads,(args.pack / "validation.jsonl").read_text().splitlines())) ref = {r["id"]:r["prediction"] for r in map(json.loads,(args.run / "best-validation.jsonl").read_text().splitlines())} equal = 0 with ZipFile(args.pack / "validation.zip") as archive: for row in va: with Image.open(BytesIO(archive.read(row["image"]))) as image: equal += new(image) == ref[row["id"]] write(args.output / "parity.json",dict(lines=len(va),identical=equal)) if equal < .98 * len(va): raise ValueError("Inspect ONNX export discrepancy before evaluation") rows = [] missing = Counter() with ZipFile(args.pack / "test.zip") as archive, PyTessBaseAPI(path=str(args.tessdata), lang="frak2021", oem=OEM.LSTM_ONLY, psm=PSM.SINGLE_LINE) as native, (args.output / "test-predictions.jsonl").open("w") as stream: for row in map(json.loads,(args.pack / "test.jsonl").read_text().splitlines()): with Image.open(BytesIO(archive.read(row["image"]))) as im: image=im.convert("RGB") native.ClearAdaptiveClassifier() native.SetImage(image) try: text=native.GetUTF8Text().strip() finally: native.Clear() r = {k:row[k] for k in ("id","author","book","page","line_id","pixel_sha256","text")} r["predictions"] = dict(adapted=new(image), early=old(image), mannheim=text) missing.update(c for c in row["text"] if c not in vocab) rows.append(r) print(json.dumps(r,ensure_ascii=False),file=stream) measures = {name:score([dict(text=r["text"],prediction=r["predictions"][name],author=r["author"]) for r in rows]) for name in ("adapted","early","mannheim")} stats = {k:v["diplomatic"]["total"] for k,v in measures.items()} passed = all(stats["adapted"][key] < stats[other][key] for other in ("early","mannheim") for key in ("cer","macro_author_cer")) write(args.output / "test-scores.json", dict(passed=passed, scores=measures, unseen_symbols=missing, unseen_reference_chars=sum(missing.values()))) print(stats, "passed", passed, flush=True) if __name__ == "__main__": parser=argparse.ArgumentParser(description=__doc__) for key in ("run","pack","early","tessdata","exporter","output"): parser.add_argument(key,type=Path) main(parser.parse_args())