"""R5 DATA: manifest statistics, the evaluation registry (evalsets.json) and the effective mix_v1 shares. Reads only the manifests (text columns); opens no image. Run on a cluster compute node after dedupe (and again when GEN's manifests appear). Writes DATA/data/processed/r5/manifest_stats.json, DATA/data/processed/r5/evalsets.json, DATA/outputs/r5/mix_v1_shares.json. """ import collections import hashlib import json import time from pathlib import Path R5 = Path("/path/to/TURKIC_OCR_DATA/data/processed/r5") MAN = R5 / "manifests" OUTD = Path("/path/to/TURKIC_OCR_DATA/outputs/r5") HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] NOW = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) def sha256_file(p): h = hashlib.sha256() with open(p, "rb") as f: for c in iter(lambda: f.read(1 << 20), b""): h.update(c) return h.hexdigest() def stats(p): rows = [] with open(p, encoding="utf-8", newline="") as f: assert f.readline().rstrip("\n").split("\t") == HDR, p for line in f: rows.append(line.rstrip("\n").split("\t")) return { "rows": len(rows), "groups": len({r[8] for r in rows}), "chars": sum(len(r[2]) for r in rows), "by_lang": dict(collections.Counter(r[3] for r in rows)), "by_script": dict(collections.Counter(r[4] for r in rows)), "by_kind": dict(collections.Counter(r[5] for r in rows)), "by_source": dict(collections.Counter(r[6] for r in rows)), "by_split": dict(collections.Counter(r[7] for r in rows)), "by_unit": dict(collections.Counter(r[9] for r in rows)), "empty_labels": sum(1 for r in rows if r[2] == ""), "sha256": sha256_file(p), "path": str(p), } mstats = {} for p in sorted(MAN.glob("*.tsv")): if p.name.endswith(".meta.tsv"): # FREEZE 21 Nov: GEN's per-row sidecars are not manifests (extra columns) continue mstats[p.stem] = stats(p) json.dump({"generated_utc": NOW, "manifests": mstats}, open(R5 / "manifest_stats.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) def entry(name, manifest, split, purpose, locked, **kw): path = MAN / (manifest + ".tsv") e = {"name": name, "manifest": str(path), "split": split, "purpose": purpose, "locked": locked} if manifest in mstats: s = mstats[manifest] e.update(status="ready", n_rows=s["rows"], n_groups=s["groups"], manifest_sha256=s["sha256"], langs=s["by_lang"], unit=list(s["by_unit"])[0] if s["by_unit"] else None) else: e.update(status="placeholder: manifest not written yet (planned path)", n_rows=None, n_groups=None, manifest_sha256=None) e.update(kw) assert " " not in name and "(" not in name, "evalset names are used in file paths" return e p2info = json.load(open(R5 / "p2_slice_info.json")) if (R5 / "p2_slice_info.json").exists() else {} p2_final = bool(p2info.get("final")) sets = [ # ---- validation sets (selection only; never used for the final claim) entry("V1", "kohtd_screen_v1", "val", "KOHTD validation screen set of the zero-shot screen: at most 15 crops per validation form, 3,678 crops (screen rule v1). Selection of B1 and B2 by amendment 3.2 C6 uses CER on this set.", False, group_unit="KOHTD form", source_of_list="records/R4/J2_screen/screen_set_v1.tsv, sha256 aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec (matches the cluster copy), used unchanged", split_rule="form-disjoint from KOHTD train and test (K1 split v1)"), entry("V1lm", "kohtd_lmtune", "val", "500 KOHTD validation crops that are not in V1 (numpy default_rng(20261121)). Only for tuning the weights of post-processing (language model, fixed script).", False, group_unit="KOHTD form", split_rule="subset of KOHTD validation, disjoint from V1"), entry("kohtd_val", "kohtd_val", "val", "All 16,238 KOHTD validation crops (258 forms); superset of V1 and V1lm. Reported as the wider validation figure; selection uses V1.", False, group_unit="KOHTD form", split_rule="K1 split v1: sha256 of 'KOHTD-split-v1-2026-11-20:'+form id, first 8 hex digits mod 100 in 70..84"), entry("hkr_val", "hkr_val", "val", "HKR words, validation part of the audit-recorded official split (Russian and Kazakh handwriting words). Cyrillic handwriting check.", False, group_unit="HKR template and filled-form instance (project inference)", split_rule="the split recorded in the project audit manifest (described there as the official CSV split; not re-read from the CSV in R5); NOT form-disjoint", caution="the HKR split puts crops of the same filled forms in train, val and test; sizes differ from the 5,057-per-part figures of one published paper; use it for rough comparison, not as proof of generalisation to new writers"), entry("chd_val", "chd_val", "val", "Cyrillic Handwriting Dataset (Russian words): 5% of train word types held out for validation (the dataset ships no validation part).", False, group_unit="word type (the dataset has no writer or page id)", split_rule="word type with sha256('R5-chd-val-v1:'+label) first 8 hex digits mod 100 below 5; a word type never sits in both train and val", caution="writer identity is unknown, so the same hand may appear in train and val"), entry("school_val", "school_val", "val", "School notebooks (Russian), word crops of the 150 official validation pages.", False, group_unit="notebook page", split_rule="official page split of the dataset kept (train 1,557 / val 150 / test 150 pages, no page in two parts)"), entry("hkr_val_s2000", "hkr_val_s2000", "val", "OPTIONAL small version of hkr_val: 2,000 rows drawn with seed 20261121 (default_rng.choice), for cheap validation passes.", False, subset_of="hkr_val", group_unit="HKR template and filled-form instance"), entry("chd_val_s2000", "chd_val_s2000", "val", "OPTIONAL small version of chd_val: 2,000 rows drawn with seed 20261121.", False, subset_of="chd_val", group_unit="word type"), entry("school_val_s2000", "school_val_s2000", "val", "OPTIONAL small version of school_val: 2,000 rows drawn with seed 20261121 over the 150 validation pages.", False, subset_of="school_val", group_unit="notebook page"), entry("synth_hand_val", "synth_hand_val", "val", "Synthetic handwriting line crops (10 language-scripts, 1,000 each planned), with two held-out fonts per script (unseen-font check).", False, group_unit="composed page", owner="GEN"), entry("synth_typed_val", "synth_typed_val", "val", "Synthetic typed line crops (500 per language-script planned).", False, group_unit="source document", owner="GEN"), entry("synth_clutter_val", "synth_clutter_val", "val", "Clutter crops with no text; the target is the empty string (500 planned). Measures hallucination.", False, owner="GEN"), entry("synth_pages_val", "synth_pages_val", "val", "Composed pages with line boxes and polygons (300 planned), for detector validation.", False, owner="GEN"), # ---- test sets (locked) entry("kohtd_test", "kohtd_test", "test", "Primary endpoint P1: CER on all 18,615 KOHTD test crops of 305 forms.", True, group_unit="KOHTD form", endpoint="P1", split_rule="K1 split v1, share 85..99 of the form hash", caution="form-disjoint, not writer-disjoint (writer ids do not exist); labels are crowd labels (two volunteers agreeing)"), entry("kohtd_test_p2", "kohtd_test_p2", "test", "Primary endpoint P2: KOHTD test crops whose normalised label (NFC, lower case, letters and digits only) is in no handwriting training label (version 3 section 1).", True, group_unit="KOHTD form", split_rule="slice of kohtd_test by label, computed by scripts/r5_p2_slice.py from the final train manifests", endpoint="P2", provisional=not p2_final, p2_info=p2info, note="provisional until GEN's synthetic train manifests exist; rerun r5_p2_slice.py then (it records which train manifests it used)"), entry("kohtd_test_p2b", "kohtd_test_p2b", "test", "Reported only: P2 crops whose normalised label equals no whitespace token of any training label of any kind (real, synthetic handwriting, synthetic typed).", True, group_unit="KOHTD form", endpoint="P2b (reported only)", split_rule="slice of P2", provisional=not p2_final), entry("hkr_test1", "hkr_test1", "test", "HKR words, test1 part of the audit-recorded official split (rough comparison with published figures).", True, group_unit="HKR template and filled-form instance", split_rule="project audit record of the official split, kept", caution="not form-disjoint from train; 4,966 rows against 5,057 in one published paper"), entry("hkr_test2", "hkr_test2", "test", "HKR words, test2 part of the audit-recorded official split (rough comparison with published figures).", True, group_unit="HKR template and filled-form instance", split_rule="project audit record of the official split, kept", caution="not form-disjoint from train; 5,043 rows against 5,057 in one published paper"), entry("chd_test", "chd_test", "test", "Cyrillic Handwriting Dataset, official test part (1,544 Russian word crops).", True, group_unit="word type", split_rule="official train/test split of the dataset kept", caution="615 of 1,544 test crops carry a word that also occurs in CHD train; writers unknown"), entry("school_test", "school_test", "test", "School notebooks (Russian), word crops of the 150 official test pages.", True, group_unit="notebook page", split_rule="official page split of the dataset kept"), entry("rukopys_test", "rukopys_test", "test", "RUKOPYS test split (Ukrainian handwriting; 385 pages; lines cut from the handwritten, legible, Ukrainian boxes, human-annotated). Cyrillic handwriting on photos and scans; lang is 'other'.", True, group_unit="page", split_rule="official test split of the dataset; no training data of RUKOPYS is used in R5 (only the test split is on the cluster)"), entry("az_localdoc_test", "az_localdoc_test", "test", "EXTRA (added by stage DATA beyond the plan): 442 real Azerbaijani (Latin) handwriting lines from 29 phone-photographed pages, annotated by hand in Label Studio with exact transcriptions (LocalDoc/azerbaijani-htr-benchmark, CC BY 4.0). The only real handwriting of a Latin-script target language that could be obtained openly; unknown writers (at least 3 hands). lang az.", True, group_unit="source page", split_rule="the dataset ships one test split only; used as a test set only, never for training", added_beyond_plan=True, caution="test-sized (442 lines) and few writers; intervals will be wide"), entry("synth_hand_test", "synth_hand_test", "test", "Synthetic handwriting line crops, held-out text and held-out fonts (1,000 per language-script planned).", True, owner="GEN"), entry("synth_typed_test", "synth_typed_test", "test", "Synthetic typed line crops from held-out text (500 per language-script planned).", True, owner="GEN"), entry("synth_clutter_test", "synth_clutter_test", "test", "Clutter crops, empty target (500 planned).", True, owner="GEN"), entry("synth_pages_test", "synth_pages_test", "test", "Composed test pages with line polygons (300 planned) for Level P if a detector exists.", True, owner="GEN"), ] listed = [{ "name": "TurkishOCR-Bench (moganai)", "manifest": None, "split": "test", "locked": True, "purpose": "488 Turkish pages in 10 categories, 50 of them handwritten phone photos (the only real Turkish handwriting held).", "status": "listed, not used in R5", "reason": "its licence is an open owner question: the pages carry mixed per-page licences (by-nc, by, by-sa, FSEK, and 'no licence stated' for the 50 handwritten pages)", "held_at": "/path/to/TURKIC_OCR_DATA/data/raw/turkishocr_bench"}] reg = { "registry_version": "r5-evalsets-1", "generated_utc": NOW, "format": "manifest TSV columns: id, image, text, lang, script, kind, source, split, group, unit (R5 common specification). Every test set is locked: no process opens its images or runs a model on it before the single scoring pass after 22 Nov 2026 19:00 UTC.", "sets": sets, "listed_not_used": listed, "hash_note": "images were hashed (sha256 and 64-bit pHash) for the duplicate check; no test image was shown or scored", } json.dump(reg, open(R5 / "evalsets.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) # ---- effective mix_v1 shares n_train = {k: mstats[k]["rows"] for k in ("kohtd_train", "hkr_train", "chd_train", "school_train") if k in mstats} latin_items = 0 # no Turkish (or other Latin-script) handwriting word or line set is held: the Turkish sets are single characters latin_cap_share = min(0.05, 5 * latin_items / 1e6) other_cyr = {} for k in ("hkr_train", "chd_train", "school_train"): n = n_train.get(k, 0) want = round(0.15 / 3 * 1e6) # samples per 1M cap = 3 * n other_cyr[k] = {"train_items": n, "requested_samples_per_1M": want, "cap_3_passes_samples_per_1M": cap, "passes_at_request_per_1M": round(want / n, 3) if n else None, "cap_binds": want > cap} moved = round(0.05 - latin_cap_share, 6) latin = ["uz_latn", "tr", "az", "tk"] cyr = ["kk", "ky", "uz_cyrl", "tt", "ba", "sah"] hand_synth_each = {l: 0.30 / 10 for l in cyr + latin} for l in latin: hand_synth_each[l] += moved / len(latin) mix = { "set_by": "the R5 DATA plan; the shares below are written unchanged", "shares_as_set": { "hand_real_kk (KOHTD train)": 0.35, "hand_real_other_cyrillic (HKR train, CHD train, school_notebooks train; equal by source; at most 3 passes of a source per 1M samples)": 0.15, "hand_real_latin (Turkish handwriting train)": 0.05, "hand_synth (equal across the 10 language-scripts)": 0.30, "typed_synth (equal across the 10 language-scripts)": 0.12, "clutter (empty string target)": 0.03, }, "clause_applied_hand_real_latin": { "rule": "if fewer than 5,000 items, the share drops to what 5 repeats per 1M samples allow, and the rest moves to hand_synth Latin", "items_available": latin_items, "why_zero": "no Latin-script handwriting set of words or lines that can be used for TRAINING is on the cluster (the only real Latin-script lines held are the 442 Azerbaijani test-only lines, which must never be trained on): the Turkish and Azerbaijani handwriting sets held are single characters (T-H-E copies, Turkish special characters, AzEMNIST, a set of 835,750 character images); TurkishOCR-Bench handwriting is 50 pages and is listed, not used", "allowed_share": latin_cap_share, "moved_to_hand_synth_latin": moved, }, "other_cyrillic_sources_check": other_cyr, "kohtd_train_passes_per_1M_samples": round(0.35 * 1e6 / n_train["kohtd_train"], 3) if n_train.get("kohtd_train") else None, "effective_shares": { "hand_real_kk": 0.35, "hand_real_other_cyrillic": 0.15, "hand_real_latin": latin_cap_share, "hand_synth": round(0.30 + moved, 6), "typed_synth": 0.12, "clutter": 0.03, "sum": round(0.35 + 0.15 + latin_cap_share + 0.30 + moved + 0.12 + 0.03, 6)}, "hand_synth_share_per_language_script": {k: round(v, 6) for k, v in hand_synth_each.items()}, "assumption_flag": "the 5 points moved to hand_synth Latin are split equally over the four Latin-script language-scripts (uz_latn, tr, az, tk); this is DATA's reading of the clause, another split may be chosen", "typed_synth_share_per_language_script": {k: 0.012 for k in cyr + latin}, "train_items_after_dedupe": n_train, "generated_utc": NOW, } OUTD.mkdir(parents=True, exist_ok=True) json.dump(mix, open(OUTD / "mix_v1_shares.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) print("written: manifest_stats.json, evalsets.json, mix_v1_shares.json;", len(mstats), "manifests;", sum(1 for s in sets if s["status"] == "ready"), "sets ready")