"""Builds the fixed learning-curve set curve_v1 (request of 21 Nov) and registers it in evalsets.json as a validation set. curve_v1.tsv (shared manifest format) holds, drawn with seed 20261121 from VALIDATION manifests only: - all 500 rows of V1lm (kohtd_lmtune.tsv) - 50 rows per language-script from synth_hand_val - 20 rows per language-script from synth_typed_val - 20 rows per language-script from print_real_val (a language-script that print_real_val lacks is skipped and listed) - 100 rows from synth_clutter_val Each (part, language-script) draw is a function of the seed, the part name and the language only: a part that appears later does not change a part drawn earlier. The builder can be re-run when a source manifest appears; it records every source file's sha256 and which parts are missing in curve_v1_info.json ('complete' is true only when all five parts are present). It refuses any source whose rows are not split == val and any source name that contains 'test' or 'train'. Row ids, texts, groups and units are copied unchanged (KOHTD rows have unit word, the others line). usage: python -I build_curve_set.py [--manifests DIR] [--registry evalsets.json] [--no-register] [--register-only] The evaluation registry is rewritten from scratch by DATA's r5_registry.py: after that script runs, run this one with --register-only. """ import argparse import csv import hashlib import json import os import sys import time import numpy as np csv.field_size_limit(10 ** 9) DATA = "/path/to/TURKIC_OCR_DATA" R5 = DATA + "/data/processed/r5" SEED = 20261121 HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"] PARTS = [ # name, manifest, per language quota (None: all rows; 'total:N' one draw of N) ("V1lm", "kohtd_lmtune.tsv", None), ("synth_hand_val", "synth_hand_val.tsv", 50), ("synth_typed_val", "synth_typed_val.tsv", 20), ("print_real_val", "print_real_val.tsv", 20), ("synth_clutter_val", "synth_clutter_val.tsv", "total:100"), ] def sha(path): h = hashlib.sha256() with open(path, "rb") as f: for b in iter(lambda: f.read(1 << 20), b""): h.update(b) return h.hexdigest() def read(path): with open(path, encoding="utf-8", newline="") as f: rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE) missing = [c for c in HDR if c not in (rd.fieldnames or [])] if missing: raise SystemExit("%s: the shared manifest columns %s are missing (header %s)" % (path, missing, rd.fieldnames)) # extra columns (a slightly different producer) are ignored: the ten shared columns are kept return [{c: (r.get(c) or "") for c in HDR} for r in rd] def draw(rows, k, part, lang): rows = sorted(rows, key=lambda r: r["id"]) if k is None or k >= len(rows): return rows seed = int.from_bytes(hashlib.sha256(("%d|%s|%s" % (SEED, part, lang)).encode()).digest()[:8], "little") idx = sorted(np.random.default_rng(seed).choice(len(rows), size=k, replace=False).tolist()) return [rows[i] for i in idx] def build(man_dir): out_rows, info_parts, missing = [], [], [] for part, fn, quota in PARTS: if "test" in fn or "train" in fn: raise SystemExit("refusing source %s" % fn) p = os.path.join(man_dir, fn) if not os.path.exists(p): missing.append(part) info_parts.append({"part": part, "manifest": p, "status": "missing at build time"}) continue rows = read(p) bad = [r["id"] for r in rows if r["split"] != "val"] if bad: raise SystemExit("%s has %d rows that are not split val (first %s): refusing" % (fn, len(bad), bad[0])) chosen, short = [], {} if quota is None: chosen = draw(rows, None, part, "all") elif isinstance(quota, str): chosen = draw(rows, int(quota.split(":")[1]), part, "all") if len(chosen) < int(quota.split(":")[1]): short["all"] = len(chosen) else: by = {} for r in rows: by.setdefault(r["lang"], []).append(r) for lang in LANGS: if lang not in by: short[lang] = 0 continue c = draw(by[lang], quota, part, lang) if len(c) < quota: short[lang] = len(c) chosen += c langs = {} for r in chosen: langs[r["lang"]] = langs.get(r["lang"], 0) + 1 out_rows += chosen info_parts.append({"part": part, "manifest": p, "manifest_sha256": sha(p), "source_rows": len(rows), "rows_drawn": len(chosen), "per_language": langs, "short_languages": short, "status": "included"}) return out_rows, info_parts, missing def register(registry_path, man_path, rows, info): reg = json.load(open(registry_path, encoding="utf-8")) sets = [s for s in reg["sets"] if s.get("name") != "curve_v1"] langs = {} for r in rows: langs[r["lang"]] = langs.get(r["lang"], 0) + 1 sets.append({ "name": "curve_v1", "manifest": man_path, "split": "val", "locked": False, "status": "ready", "purpose": "Fixed learning-curve set: all 500 V1lm rows, 50 synth_hand_val rows, 20 synth_typed_val rows and 20 print_real_val rows per " "language-script, 100 synth_clutter_val rows (seed 20261121). Scored at 25%, 50%, 75% and 100% of P_short to draw learning curves.", "n_rows": len(rows), "n_groups": len({r["group"] for r in rows}), "manifest_sha256": sha(man_path), "langs": langs, "unit": "word and line (per row)", "group_unit": "KOHTD form for the handwriting words, source page for synthetic lines, document for real print", "split_rule": "rows copied from validation manifests only", "complete": info["complete"], "missing_parts": info["missing_parts"], "owner": "EVALCODE", "built_utc": info["built_utc"], "note": "a part that was missing at build time is added by re-running build_curve_set.py; the manifest hash then changes"}) reg["sets"] = sets tmp = registry_path + ".tmp%d" % os.getpid() with open(tmp, "w", encoding="utf-8") as f: json.dump(reg, f, ensure_ascii=False, indent=1) os.replace(tmp, registry_path) def main(): ap = argparse.ArgumentParser() ap.add_argument("--manifests", default=R5 + "/manifests") ap.add_argument("--registry", default=R5 + "/evalsets.json") ap.add_argument("--no-register", action="store_true") ap.add_argument("--register-only", action="store_true") ap.add_argument("--final", action="store_true", help="freeze: write curve_v1_frozen.json; later builds are refused") a = ap.parse_args() man_path = os.path.join(a.manifests, "curve_v1.tsv") info_path = os.path.join(os.path.dirname(a.manifests.rstrip("/")), "curve_v1_info.json") frozen_path = os.path.join(os.path.dirname(a.manifests.rstrip("/")), "curve_v1_frozen.json") if os.path.exists(frozen_path) and not a.register_only: sys.exit("curve_v1 is frozen (%s): it is never rebuilt after the first run starts, so every learning curve stays comparable" % frozen_path) if a.register_only: rows = read(man_path) info = json.load(open(info_path, encoding="utf-8")) register(a.registry, man_path, rows, info) print("registered curve_v1 (%d rows)" % len(rows)) return rows, parts, missing = build(a.manifests) ids = [r["id"] for r in rows] if len(ids) != len(set(ids)): raise SystemExit("duplicate ids in the curve set") tmp = man_path + ".tmp%d" % os.getpid() with open(tmp, "w", encoding="utf-8", newline="") as f: f.write("\t".join(HDR) + "\n") for r in rows: f.write("\t".join(r[c] for c in HDR) + "\n") os.replace(tmp, man_path) info = {"name": "curve_v1", "built_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "seed": SEED, "rows": len(rows), "manifest": man_path, "manifest_sha256": sha(man_path), "parts": parts, "missing_parts": missing, "complete": not missing} with open(info_path, "w", encoding="utf-8") as f: json.dump(info, f, ensure_ascii=False, indent=1) print("curve_v1: %d rows; parts missing: %s; complete: %s" % (len(rows), missing, not missing)) for p in parts: print(" ", p["part"], p.get("rows_drawn"), p.get("short_languages") or "", p["status"]) if not a.no_register: register(a.registry, man_path, rows, info) print("registered in", a.registry) if a.final: fz = {"frozen_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "manifest": man_path, "manifest_sha256": info["manifest_sha256"], "rows": len(rows), "rows_by_part": {p["part"]: p.get("rows_drawn", 0) for p in parts}, "missing_parts_left_out_for_good": missing, "short_languages": {p["part"]: p.get("short_languages") for p in parts if p.get("short_languages")}} with open(frozen_path, "w", encoding="utf-8") as f: json.dump(fz, f, ensure_ascii=False, indent=1) print("FROZEN:", json.dumps(fz, ensure_ascii=False)) if __name__ == "__main__": main()