Download scripts/r5_erran/erran_analysis.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 56.4 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_erran/erran_analysis.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_erran/erran_analysis.py
-
curl -L -o erran_analysis.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_erran/erran_analysis.py
56.4 kB
"""ERRAN (R5): descriptive error analysis of every arm on VALIDATION data only.
Tasks (ERRAN plan):
1 error taxonomy on V1 (KOHTD validation screen set) and on hkr/chd/school _val_s2000, with form-bootstrap intervals,
top-20 confusion pairs and per-letter error rates of the Kazakh special letters;
3 overlap of error-crop sets between arms (Jaccard) and the crops every arm gets wrong;
4 attribute breakdown on synth_hand_val, synth_typed_val, print_real_val and synth_clutter_val from the generator side files;
6 learning curves on curve_v1 (25/50/75/100% of P_short).
Scoring conventions are those of the frozen R5 scorer (CODE/src/r5eval): reference = manifest text joined on id after N0,
output = N0 of the TSV hyp, alignment = r5eval.align.align_ops (J2 tie-break), bootstrap = r5eval.stats weights (seed 20261121,
B = 10,000, clusters = the manifest 'group' column: forms for KOHTD, form instances for HKR, pages, source documents).
Locked (test) sets are never opened: every manifest path is taken from a registry entry whose split is 'val' and locked is false.
Private outputs (reference and output strings of real persons' handwriting) are written only under OUT/private/ on the cluster.
The public JSON files contain counts, rates and single characters only.
"""
import argparse
import collections
import json
import os
import sys
import time
import unicodedata
import numpy as np
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
from r5eval import stats # noqa: E402
from r5eval.align import align_ops, lev_fast # noqa: E402
from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket # noqa: E402
from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic # noqa: E402
from r5eval.lookalike import PARTNER, repair_label # noqa: E402
from r5eval.textnorm import fold_lower, char_script_set, norm # noqa: E402
D = "/path/to/TURKIC_OCR_DATA"
PREDS = D + "/outputs/r5/preds"
SCORES = D + "/outputs/r5/scores"
REG = D + "/data/processed/r5/evalsets.json"
B = stats.B_DEFAULT
SEED = stats.SEED_BASE
P_SHORT = 150000
VLM_ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "qwen3_vl_2b", "lightonocr_3_0_8b", "glm_ocr", "teleocr",
"ovisocr2", "ovisocr3", "lightonocr_3_1b", "granite_docling_258m"]
LINE_ARMS = [("A1", "long"), ("A1", "long_lm_gated"), ("A2", "long_lm_gated"), ("A3", "long")]
TAX_SETS = ["V1", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000"]
ATTR_SETS = ["synth_hand_val", "synth_typed_val", "print_real_val", "synth_clutter_val"]
CURVE_ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "qwen3_vl_2b", "lightonocr_3_0_8b", "glm_ocr", "teleocr",
"ovisocr2", "ovisocr3", "lightonocr_3_1b", "granite_docling_258m", "firered_ocr", "oxr_1_0", "surya_ocr_2_5",
"mineru2_5_pro", "A1", "A2", "A3", "A1s", "A4"]
MIN_ROWS = 30
# Kazakh special letter -> Russian look-alike (frozen scorer table, lower case; analyse._PARTNER_LOWER['kk'] via COLLAPSE)
KK_PAIRS_LOWER = {k: v for k, v in COLLAPSE["kk"].items() if k == k.lower()}
KK_SPECIAL_LOWER = set(KK_PAIRS_LOWER)
KK_PLAIN_TO_SPECIAL = collections.defaultdict(set)
for _s, _p in KK_PAIRS_LOWER.items():
KK_PLAIN_TO_SPECIAL[_p].add(_s)
KK_ALL_SPECIAL = set(LETTERS["kk"])
FINE_TO_COARSE = {
"kk_collapse_to_russian": "kazakh_letter_vs_russian_lookalike",
"kk_overgeneration": "kazakh_letter_vs_russian_lookalike",
"kk_letter_swapped_for_another_kk_letter": "kazakh_letter_vs_another_kazakh_letter",
"wrong_script_in_output": "wrong_script_lookalike",
"offscript_letter_in_reference": "reference_has_offscript_letter",
"case_only": "case_only",
"space_words_merged": "space_words_merged_or_split",
"space_word_split": "space_words_merged_or_split",
"space_substituted": "space_words_merged_or_split",
"space_next_to_punctuation": "space_next_to_punctuation",
"punctuation_or_symbol": "punctuation_or_symbol",
"digit": "digit",
"other_substitution": "other_substitution",
"other_deletion": "other_deletion",
"other_insertion": "other_insertion",
}
CROP_LEVEL = ["empty_output", "truncation", "extra_text_after_correct_reading", "unrelated_cer_above_0_8"]
FINE = list(FINE_TO_COARSE)
COARSE = []
for _c in FINE_TO_COARSE.values():
if _c not in COARSE:
COARSE.append(_c)
CHAR_CLASSES = CROP_LEVEL + FINE
CROP_CLASSES = CROP_LEVEL + COARSE + ["mixed"]
PLAIN_NAMES = {
"empty_output": "the model gave no text at all",
"truncation": "the output is a proper prefix of the reference (reading stopped early)",
"extra_text_after_correct_reading": "the reference is a proper prefix of the output (correct reading, then extra text)",
"unrelated_cer_above_0_8": "output unrelated to the reference: crop CER above 0.8 and a reference of at least 3 characters (and not one of the three cases above); shorter references are classified by their edit operations",
"kk_collapse_to_russian": "a Kazakh letter (Ә Ғ Қ Ң Ө Ұ Ү Һ І) read as its Russian look-alike (А Г К Н О У У Х И), either case",
"kk_overgeneration": "a Russian letter (А Г К Н О У Х И) read as a Kazakh letter that looks like it",
"kk_letter_swapped_for_another_kk_letter": "one Kazakh letter read as another Kazakh letter (for example Ң read as Қ, Ү as Ұ), either case",
"wrong_script_in_output": "a letter replaced by a letter of the other script (Latin instead of Cyrillic or the reverse) where the reference letter is in the row's own script",
"offscript_letter_in_reference": "the REFERENCE letter is in the other script (for example Latin i inside a Cyrillic word) and the output differs: a labelling artefact, not a reading fault",
"case_only": "right letter, wrong case",
"space_words_merged": "a space of the reference is missing (two words merged)",
"space_word_split": "a space is added (one word split)",
"space_substituted": "a space replaced by another character or the reverse",
"space_next_to_punctuation": "a space missing or added directly next to a punctuation mark (a spacing convention, for example 'word .' read as 'word.')",
"punctuation_or_symbol": "a punctuation mark or symbol missed, added or replaced (Unicode categories P* and S*)",
"digit": "a digit missed, added or replaced",
"other_substitution": "any other letter replaced by another letter",
"other_deletion": "any other letter missing",
"other_insertion": "any other letter added",
"mixed": "the crop's errors fall into two or more of the classes",
}
def log(*a):
print(time.strftime("%H:%M:%S"), *a, flush=True)
def registry():
reg = json.load(open(REG, encoding="utf-8"))
sets = reg["sets"] if isinstance(reg, dict) else reg
out = {}
for s in sets:
if s.get("locked") or str(s.get("split", "")).lower() != "val":
continue
out[s["name"]] = s
return out
def is_punct_or_symbol(c):
cat = unicodedata.category(c)
return cat[0] in ("P", "S")
def is_digit(c):
return unicodedata.category(c) == "Nd"
def letter_script(c):
"""'Latin', 'Cyrillic' or None (not a letter of exactly one of the two scripts)."""
if not unicodedata.category(c).startswith("L"):
return None
s = char_script_set(c)
if not s:
return None
if "Latin" in s and "Cyrillic" not in s:
return "Latin"
if "Cyrillic" in s and "Latin" not in s:
return "Cyrillic"
return None
def space_next_to_punct(s, k):
for x in (k - 1, k + 1):
if 0 <= x < len(s) and is_punct_or_symbol(s[x]):
return True
return False
def op_class(op, i, j, ref, hyp, row_script):
if op == "S":
rc, hc = ref[i], hyp[j]
rl, hl = rc.lower(), hc.lower()
if rl in KK_SPECIAL_LOWER and KK_PAIRS_LOWER[rl] == hl:
return "kk_collapse_to_russian"
if hl in KK_SPECIAL_LOWER and KK_PAIRS_LOWER[hl] == rl:
return "kk_overgeneration"
if rl in KK_SPECIAL_LOWER and hl in KK_SPECIAL_LOWER and rl != hl:
return "kk_letter_swapped_for_another_kk_letter"
rs, hs = letter_script(rc), letter_script(hc)
if rs and hs and rs != hs:
own = "Cyrillic" if row_script == "Cyrl" else "Latin"
return "offscript_letter_in_reference" if rs != own else "wrong_script_in_output"
if fold_lower(rc) == fold_lower(hc):
return "case_only"
if rc == " " or hc == " ":
if (rc == " " and space_next_to_punct(ref, i)) or (hc == " " and space_next_to_punct(hyp, j)):
return "space_next_to_punctuation"
return "space_substituted"
if is_punct_or_symbol(rc) or is_punct_or_symbol(hc):
return "punctuation_or_symbol"
if is_digit(rc) or is_digit(hc):
return "digit"
return "other_substitution"
if op == "D":
rc = ref[i]
if rc == " ":
return "space_next_to_punctuation" if space_next_to_punct(ref, i) else "space_words_merged"
if is_punct_or_symbol(rc):
return "punctuation_or_symbol"
if is_digit(rc):
return "digit"
return "other_deletion"
hc = hyp[j]
if hc == " ":
return "space_next_to_punctuation" if space_next_to_punct(hyp, j) else "space_word_split"
if is_punct_or_symbol(hc):
return "punctuation_or_symbol"
if is_digit(hc):
return "digit"
return "other_insertion"
def classify_crop(ref, hyp, row_script):
"""Returns dict: dist, S, D, I, crop_class, char_counts (partition of dist over CHAR_CLASSES), contains (set of coarse
classes and crop-level flags), pairs (Counter of (ref char, out char))."""
dist, ops = align_ops(ref, hyp)
s = sum(1 for o in ops if o[0] == "S")
d = sum(1 for o in ops if o[0] == "D")
ins = sum(1 for o in ops if o[0] == "I")
res = {"dist": dist, "S": s, "D": d, "I": ins, "ops": ops}
if dist == 0:
res["crop_class"] = None
return res
fine = collections.Counter()
pairs = collections.Counter()
for op, i, j in ops:
if op == "M":
continue
fine[op_class(op, i, j, ref, hyp, row_script)] += 1
pairs[(ref[i] if i >= 0 else "", hyp[j] if j >= 0 else "")] += 1
cer = dist / len(ref)
if hyp == "":
cc = "empty_output"
elif ref.startswith(hyp):
cc = "truncation"
elif hyp.startswith(ref):
cc = "extra_text_after_correct_reading"
elif cer > 0.8 and len(ref) >= 3:
# a 1-2 character reference reaches CER 1 with one wrong letter (for example a case error on a one-letter word); such crops are
# classified by their edit operations instead
cc = "unrelated_cer_above_0_8"
else:
cc = None
contains = set(FINE_TO_COARSE[f] for f in fine)
if cc is not None:
charc = {cc: dist}
contains.add(cc)
crop_class = cc
else:
charc = dict(fine)
coarse = set(FINE_TO_COARSE[f] for f in fine)
crop_class = next(iter(coarse)) if len(coarse) == 1 else "mixed"
res.update({"crop_class": crop_class, "char_counts": charc, "fine_counts": dict(fine), "contains": contains, "pairs": pairs,
"cer": cer})
return res
# ------------------------------------------------------------------------------------------------ bootstrap helpers
class Boot:
"""Cluster bootstrap over a fixed sorted cluster list (the scorer's S01: multinomial cluster counts, ratio of sums)."""
def __init__(self, cluster_ids):
self.clusters = sorted(set(cluster_ids))
self.index = {c: k for k, c in enumerate(self.clusters)}
self.K = len(self.clusters)
W = stats.weights_full(self.K, B, SEED)
if W is None:
W = np.concatenate([w for _, w in stats.weight_chunks(self.K, B, SEED)])
self.W = np.asarray(W, dtype=np.float64)
def sums(self, row_clusters, values):
"""values: (n_rows, c) -> per-cluster sums (K, c)."""
idx = np.array([self.index[c] for c in row_clusters], dtype=np.int64)
M = np.zeros((self.K, values.shape[1]), dtype=np.float64)
np.add.at(M, idx, values)
return M
def ratio_ci(self, num_k, den_k):
"""num_k: (K, c) per-cluster numerators; den_k: (K,) or (K, c) denominators. Returns lists lo, hi (95% percentile)."""
Wn = self.W @ num_k
dd = den_k if den_k.ndim == 2 else den_k[:, None]
Wd = self.W @ dd
with np.errstate(divide="ignore", invalid="ignore"):
R = Wn / Wd
lo, hi = [], []
for c in range(R.shape[1]):
r = R[:, c]
r = r[np.isfinite(r)]
if len(r) < 20:
lo.append(None)
hi.append(None)
else:
a, b = np.percentile(r, [2.5, 97.5])
lo.append(float(a))
hi.append(float(b))
return lo, hi
def diff_ci(self, num_a, den_a, num_b, den_b):
"""CER_a - CER_b per resample (same resamples, so paired by cluster). Inputs per-cluster (K,) arrays."""
W = self.W
with np.errstate(divide="ignore", invalid="ignore"):
ra = (W @ num_a) / (W @ den_a)
rb = (W @ num_b) / (W @ den_b)
d = ra - rb
d = d[np.isfinite(d)]
if len(d) < 20:
return None, None
a, b = np.percentile(d, [2.5, 97.5])
return float(a), float(b)
def rate(num, den, lo=None, hi=None, n_rows=None):
out = {"value": (num / den) if den else None, "num": float(num), "den": float(den)}
if lo is not None:
out["lo"], out["hi"] = lo, hi
if n_rows is not None:
out["n_rows"] = int(n_rows)
if n_rows < MIN_ROWS:
out["fewer_than_30_rows"] = True
return out
# ------------------------------------------------------------------------------------------------ loading
def arm_list():
arms = [(a, "short", a) for a in VLM_ARMS] + [(a, ck, "%s %s" % (a, ck)) for a, ck in LINE_ARMS]
return arms
def load_pairs(reg, set_name, arm, ck):
"""Rows of the set that the arm predicted: list of dicts (id, ref, hyp, lang, script, kind, group, unit). None if no file."""
entry = reg.get(set_name)
if entry is None:
return None, "set not in registry as an unlocked validation set"
p = os.path.join(PREDS, arm, ck, set_name + ".tsv")
if not os.path.exists(p):
return None, "no prediction file"
preds, header, ragged, dup = read_preds(p)
man = read_manifest(entry["manifest"])
rows = []
missing = 0
for r in man:
q = preds.get(r["id"])
if q is None:
missing += 1
continue
rows.append({"id": r["id"], "ref": norm(r["text"]), "hyp": norm(q["hyp"]), "lang": r["lang"], "script": r["script"],
"kind": r["kind"], "group": r["group"], "unit": r["unit"]})
info = {"pred_path": p, "pred_sha256": sha256_file(p), "manifest_path": entry["manifest"], "manifest_rows": len(man),
"rows_scored": len(rows), "manifest_rows_without_prediction": missing, "ragged_pred_rows": ragged, "duplicate_pred_ids": dup}
return rows, info
def score_file_counts(arm, ck, set_name):
p = os.path.join(SCORES, arm, ck, set_name + ".json")
if not os.path.exists(p):
return None
try:
sc = json.load(open(p, encoding="utf-8"))
g = sc["profiles"]["plain"]["groups"]["all"]["metrics"]
return {"path": p, "dist": g["cer"]["num"], "ref_chars": g["cer"]["den"], "S": g["sub_rate"]["num"],
"D": g["del_rate"]["num"], "I": g["ins_rate"]["num"], "cer": g["cer"]["value"],
"homoglyph_sub": (g.get("homoglyph_sub_rate") or {}).get("num"),
"case_err": (g.get("case_error_rate") or {}).get("num"),
"kk_letters": {k: v for k, v in g.items() if k.startswith(("sl|kk|", "slg|kk|"))}}
except (KeyError, ValueError, TypeError) as e:
return {"path": p, "error": repr(e)}
# ------------------------------------------------------------------------------------------------ task 1 (+ data for 3 and 2)
def taxonomy_one(rows, arm_label, set_name, sc_counts, priv):
scored = [r for r in rows if r["ref"] != ""]
boot = Boot([r["group"] for r in scored])
res = [classify_crop(r["ref"], r["hyp"], r["script"]) for r in scored]
n = len(scored)
ref_chars = sum(len(r["ref"]) for r in scored)
tot = {"dist": sum(x["dist"] for x in res), "S": sum(x["S"] for x in res), "D": sum(x["D"] for x in res),
"I": sum(x["I"] for x in res)}
err_idx = [k for k in range(n) if res[k]["dist"] > 0]
groups = [scored[k]["group"] for k in range(n)]
# character partition
ci = {c: k for k, c in enumerate(CHAR_CLASSES)}
Mc = np.zeros((n, len(CHAR_CLASSES)))
for k in err_idx:
for c, v in res[k]["char_counts"].items():
Mc[k, ci[c]] += v
dist_rows = np.array([x["dist"] for x in res], dtype=np.float64)
ref_rows = np.array([len(r["ref"]) for r in scored], dtype=np.float64)
Mk = boot.sums(groups, Mc)
distk = boot.sums(groups, dist_rows[:, None])[:, 0]
refk = boot.sums(groups, ref_rows[:, None])[:, 0]
lo, hi = boot.ratio_ci(Mk, distk)
lo2, hi2 = boot.ratio_ci(Mk, refk)
char_share = {}
for c in CHAR_CLASSES:
k = ci[c]
num = float(Mc[:, k].sum())
char_share[c] = {"error_chars": num, "share_of_error_chars": rate(num, tot["dist"], lo[k], hi[k]),
"per_reference_char": rate(num, ref_chars, lo2[k], hi2[k])}
# coarse char shares (sum of fine)
coarse_share = {}
for cc in CROP_LEVEL + COARSE:
members = [cc] if cc in CROP_LEVEL else [f for f in FINE if FINE_TO_COARSE[f] == cc]
cols = [ci[m] for m in members]
num_k = Mk[:, cols].sum(axis=1, keepdims=True)
l1, h1 = boot.ratio_ci(num_k, distk)
l2, h2 = boot.ratio_ci(num_k, refk)
num = float(Mc[:, cols].sum())
coarse_share[cc] = {"error_chars": num, "share_of_error_chars": rate(num, tot["dist"], l1[0], h1[0]),
"per_reference_char": rate(num, ref_chars, l2[0], h2[0])}
# crop classes (exclusive) and 'contains'
cri = {c: k for k, c in enumerate(CROP_CLASSES)}
Mx = np.zeros((n, len(CROP_CLASSES)))
contain_names = CROP_LEVEL + COARSE
cti = {c: k for k, c in enumerate(contain_names)}
Mt = np.zeros((n, len(contain_names)))
is_err = np.zeros(n)
for k in err_idx:
Mx[k, cri[res[k]["crop_class"]]] = 1
for c in res[k]["contains"]:
Mt[k, cti[c]] = 1
is_err[k] = 1
errk = boot.sums(groups, is_err[:, None])[:, 0]
Mxk, Mtk = boot.sums(groups, Mx), boot.sums(groups, Mt)
lx, hx = boot.ratio_ci(Mxk, errk)
lt, ht = boot.ratio_ci(Mtk, errk)
n_err = len(err_idx)
crop_excl = {c: rate(float(Mx[:, cri[c]].sum()), n_err, lx[cri[c]], hx[cri[c]]) for c in CROP_CLASSES}
crop_contains = {c: rate(float(Mt[:, cti[c]].sum()), n_err, lt[cti[c]], ht[cti[c]]) for c in contain_names}
# confusion pairs
pairs = collections.Counter()
pair_cls = {}
for k in err_idx:
pairs.update(res[k]["pairs"])
top_all = []
for (rc, hc), cnt in pairs.most_common(20):
top_all.append({"reference_char": rc, "output_char": hc, "count": cnt, "share_of_error_chars": cnt / tot["dist"] if tot["dist"] else None,
"op": "substitution" if rc and hc else ("deletion" if rc else "insertion"),
"U+ref": ("U+%04X" % ord(rc)) if rc else "", "U+out": ("U+%04X" % ord(hc)) if hc else ""})
subs = collections.Counter({p: c for p, c in pairs.items() if p[0] and p[1]})
top_sub = [{"reference_char": rc, "output_char": hc, "count": cnt, "U+ref": "U+%04X" % ord(rc), "U+out": "U+%04X" % ord(hc)}
for (rc, hc), cnt in subs.most_common(20)]
# Kazakh special letters: per letter (case-sensitive) and merged case
kk = kk_letter_stats(scored, res, boot, groups)
# Kazakh letters produced on rows whose language is not kk (over-generation on Russian sets)
kk_out_on_ru = 0
ru_ref_chars = 0
for r, x in zip(scored, res):
if r["lang"] != "kk":
ru_ref_chars += len(r["ref"])
hm = ["I"] * len(r["hyp"])
for op, i, j in x["ops"]:
if j >= 0:
hm[j] = op
kk_out_on_ru += sum(1 for j, c in enumerate(r["hyp"]) if c in KK_ALL_SPECIAL and hm[j] != "M")
# reconciliation with the scorer
recon = {"mine": {"error_chars": tot["dist"], "S": tot["S"], "D": tot["D"], "I": tot["I"], "ref_chars": ref_chars},
"score_file": None, "match": None}
if sc_counts and "error" not in sc_counts:
recon["score_file"] = {k: sc_counts[k] for k in ("path", "dist", "ref_chars", "S", "D", "I", "cer")}
recon["match"] = (abs(sc_counts["dist"] - tot["dist"]) < 1e-9 and abs(sc_counts["ref_chars"] - ref_chars) < 1e-9 and
abs(sc_counts["S"] - tot["S"]) < 1e-9 and abs(sc_counts["D"] - tot["D"]) < 1e-9 and
abs(sc_counts["I"] - tot["I"]) < 1e-9)
hs = sc_counts.get("homoglyph_sub")
mine_h = sum(1 for k in err_idx for (op, i, j) in res[k]["ops"]
if op == "S" and PARTNER.get(scored[k]["ref"][i]) == scored[k]["hyp"][j])
recon["homoglyph_sub"] = {"mine_table_pairs": mine_h, "score_file": hs, "match": (hs is not None and abs(hs - mine_h) < 1e-9)}
elif sc_counts:
recon["score_file"] = sc_counts
# repaired references (frozen look-alike table): how the shares move
rep = repaired_view(scored)
# private per-crop rows (cluster only)
for k in range(n):
r, x = scored[k], res[k]
priv.append((set_name, arm_label, r["id"], r["group"], len(r["ref"]), x["dist"], x["crop_class"] or "", r["ref"], r["hyp"]))
def sp_punct(t):
return any(t[k] == " " and (is_punct_or_symbol(t[k + 1]) or (k > 0 and is_punct_or_symbol(t[k - 1])))
for k in range(len(t) - 1))
spacing = {"references_with_a_space_next_to_punctuation": sum(1 for r in scored if sp_punct(r["ref"])),
"outputs_with_a_space_next_to_punctuation": sum(1 for r in scored if sp_punct(r["hyp"]))}
out = {"rows": n, "ref_chars": ref_chars, "clusters": boot.K, "error_crops": n_err, "error_chars": tot["dist"],
"spacing_convention_counts": spacing,
"cer": rate(tot["dist"], ref_chars), "S": tot["S"], "D": tot["D"], "I": tot["I"],
"char_partition_fine": char_share, "char_partition_coarse": coarse_share,
"crop_primary_class": crop_excl, "crop_contains_class": crop_contains,
"top20_pairs_all_ops": top_all, "top20_substitution_pairs": top_sub, "kazakh_special_letters": kk,
"kazakh_letters_written_in_non_kk_rows": {"count": kk_out_on_ru, "non_kk_reference_chars": ru_ref_chars,
"per_1000_reference_chars": (1000.0 * kk_out_on_ru / ru_ref_chars) if ru_ref_chars else None},
"reconciliation_with_scorer": recon, "repaired_reference_view": rep}
return out, res, scored
def kk_letter_stats(scored, res, boot, groups):
n = len(scored)
letters = LETTERS["kk"]
merged = sorted(set(c.lower() for c in letters), key=lambda c: letters.index(c.upper()) if c.upper() in letters else 0)
keys = []
for c in letters:
keys += [("case", c)]
for c in merged:
keys += [("both", c)]
kix = {k: q for q, k in enumerate(keys)}
refc = np.zeros((n, len(keys)))
miss = np.zeros((n, len(keys)))
coll = np.zeros((n, len(keys)))
coll_ci = np.zeros((n, len(keys)))
fa = np.zeros((n, len(keys)))
became = {k: collections.Counter() for k in keys}
for q, (r, x) in enumerate(zip(scored, res)):
if r["lang"] != "kk":
continue
ref, hyp = r["ref"], r["hyp"]
rmap = ["D"] * len(ref)
r2h = [-1] * len(ref)
hmap = ["I"] * len(hyp)
for op, i, j in x["ops"]:
if i >= 0:
rmap[i] = op
r2h[i] = j
if j >= 0:
hmap[j] = op
for i, c in enumerate(ref):
if c in KK_ALL_SPECIAL:
for key in (("case", c), ("both", c.lower())):
t = kix[key]
refc[q, t] += 1
if rmap[i] != "M":
miss[q, t] += 1
became[key][hyp[r2h[i]] if rmap[i] == "S" else ""] += 1
p = COLLAPSE["kk"].get(c)
if rmap[i] == "S" and p is not None and hyp[r2h[i]] == p:
coll[q, t] += 1
if rmap[i] == "S" and hyp[r2h[i]].lower() == KK_PAIRS_LOWER[c.lower()]:
coll_ci[q, t] += 1
for j, c in enumerate(hyp):
if c in KK_ALL_SPECIAL and hmap[j] != "M":
for key in (("case", c), ("both", c.lower())):
fa[q, kix[key]] += 1
R = boot.sums(groups, refc)
lo_m, hi_m = boot.ratio_ci(boot.sums(groups, miss), R)
lo_c, hi_c = boot.ratio_ci(boot.sums(groups, coll_ci), R)
lo_f, hi_f = boot.ratio_ci(boot.sums(groups, fa), R)
out = {}
for key, t in kix.items():
nref = float(refc[:, t].sum())
name = key[1] if key[0] == "case" else key[1] + " (both cases)"
if nref == 0 and fa[:, t].sum() == 0:
continue
e = {"reference_occurrences": nref, "missed": float(miss[:, t].sum()), "read_as_russian_partner_exact_case": float(coll[:, t].sum()),
"read_as_russian_partner_any_case": float(coll_ci[:, t].sum()), "false_alarms": float(fa[:, t].sum()),
"most_common_misreadings": [{"output_char": h, "count": cnt} for h, cnt in became[key].most_common(5)]}
if nref >= MIN_ROWS:
e["miss_rate"] = {"value": e["missed"] / nref, "lo": lo_m[t], "hi": hi_m[t]}
e["collapse_rate_any_case"] = {"value": e["read_as_russian_partner_any_case"] / nref, "lo": lo_c[t], "hi": hi_c[t]}
e["false_alarm_rate"] = {"value": e["false_alarms"] / nref, "lo": lo_f[t], "hi": hi_f[t]}
else:
e["note"] = "fewer than 30 reference occurrences: counts only"
out[name] = e
return out
def repaired_view(scored):
changed = 0
tot = collections.Counter()
for r in scored:
new, ch = repair_label(r["ref"], r["script"])
if ch:
changed += 1
x = classify_crop(new, r["hyp"], r["script"])
if x["dist"] > 0:
for c, v in x["char_counts"].items():
tot[c] += v
tot["_dist"] += x["dist"]
tot["_ref"] += len(new)
d = tot.pop("_dist")
rf = tot.pop("_ref")
return {"references_changed_by_lookalike_repair": changed, "error_chars": d, "cer": d / rf if rf else None,
"char_partition_fine_share": {c: (tot[c] / d if d else None) for c in CHAR_CLASSES},
"note": "references repaired with the frozen look-alike table (r5eval.lookalike.repair_label); outputs unchanged; no interval"}
# ------------------------------------------------------------------------------------------------ task 3
def overlap(err_sets, all_ids, arms):
out = {"arms": arms, "n_crops": len(all_ids), "pairs": []}
for a_i in range(len(arms)):
for b_i in range(a_i + 1, len(arms)):
a, b = arms[a_i], arms[b_i]
A, Bs = err_sets[a], err_sets[b]
u = len(A | Bs)
out["pairs"].append({"a": a, "b": b, "errors_a": len(A), "errors_b": len(Bs), "both": len(A & Bs), "union": u,
"jaccard": (len(A & Bs) / u) if u else None})
cnt = collections.Counter()
for i in all_ids:
cnt[sum(1 for a in arms if i in err_sets[a])] += 1
out["crops_by_number_of_arms_wrong"] = {str(k): cnt[k] for k in sorted(cnt)}
allw = set(all_ids)
for a in arms:
allw &= err_sets[a]
out["wrong_for_every_arm"] = {"count": len(allw), "share_of_crops": len(allw) / len(all_ids) if all_ids else None}
nonew = set(all_ids)
for a in arms:
nonew -= err_sets[a]
out["right_for_every_arm"] = {"count": len(nonew), "share_of_crops": len(nonew) / len(all_ids) if all_ids else None}
return out, allw
# ------------------------------------------------------------------------------------------------ task 4
def attr_rows(rows, side):
"""Attach side-file attributes and the length bucket."""
for r in rows:
m = side.get(r["id"]) if side else None
r["len_bucket"] = length_bucket(len(r["ref"])) if r["ref"] else None
r["m"] = m or {}
return rows
def cell_table(rows, dist, refl, boot, cells, min_rows=MIN_ROWS, with_contrast=False):
"""cells: list of (name, mask). CER with CI per cell; with_contrast: CER with vs without and the paired difference."""
groups = [r["group"] for r in rows]
distk_rows = np.asarray(dist, dtype=np.float64)
refl_rows = np.asarray(refl, dtype=np.float64)
out = {}
if not cells:
return out
masks = np.array([m for _, m in cells], dtype=np.float64).T # (n, c)
num = boot.sums(groups, masks * distk_rows[:, None])
den = boot.sums(groups, masks * refl_rows[:, None])
lo, hi = boot.ratio_ci(num, den)
tot_num = boot.sums(groups, distk_rows[:, None])[:, 0]
tot_den = boot.sums(groups, refl_rows[:, None])[:, 0]
for c, (name, m) in enumerate(cells):
nr = int(np.asarray(m).sum())
e = rate(float(num[:, c].sum()), float(den[:, c].sum()), lo[c], hi[c], n_rows=nr)
if with_contrast:
if nr == len(rows):
e["contrast"] = "no contrast possible: present in every row"
elif nr == 0:
e["contrast"] = "absent from every row"
else:
wn, wd = tot_num - num[:, c], tot_den - den[:, c]
e["cer_without"] = rate(float(wn.sum()), float(wd.sum()), n_rows=len(rows) - nr)
dl, dh = boot.diff_ci(num[:, c], den[:, c], wn, wd)
if e["value"] is not None and e["cer_without"]["value"] is not None:
e["difference_with_minus_without"] = {"value": e["value"] - e["cer_without"]["value"], "lo": dl, "hi": dh,
"note": "descriptive: effects co-occur on a page, so this is not the effect's own cause"}
out[name] = e
return out
def attributes_one(rows, set_name):
text_rows = [r for r in rows if r["ref"] != ""]
out = {}
if set_name == "synth_clutter_val":
boot = Boot([r["group"] for r in rows])
groups = [r["group"] for r in rows]
nonempty = np.array([1.0 if r["hyp"] != "" else 0.0 for r in rows])
olen = np.array([float(len(r["hyp"])) for r in rows])
ones = np.ones(len(rows))
res = {}
cols = [("all", ones)]
for col in ("crop_mode", "page_type", "paper_kind", "geo_mode", "strength"):
vals = sorted(set(r["m"].get(col, "") for r in rows))
for v in vals:
cols.append(("%s=%s" % (col, v), np.array([1.0 if r["m"].get(col, "") == v else 0.0 for r in rows])))
toks = collections.Counter()
for r in rows:
for t in (r["m"].get("effects_all") or "").split("|"):
if t:
toks[t] += 1
for t in sorted(toks):
cols.append(("effect=%s" % t, np.array([1.0 if t in (r["m"].get("effects_all") or "").split("|") else 0.0 for r in rows])))
M = np.array([m for _, m in cols]).T
num = boot.sums(groups, M * nonempty[:, None])
den = boot.sums(groups, M)
lo, hi = boot.ratio_ci(num, den)
for c, (name, m) in enumerate(cols):
nr = int(m.sum())
e = rate(float(num[:, c].sum()), float(den[:, c].sum()), lo[c], hi[c], n_rows=nr)
e["mean_output_chars_when_nonempty"] = (float((olen * m * nonempty).sum()) / float((m * nonempty).sum())) if (m * nonempty).sum() else None
if nr == len(rows) and name != "all":
e["contrast"] = "no contrast possible: present in every row"
res[name] = e
out["HR1_text_on_empty_images"] = res
return out
if not text_rows:
return out
dist = [lev_fast(r["ref"], r["hyp"]) for r in text_rows]
refl = [len(r["ref"]) for r in text_rows]
bt = Boot([r["group"] for r in text_rows])
n = len(text_rows)
def mask(f):
return [1.0 if f(r) else 0.0 for r in text_rows]
out["all"] = cell_table(text_rows, dist, refl, bt, [("all", [1.0] * n)])["all"]
langs = sorted(set(r["lang"] for r in text_rows))
out["by_language_script"] = cell_table(text_rows, dist, refl, bt, [(l, mask(lambda r, l=l: r["lang"] == l)) for l in langs])
vals = [v for v in out["by_language_script"].values() if v["value"] is not None]
out["macro_over_language_scripts"] = (sum(v["value"] for v in vals) / len(vals)) if vals else None
out["by_length_bucket"] = cell_table(text_rows, dist, refl, bt, [(name, mask(lambda r, name=name: r["len_bucket"] == name)) for _, _, name in LEN_EDGES])
if set_name in ("synth_hand_val", "synth_typed_val"):
fg = sorted(set(r["m"].get("font_group", "") for r in text_rows))
cells = [("font_group=%s" % v, mask(lambda r, v=v: r["m"].get("font_group", "") == v)) for v in fg]
for sc in ("Cyrl", "Latn"):
for v in fg:
cells.append(("font_group=%s|%s" % (v, sc), mask(lambda r, v=v, sc=sc: r["m"].get("font_group", "") == v and r["script"] == sc)))
out["by_font_group"] = cell_table(text_rows, dist, refl, bt, cells)
if len(fg) == 2 and "seen" in fg and "unseen" in fg:
groups = [r["group"] for r in text_rows]
d_ = np.asarray(dist, dtype=np.float64)
l_ = np.asarray(refl, dtype=np.float64)
mu = np.asarray(mask(lambda r: r["m"].get("font_group") == "unseen"))
ms = 1.0 - mu
nu, du = bt.sums(groups, (mu * d_)[:, None])[:, 0], bt.sums(groups, (mu * l_)[:, None])[:, 0]
ns, ds = bt.sums(groups, (ms * d_)[:, None])[:, 0], bt.sums(groups, (ms * l_)[:, None])[:, 0]
lo, hi = bt.diff_ci(nu, du, ns, ds)
out["unseen_minus_seen_font"] = {"value": nu.sum() / du.sum() - ns.sum() / ds.sum(), "lo": lo, "hi": hi}
fonts = collections.Counter(r["m"].get("font_id", "") for r in text_rows)
out["by_font_id"] = cell_table(text_rows, dist, refl, bt, [("%s (%s)" % (f, next((r["m"].get("font_group", "") for r in text_rows if r["m"].get("font_id", "") == f), "")),
mask(lambda r, f=f: r["m"].get("font_id", "") == f)) for f in sorted(fonts)])
for col in ("paper_kind", "geo_mode", "page_type", "strength", "ink", "region_class", "crop_mode", "overlaps", "mixed"):
vals = sorted(set(r["m"].get(col, "") for r in text_rows))
out["by_" + col] = cell_table(text_rows, dist, refl, bt, [("%s=%s" % (col, v if v else "(none)"), mask(lambda r, v=v, col=col: r["m"].get(col, "") == v)) for v in vals])
toks = collections.Counter()
for r in text_rows:
for t in (r["m"].get("effects_all") or "").split("|"):
if t:
toks[t] += 1
cells = [(t, mask(lambda r, t=t: t in (r["m"].get("effects_all") or "").split("|"))) for t in sorted(toks)]
out["by_effect_with_vs_without"] = cell_table(text_rows, dist, refl, bt, cells, with_contrast=True)
same = collections.defaultdict(list)
for t, m in cells:
same[tuple(k for k, x in enumerate(m) if x)].append(t)
out["effect_tokens_always_together"] = [{"tokens": v, "n_rows": len(k), "note": "these tokens occur on exactly the same rows: their "
"contrasts are identical and cannot be told apart"} for k, v in same.items() if len(v) > 1]
n_all = len(text_rows)
keyset = {k: v for k, v in same.items()}
comp = []
for k, v in keyset.items():
ks = set(k)
ck = tuple(i for i in range(n_all) if i not in ks)
if ck in keyset and k < ck:
comp.append({"tokens_present": v, "rows_present": len(k), "complement_tokens": keyset[ck], "rows_complement": len(ck),
"note": "the second group is present exactly where the first is absent: its 'with vs without' contrast is the first "
"group's contrast reversed"})
out["effect_tokens_exact_complements"] = comp
out["effect_contrasts_within_strata"] = stratified_contrasts(text_rows, dist, refl, bt)
out["by_effect_with_vs_without:note"] = ("tokens of the side-file column effects_all (every effect the generator applied, a superset of the "
"column 'effects'); CER of rows with the token, of rows without it, and the difference with a "
"paired page-bootstrap interval")
return out
STRAT_TOKENS = ["overlaps=stamp", "stamp", "stains", "creases", "staple", "binder_holes", "pattern:dots", "pattern:faint_table", "pattern:guilloche",
"pattern:stripes", "pattern:tint", "pattern:watermark", "mark:arrow", "mark:brace", "mark:circle", "mark:cross", "mark:highlight",
"mark:scribble", "mark:strike", "mark:tick", "mark:underline", "paper:ruled", "object:map", "blur:>=1.0", "noise:>=5", "fx:ink_dropout"]
def _has_token(r, t):
if t.startswith("overlaps="):
return r["m"].get("overlaps", "") == t.split("=", 1)[1]
return t in (r["m"].get("effects_all") or "").split("|")
def stratified_contrasts(rows, dist, refl, bt):
"""CER with minus without a token, computed inside strata of capture mode x degradation strength (geo_mode x strength, the two
page-level settings that bundle most other effects) and averaged with weights = rows with the token in each stratum. The interval
comes from the same page bootstrap (resampled per-stratum ratios, fixed weights). Descriptive: other co-occurring effects remain."""
groups = [r["group"] for r in rows]
d = np.asarray(dist, dtype=np.float64)
l = np.asarray(refl, dtype=np.float64)
skey = [(r["m"].get("geo_mode", ""), r["m"].get("strength", "")) for r in rows]
svals = sorted(set(skey))
out = {"strata": "geo_mode x strength (%d cells)" % len(svals), "weighting": "rows with the token per stratum",
"note": "descriptive: removes the capture-mode and strength bundles only; tokens that define a stratum cannot be contrasted", "tokens": {}}
for t in STRAT_TOKENS:
has = np.array([1.0 if _has_token(r, t) else 0.0 for r in rows])
if has.sum() == 0:
continue
cols, wts = [], []
for v in svals:
s = np.array([1.0 if k == v else 0.0 for k in skey])
nw, nwo = float((s * has).sum()), float((s * (1 - has)).sum())
if nw == 0 or nwo == 0:
continue
cols += [s * has * d, s * has * l, s * (1 - has) * d, s * (1 - has) * l]
wts.append(nw)
raw_w = (has * d).sum() / (has * l).sum() if (has * l).sum() else None
raw_wo = ((1 - has) * d).sum() / ((1 - has) * l).sum() if ((1 - has) * l).sum() else None
e = {"n_rows_with": int(has.sum()), "raw_difference": (raw_w - raw_wo) if (raw_w is not None and raw_wo is not None) else None}
if not wts:
e["stratified_difference"] = "not evaluable: no stratum has rows both with and without the token"
out["tokens"][t] = e
continue
M = np.array(cols).T
Mk = bt.sums(groups, M)
w = np.array(wts) / sum(wts)
S = len(wts)
pt = 0.0
for i in range(S):
pt += w[i] * (Mk[:, 4 * i].sum() / Mk[:, 4 * i + 1].sum() - Mk[:, 4 * i + 2].sum() / Mk[:, 4 * i + 3].sum())
R = bt.W @ Mk
with np.errstate(divide="ignore", invalid="ignore"):
reps = sum(w[i] * (R[:, 4 * i] / R[:, 4 * i + 1] - R[:, 4 * i + 2] / R[:, 4 * i + 3]) for i in range(S))
reps = reps[np.isfinite(reps)]
e["stratified_difference"] = {"value": float(pt), "lo": float(np.percentile(reps, 2.5)) if len(reps) >= 20 else None,
"hi": float(np.percentile(reps, 97.5)) if len(reps) >= 20 else None, "strata_used": S,
"valid_replicates": int(len(reps))}
if has.sum() < MIN_ROWS:
e["fewer_than_30_rows"] = True
out["tokens"][t] = e
return out
# ------------------------------------------------------------------------------------------------ task 6
def curves(reg):
entry = reg.get("curve_v1")
man = read_manifest(entry["manifest"])
mrows = {r["id"]: r for r in man}
out = {}
for arm in CURVE_ARMS:
ad = os.path.join(PREDS, arm)
if not os.path.isdir(ad):
continue
pts = []
for ck in sorted(os.listdir(ad)):
if not ck.startswith("curve_"):
continue
p = os.path.join(ad, ck, "curve_v1.tsv")
if not os.path.exists(p):
continue
meta = {}
mp = os.path.join(ad, ck, "meta.json")
if os.path.exists(mp):
try:
meta = json.load(open(mp, encoding="utf-8"))
except ValueError:
meta = {}
preds, _, _, _ = read_preds(p)
per = {}
for r in man:
q = preds.get(r["id"])
if q is None:
continue
ref, hyp = norm(r["text"]), norm(q["hyp"])
per[r["id"]] = (ref, hyp)
ss = meta.get("samples_seen")
try:
ss = int(ss)
except (TypeError, ValueError):
ss = None
if ss is None:
digits = "".join(ch for ch in ck.split("_")[1] if ch.isdigit())
ss = int(digits) if digits else None
pts.append({"checkpoint": ck, "samples_seen": ss, "per": per, "pred_path": p, "pred_sha256": sha256_file(p),
"killed_or_crashed": ("killed" in ck or "crash" in ck)})
if not pts:
continue
kr_ids = [i for i, r in mrows.items() if r["kind"] == "hand_real"]
bt = Boot([mrows[i]["group"] for i in kr_ids])
res_pts = []
cl = {}
for pt in sorted(pts, key=lambda x: (x["samples_seen"] or 0, x["checkpoint"])):
per = pt["per"]
ids = [i for i in kr_ids if i in per]
d = np.array([lev_fast(per[i][0], per[i][1]) for i in ids], dtype=np.float64)
l = np.array([len(per[i][0]) for i in ids], dtype=np.float64)
g = [mrows[i]["group"] for i in ids]
nk, dk = bt.sums(g, d[:, None])[:, 0], bt.sums(g, l[:, None])[:, 0]
lo, hi = bt.ratio_ci(nk[:, None], dk)
kinds = {}
for kind in ("hand_synth", "typed_synth", "typed_real"):
kid = [i for i, r in mrows.items() if r["kind"] == kind and i in per and per[i][0]]
dd = sum(lev_fast(per[i][0], per[i][1]) for i in kid)
ll = sum(len(per[i][0]) for i in kid)
kinds[kind] = {"cer": dd / ll if ll else None, "rows": len(kid)}
clut = [i for i, r in mrows.items() if r["kind"] == "clutter" and i in per]
kinds["clutter_HR1"] = {"value": (sum(1 for i in clut if per[i][1] != "") / len(clut)) if clut else None, "rows": len(clut)}
res_pts.append({"checkpoint": pt["checkpoint"], "samples_seen": pt["samples_seen"],
"fraction_of_P_short": (pt["samples_seen"] / P_SHORT) if pt["samples_seen"] else None,
"killed_or_crashed_run": pt["killed_or_crashed"], "kohtd_part_rows": len(ids),
"cer_kohtd_part": {"value": float(nk.sum() / dk.sum()) if dk.sum() else None, "lo": lo[0], "hi": hi[0],
"num": float(nk.sum()), "den": float(dk.sum())},
"other_parts": kinds, "pred_path": pt["pred_path"], "pred_sha256": pt["pred_sha256"]})
cl[pt["checkpoint"]] = (nk, dk)
# flag per r5_descriptive_labels.txt: 75% vs 100% points of P_short
valid = [p for p in res_pts if not p["killed_or_crashed_run"] and p["samples_seen"]]
p75 = [p for p in valid if abs(p["samples_seen"] - 0.75 * P_SHORT) <= 0.1 * P_SHORT]
p100 = [p for p in valid if abs(p["samples_seen"] - P_SHORT) <= 0.1 * P_SHORT]
flag, fig = None, None
if p75 and p100:
a, b = p75[0], p100[0]
va, vb = a["cer_kohtd_part"]["value"], b["cer_kohtd_part"]["value"]
fell = (va - vb) / va if va else None
flag = "still improving" if (fell is not None and fell > 0.10) else "plateaued"
na, da = cl[a["checkpoint"]]
nb, db = cl[b["checkpoint"]]
W = bt.W
with np.errstate(divide="ignore", invalid="ignore"):
ra, rb = (W @ na) / (W @ da), (W @ nb) / (W @ db)
rel = (ra - rb) / ra
rel = rel[np.isfinite(rel)]
fig = {"cer_75": va, "cer_100": vb, "relative_drop": fell, "relative_drop_ci95_paired_form_bootstrap":
[float(np.percentile(rel, 2.5)), float(np.percentile(rel, 97.5))] if len(rel) >= 20 else None,
"share_of_resamples_with_drop_above_10pct": float(np.mean(rel > 0.10)) if len(rel) else None,
"checkpoints": [a["checkpoint"], b["checkpoint"]]}
flag_note = None
if flag is None:
last = max((p["samples_seen"] for p in valid), default=None)
flag_note = ("not evaluable: the rule needs points within 10%% of 75%% and of 100%% of P_short; the last usable checkpoint is at %s samples "
"(%s of P_short)%s" % (last, ("%.0f%%" % (100.0 * last / P_SHORT)) if last else "n/a",
"; checkpoints of killed or crashed runs are not used" if any(p["killed_or_crashed_run"] for p in res_pts) else ""))
status = "complete" if (p75 and p100 and len(valid) >= 4) else "incomplete"
if any(p["killed_or_crashed_run"] for p in res_pts):
status += " (some checkpoints come from a killed or crashed run and are not used for the flag)"
out[arm] = {"points": res_pts, "flag_rule_r5_descriptive_labels": flag, "flag_figures": fig, "curve_status": status}
if flag_note:
out[arm]["flag_note"] = flag_note
return out
# ------------------------------------------------------------------------------------------------ main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--tasks", default="1,3,4,6")
ap.add_argument("--limit-arms", default="")
ap.add_argument("--extra-vlm-arms", default="", help="VLM arms that finished after the task-2 sample was drawn (checkpoint 'short')")
args = ap.parse_args()
tasks = set(args.tasks.split(","))
os.makedirs(os.path.join(args.out, "private"), exist_ok=True)
reg = registry()
arms = arm_list()
extra_labels = [a for a in args.extra_vlm_arms.split(",") if a]
arms = arms[:len(VLM_ARMS)] + [(a, "short", a) for a in extra_labels] + arms[len(VLM_ARMS):]
if args.limit_arms:
keep = set(args.limit_arms.split(","))
arms = [a for a in arms if a[2] in keep]
meta = {"generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "script": os.path.abspath(__file__),
"script_sha256": sha256_file(os.path.abspath(__file__)), "bootstrap": {"B": B, "seed": SEED, "level": "95% percentile",
"clusters": "manifest column 'group' (KOHTD forms, HKR form instances, school pages, CHD groups, synthetic source pages, real-print documents)"},
"normalisation": "N0 (r5eval.textnorm.norm) on manifest text and TSV hyp; alignment r5eval.align.align_ops", "validation_only": True}
if "1" in tasks or "3" in tasks:
tax = {"meta": dict(meta), "class_definitions": PLAIN_NAMES,
"partition_rule": ("Character shares are a partition of all error characters (edit operations) of the set: a crop whose output is empty, "
"a proper prefix of the reference, has the reference as a proper prefix, or has CER above 0.8 with a reference of 3+ characters puts all its error characters "
"into that crop-level class (checked in this order); every other crop's operations are classified one by one in the order "
"Kazakh letter vs Russian partner (either direction), Kazakh letter vs another Kazakh letter, other script, case, space "
"(next to punctuation, else merged/split/substituted), punctuation or symbol, digit, other. Crop shares: 'primary' gives each erroneous "
"crop one class (crop-level class, else its single coarse class, else 'mixed'); 'contains' counts crops with at least one "
"operation of the class (overlapping)."),
"sets": {}, "arms": [a[2] for a in arms]}
priv = []
err_sets = collections.defaultdict(dict)
crop_info = collections.defaultdict(dict)
ids_by_set = {}
for s in TAX_SETS:
tax["sets"][s] = {}
for arm, ck, label in arms:
rows, info = load_pairs(reg, s, arm, ck)
if rows is None:
tax["sets"][s][label] = {"status": info}
continue
sc = score_file_counts(arm, ck, s)
log("taxonomy", s, label, len(rows))
o, res, scored = taxonomy_one(rows, label, s, sc, priv)
o["inputs"] = info
tax["sets"][s][label] = o
err_sets[s][label] = set(r["id"] for r, x in zip(scored, res) if x["dist"] > 0)
crop_info[s][label] = {r["id"]: (x["dist"], x["crop_class"]) for r, x in zip(scored, res) if x["dist"] > 0}
ids_by_set.setdefault(s, set(r["id"] for r in scored))
write_json_atomic(os.path.join(args.out, "error_taxonomy.json"), tax)
with open(os.path.join(args.out, "private", "per_crop_errors.tsv"), "w", encoding="utf-8") as f:
f.write("set\tarm\tid\tgroup\tref_len\tdist\tcrop_class\tref\thyp\n")
for t in priv:
f.write("\t".join(str(x).replace("\t", " ") for x in t) + "\n")
ov = {"meta": dict(meta), "sets": {}}
for s in TAX_SETS:
labels = [a[2] for a in arms if a[2] in err_sets[s]]
if not labels:
continue
full, allw = overlap(err_sets[s], sorted(ids_by_set[s]), labels)
base = [l for l in labels if l not in extra_labels]
if extra_labels:
# the 15-arm list fixed when the task-2 sample was drawn stays the definition of "every arm" for task 2
base_ov, allw = overlap(err_sets[s], sorted(ids_by_set[s]), base)
full["task1_base_15_arms"] = {k: v for k, v in base_ov.items() if k != "pairs"}
full["late_arms_added"] = extra_labels
vlm = [l for l in labels if " " not in l]
vlm_ov, vlm_allw = overlap(err_sets[s], sorted(ids_by_set[s]), vlm)
four = [l for l in ("hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "A1 long_lm_gated") if l in labels]
four_ov, four_allw = overlap(err_sets[s], sorted(ids_by_set[s]), four)
ov["sets"][s] = {"all_arms": full, "vlm_arms_only": {k: v for k, v in vlm_ov.items() if k != "pairs"},
"four_sampled_arms": {k: v for k, v in four_ov.items() if k != "pairs"}}
mass = {}
for l in labels:
ci = crop_info[s][l]
tot = sum(dd for dd, _ in ci.values())
unr = sum(dd for dd, c in ci.values() if c == "unrelated_cer_above_0_8")
tot_in = sum(dd for i, (dd, _) in ci.items() if i in allw)
unr_in = sum(dd for i, (dd, c) in ci.items() if i in allw and c == "unrelated_cer_above_0_8")
mass[l] = {"error_chars": tot, "error_chars_in_every_arm_wrong_crops": tot_in,
"share_of_error_chars_in_every_arm_wrong_crops": (tot_in / tot) if tot else None,
"unrelated_error_chars": unr, "unrelated_error_chars_in_every_arm_wrong_crops": unr_in,
"share_of_unrelated_in_every_arm_wrong_crops": (unr_in / unr) if unr else None}
ov["sets"][s]["error_mass_in_every_arm_wrong_crops"] = {"every_arm_definition": "the 15 arms of the task-1 list fixed when the task-2 sample was drawn",
"n_crops": len(allw), "arms": mass}
with open(os.path.join(args.out, "private", "wrong_for_every_arm_%s.txt" % s), "w", encoding="utf-8") as f:
for i in sorted(allw):
f.write(i + "\n")
with open(os.path.join(args.out, "private", "error_sets_%s.json" % s), "w", encoding="utf-8") as f:
json.dump({k: sorted(v) for k, v in err_sets[s].items()}, f)
write_json_atomic(os.path.join(args.out, "overlap.json"), ov)
if "4" in tasks:
att = {"meta": dict(meta), "sets": {}, "note_common_rows": ("The line arms with LM-gated decoding were scored on 4,000-row subsets of "
"synth_hand_val, synth_typed_val and print_real_val. 'all_rows' uses every row an arm has; 'common_rows' uses only the ids every "
"listed arm has, which is the figure to compare across arms.")}
side_dir = D + "/data/processed/r5/frozen_eval_v1"
for s in ATTR_SETS:
side_p = os.path.join(side_dir, s + ".meta.tsv")
side = read_meta_tsv(side_p) if os.path.exists(side_p) else {}
loaded = {}
for arm, ck, label in arms:
rows, info = load_pairs(reg, s, arm, ck)
if rows is None:
continue
loaded[label] = (rows, info)
if not loaded:
continue
common = None
for label, (rows, info) in loaded.items():
ids = set(r["id"] for r in rows)
common = ids if common is None else (common & ids)
att["sets"][s] = {"side_file": side_p if side else None, "side_file_sha256": sha256_file(side_p) if side else None,
"common_row_count": len(common), "arms": {}}
for label, (rows, info) in loaded.items():
log("attributes", s, label, len(rows))
attr_rows(rows, side)
e = {"inputs": info}
e["all_rows"] = attributes_one(rows, s)
if len(common) < len(rows):
crow = [r for r in rows if r["id"] in common]
e["common_rows"] = attributes_one(crow, s)
else:
e["common_rows"] = "identical to all_rows"
att["sets"][s]["arms"][label] = e
write_json_atomic(os.path.join(args.out, "attributes.json"), att)
if "6" in tasks:
cv = {"meta": dict(meta), "rule": "records/R5/RULE/r5_descriptive_labels.txt (sha256 0eaf7801...): 'still improving' when V1-curve CER fell by "
"more than 10% (relative) between the 75% and the 100% points of P_short, 'plateaued' otherwise. V1-curve CER is read, as in the "
"report cards, as the CER on the KOHTD part of curve_v1 (500 V1lm crops, hand_real rows).", "arms": curves(reg)}
write_json_atomic(os.path.join(args.out, "curves.json"), cv)
log("done")
if __name__ == "__main__":
sys.exit(main())
"""ERRAN (R5): descriptive error analysis of every arm on VALIDATION data only.
Tasks (ERRAN plan):
1 error taxonomy on V1 (KOHTD validation screen set) and on hkr/chd/school _val_s2000, with form-bootstrap intervals,
top-20 confusion pairs and per-letter error rates of the Kazakh special letters;
3 overlap of error-crop sets between arms (Jaccard) and the crops every arm gets wrong;
4 attribute breakdown on synth_hand_val, synth_typed_val, print_real_val and synth_clutter_val from the generator side files;
6 learning curves on curve_v1 (25/50/75/100% of P_short).
Scoring conventions are those of the frozen R5 scorer (CODE/src/r5eval): reference = manifest text joined on id after N0,
output = N0 of the TSV hyp, alignment = r5eval.align.align_ops (J2 tie-break), bootstrap = r5eval.stats weights (seed 20261121,
B = 10,000, clusters = the manifest 'group' column: forms for KOHTD, form instances for HKR, pages, source documents).
Locked (test) sets are never opened: every manifest path is taken from a registry entry whose split is 'val' and locked is false.
Private outputs (reference and output strings of real persons' handwriting) are written only under OUT/private/ on the cluster.
The public JSON files contain counts, rates and single characters only.
"""
import argparse
import collections
import json
import os
import sys
import time
import unicodedata
import numpy as np
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
from r5eval import stats # noqa: E402
from r5eval.align import align_ops, lev_fast # noqa: E402
from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket # noqa: E402
from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic # noqa: E402
from r5eval.lookalike import PARTNER, repair_label # noqa: E402
from r5eval.textnorm import fold_lower, char_script_set, norm # noqa: E402
D = "/path/to/TURKIC_OCR_DATA"
PREDS = D + "/outputs/r5/preds"
SCORES = D + "/outputs/r5/scores"
REG = D + "/data/processed/r5/evalsets.json"
B = stats.B_DEFAULT
SEED = stats.SEED_BASE
P_SHORT = 150000
VLM_ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "qwen3_vl_2b", "lightonocr_3_0_8b", "glm_ocr", "teleocr",
"ovisocr2", "ovisocr3", "lightonocr_3_1b", "granite_docling_258m"]
LINE_ARMS = [("A1", "long"), ("A1", "long_lm_gated"), ("A2", "long_lm_gated"), ("A3", "long")]
TAX_SETS = ["V1", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000"]
ATTR_SETS = ["synth_hand_val", "synth_typed_val", "print_real_val", "synth_clutter_val"]
CURVE_ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "qwen3_vl_2b", "lightonocr_3_0_8b", "glm_ocr", "teleocr",
"ovisocr2", "ovisocr3", "lightonocr_3_1b", "granite_docling_258m", "firered_ocr", "oxr_1_0", "surya_ocr_2_5",
"mineru2_5_pro", "A1", "A2", "A3", "A1s", "A4"]
MIN_ROWS = 30
# Kazakh special letter -> Russian look-alike (frozen scorer table, lower case; analyse._PARTNER_LOWER['kk'] via COLLAPSE)
KK_PAIRS_LOWER = {k: v for k, v in COLLAPSE["kk"].items() if k == k.lower()}
KK_SPECIAL_LOWER = set(KK_PAIRS_LOWER)
KK_PLAIN_TO_SPECIAL = collections.defaultdict(set)
for _s, _p in KK_PAIRS_LOWER.items():
KK_PLAIN_TO_SPECIAL[_p].add(_s)
KK_ALL_SPECIAL = set(LETTERS["kk"])
FINE_TO_COARSE = {
"kk_collapse_to_russian": "kazakh_letter_vs_russian_lookalike",
"kk_overgeneration": "kazakh_letter_vs_russian_lookalike",
"kk_letter_swapped_for_another_kk_letter": "kazakh_letter_vs_another_kazakh_letter",
"wrong_script_in_output": "wrong_script_lookalike",
"offscript_letter_in_reference": "reference_has_offscript_letter",
"case_only": "case_only",
"space_words_merged": "space_words_merged_or_split",
"space_word_split": "space_words_merged_or_split",
"space_substituted": "space_words_merged_or_split",
"space_next_to_punctuation": "space_next_to_punctuation",
"punctuation_or_symbol": "punctuation_or_symbol",
"digit": "digit",
"other_substitution": "other_substitution",
"other_deletion": "other_deletion",
"other_insertion": "other_insertion",
}
CROP_LEVEL = ["empty_output", "truncation", "extra_text_after_correct_reading", "unrelated_cer_above_0_8"]
FINE = list(FINE_TO_COARSE)
COARSE = []
for _c in FINE_TO_COARSE.values():
if _c not in COARSE:
COARSE.append(_c)
CHAR_CLASSES = CROP_LEVEL + FINE
CROP_CLASSES = CROP_LEVEL + COARSE + ["mixed"]
PLAIN_NAMES = {
"empty_output": "the model gave no text at all",
"truncation": "the output is a proper prefix of the reference (reading stopped early)",
"extra_text_after_correct_reading": "the reference is a proper prefix of the output (correct reading, then extra text)",
"unrelated_cer_above_0_8": "output unrelated to the reference: crop CER above 0.8 and a reference of at least 3 characters (and not one of the three cases above); shorter references are classified by their edit operations",
"kk_collapse_to_russian": "a Kazakh letter (Ә Ғ Қ Ң Ө Ұ Ү Һ І) read as its Russian look-alike (А Г К Н О У У Х И), either case",
"kk_overgeneration": "a Russian letter (А Г К Н О У Х И) read as a Kazakh letter that looks like it",
"kk_letter_swapped_for_another_kk_letter": "one Kazakh letter read as another Kazakh letter (for example Ң read as Қ, Ү as Ұ), either case",
"wrong_script_in_output": "a letter replaced by a letter of the other script (Latin instead of Cyrillic or the reverse) where the reference letter is in the row's own script",
"offscript_letter_in_reference": "the REFERENCE letter is in the other script (for example Latin i inside a Cyrillic word) and the output differs: a labelling artefact, not a reading fault",
"case_only": "right letter, wrong case",
"space_words_merged": "a space of the reference is missing (two words merged)",
"space_word_split": "a space is added (one word split)",
"space_substituted": "a space replaced by another character or the reverse",