"""Builds records/R5/TESTPASS2/results.json from the cluster results table (results_cluster.json), plan.json and checks.json: per set and model n, CER with interval, WER, exact match, invented-text figures, and per-set notes (label status, caveats). usage: tp2_finalize.py TESTPASS2_DIR RESULTS_CLUSTER_JSON """ import hashlib import json import os import sys TP, RC = sys.argv[1], sys.argv[2] R = json.load(open(RC, encoding="utf-8")) P = json.load(open(os.path.join(TP, "plan.json"), encoding="utf-8")) K = json.load(open(os.path.join(TP, "checks.json"), encoding="utf-8")) NOTES = { "az_localdoc_test": "real Azerbaijani (Latin) handwriting, 29 phone-photographed pages, at least 3 writers; intervals wide", "rukopys_test": ("Ukrainian (not a target language): unseen Cyrillic handwriting; no evidence of contamination (checks.json); crop-to-label " "review: 5 of 20 random crops do not match their label exactly (25%, Wilson 95% 11-47%), 2 of 20 strictly (10%, 3-30%), " "6 of the 10 worst M1 rows are label or crop problems, so CER is an upper bound of reading error (checks.json " "rukopys_alignment)"), "hkr_test1": "descriptive: labels are the printed template texts, no human check stated; HKR split is not form-disjoint from train", "hkr_test2": "descriptive: as hkr_test1", "chd_test": "descriptive: label provenance not stated; 615 of 1,544 test words also occur in CHD train (registry caution)", "school_test": "descriptive: transcribed by the dataset team, human or model not stated; page-disjoint official split", "synth_hand_test": "generated handwriting, held-out text and fonts; exact labels; 20 rows have a near-duplicate training image", "synth_typed_test": "generated typed lines, held-out text; exact labels; 108 rows have a near-duplicate training image (22 same text)", } def slim(r): if r.get("status") != "scored": return r out = {"n": r["n"], "clusters": r["n_clusters"], "cluster_unit": r["cluster_unit"]} for k in ("cer", "wer", "exact_match", "cer_casefold", "hr3", "hr4", "fabricated_word_rate", "empty_output_rate"): if k in r: out[k] = r[k] out["hit_cap_rows"] = r.get("hit_cap_rows") out["pred_sha256"] = r.get("pred_sha256") out["scored_utc"] = r.get("scored_utc") out["scorer_code_sha256"] = r.get("scorer_code_sha256") return out res = {"plan_sha256": hashlib.sha256(open(os.path.join(TP, "plan.json"), "rb").read()).hexdigest(), "source": "DATA/outputs/r5/testpass2/results_cluster.json (tp2_results.py)", "figure": "plain profile (N0) CER, greedy decoding; 95% cluster bootstrap B 10000 seed 20261121; M2 figures reused from the 24 Nov sealed pass", "crops": {}, "pages": {}} for s, c in R["crops"].items(): cell = {"label_status": P["sets"][s]["status"], "label_provenance": P["sets"][s]["label_provenance"], "notes": NOTES.get(s, ""), "models": {m: dict(slim(c.get(m, {"status": "not run"})), batching=c.get(m, {}).get("batching")) for m in ("M1", "M2_labelfree_greedy", "M2_labelfree_gated_lm", "Qwen3-VL-2B", "M2_greedy", "M2_gated_lm")}} cell["models"]["M1"].pop("batching", None) cell["models"]["Qwen3-VL-2B"].pop("batching", None) for k in ("paired_M1_minus_M2_labelfree_greedy", "paired_M1_minus_M2_greedy_labellength"): if k in c: cell[k + "_descriptive"] = c[k] if "sensitivity_without_duplicate_partner_rows" in c: cell["sensitivity_without_duplicate_partner_rows"] = c["sensitivity_without_duplicate_partner_rows"] res["crops"][s] = cell for nm, p in R["pages"].items(): res["pages"][nm] = p res["pages_notes"] = {"tob_hand": "primary; human-checked references; M28 reading order is the figure to read; M29 is weak (logical lines)", "tob_print": "descriptive; 5 text categories only; multi-column pages are read across columns"} if len(sys.argv) > 3 and os.path.exists(sys.argv[3]): kz = json.load(open(sys.argv[3], encoding="utf-8")) kz.pop("per_page_counts", None) res["pages"]["kzb_hand"] = kz res["pages_notes"]["kzb_hand"] = ("DESCRIPTIVE ONLY (plan amendment 2): references model-drafted then corrected; the human check is the " "card's claim, qualified by the card itself; pages from public web image search") if len(sys.argv) > 4 and os.path.exists(sys.argv[4]): kc = json.load(open(sys.argv[4], encoding="utf-8")) res["kohtd_test_M2_labelfree_rescore"] = { "note": ("plan amendment 4 (owner-authorized): M2 re-read label-free on kohtd_test; M1 = the final model's existing 24 Nov predictions; " "the 24 Nov M2 rows used label-length batching and LEAK reference length (kept for the record); primary reading repaired_refs; " "slice:P2 = the verdict's recomputed unseen-word slice (2,228), slice:registry_P2 = registered 2,558; form bootstrap B 10000 " "seed 20261121; without_form_1868 is a sensitivity only"), **kc} if len(sys.argv) > 5 and os.path.exists(sys.argv[5]): res["error_analysis"] = json.load(open(sys.argv[5], encoding="utf-8")) json.dump(res, open(os.path.join(TP, "results.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) print("results.json written")