Cotton code
66 lines · 3.1 KB · PythonRaw
#!/usr/bin/env python3"""The held-out writers as a corpus folder of their own: `pnpm ink:heldout <corpus dir> <out dir> [results.json]`.The letter model (`scripts/ink/train.py`) never saw UJIpenchars2's `tst_`writers, nor the HWRT writers it named in `<corpus dir>/heldout-writers.json`.Their lines go to `<out dir>/<dataset>.jsonl`, each with its own label, so theone replay (`pnpm ink:corpus <out dir>`, the core's `ink::replay`) readsexactly them. With the model's `results.json`, itsown held-out accuracy goes to `<out dir>/expected.json` — each letter readwhere letters are admitted, each digit where digits are (`admitted`: a deck ofnames, a numeric column): the phone's path must read the same, with nofloor, within half a point. And the input contract'sfixtures (`ink_input.py`: the first 40 lines of each dataset and theirencoding) go to `<out dir>/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 jsonimport osimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import ink_input  # noqa: E402DATASETS = ["ujipenchars2", "hwrt"]def held_out(row, named):    if row["source"] == "ujipenchars2":        return row["writer"].startswith("tst_")    return row["writer"] in nameddef main():    if len(sys.argv) not in (3, 4):        sys.exit("usage: corpus-heldout.py <corpus dir> <out dir> [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()