#!/usr/bin/env python3 """The held-out writers as a corpus folder of their own: `pnpm ink:heldout [results.json]`. The letter model (`scripts/ink/train.py`) never saw UJIpenchars2's `tst_` writers, nor the HWRT writers it named in `/heldout-writers.json`. Their lines go to `/.jsonl`, each with its own label, so the one replay (`pnpm ink:corpus `, the core's `ink::replay`) reads exactly them. With the model's `results.json`, its own held-out accuracy goes to `/expected.json` — each letter read where letters are admitted, each digit where digits are (`admitted`: a deck of names, a numeric column): the phone's path must read the same, with no floor, within half a point. And the input contract's fixtures (`ink_input.py`: the first 40 lines of each dataset and their encoding) go to `/contract/fixtures.jsonl`, which the core's encoder (`cotton_core::ink::input`) is held to by the same replay. Nothing here is ever committed: the corpus is real hands. """ import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import ink_input # noqa: E402 DATASETS = ["ujipenchars2", "hwrt"] def held_out(row, named): if row["source"] == "ujipenchars2": return row["writer"].startswith("tst_") return row["writer"] in named def main(): if len(sys.argv) not in (3, 4): sys.exit("usage: corpus-heldout.py [results.json]") corpus, out = sys.argv[1], sys.argv[2] named = set(json.load(open(os.path.join(corpus, "heldout-writers.json")))) os.makedirs(os.path.join(out, "contract"), exist_ok=True) fixtures = open(os.path.join(out, "contract", "fixtures.jsonl"), "w") total = 0 for name in DATASETS: kept = 0 with open(os.path.join(corpus, f"{name}.jsonl")) as f, open(os.path.join(out, f"{name}.jsonl"), "w") as held: for i, line in enumerate(f): row = json.loads(line) if i < 40: points, count = ink_input.encode(row["strokes"]) fixtures.write(json.dumps({"strokes": row["strokes"], "label": row["label"], "case": row["case"], "points": points, "stroke_count": count}) + "\n") if held_out(row, named): held.write(line if line.endswith("\n") else line + "\n") kept += 1 print(f"{name}: {kept} held-out groups") total += kept if len(sys.argv) == 4: results = json.load(open(sys.argv[3])) expected = {"letter_confidence": 0, "kept": results["held_out"]["all"]["admitted"] / 100, "within": 0.005, "groups": results["split"]["held_out"]} if expected["groups"] != total: sys.exit(f"results.json held out {expected['groups']} groups, the corpus {total}") json.dump(expected, open(os.path.join(out, "expected.json"), "w"), indent=2) print(f"expected: {expected['kept']:.3f} as kept, within {expected['within']}") if __name__ == "__main__": main()