File size: 10,677 Bytes
24aaa76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | """Descriptive proposal metrics from EXISTING test predictions (plan amendment n 8). No model is run.
Aggregates only; no reference or hypothesis text is written."""
import json, os, re, sys, unicodedata, datetime, hashlib
from multiprocessing import Pool
import numpy as np
CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
sys.path.insert(0, CODE + "/src")
sys.path.insert(0, CODE + "/src/pagesynth")
from r5eval.align import align_ops, lev_fast # scorer alignment, unchanged
from pagesynth import text as ptext # project alphabet tables
R5 = DATA + "/outputs/r5"
TP = R5 + "/testpass2/preds"
B = 1000
SEED = 20261121
LANGS = ptext.LANG_ORDER
LANG_RX = re.compile(r"(?:^|[_:])(uz_cyrl|uz_latn|kk|ky|tt|ba|sah|tr|az|tk)_\d")
def tasks():
t = []
for s in ["az_localdoc_test", "rukopys_test", "synth_hand_test", "synth_typed_test"]:
t.append(("M1_PaddleOCR-VL-1.6_ft_testpass2", s, f"{TP}/m1_{s}/paddleocr_vl_1_6/leader/{s}.tsv"))
t.append(("Qwen3-VL-2B_amendment5_or_testpass2", s, f"{TP}/q_{s}/qwen3_vl_2b/leader/{s}.tsv"))
t.append(("M2_PP-OCRv6-medium_labelfree_greedy", s, f"{TP}/m2lf_{s}/A1/long2x_labelfree/{s}.tsv"))
t.append(("M2_PP-OCRv6-medium_labelfree_gatedLM", s, f"{TP}/m2lf_{s}/A1/long2x_labelfree_lm_gated/{s}.tsv"))
s = "kohtd_test"
t.append(("M1_PaddleOCR-VL-1.6_ft_sealed24nov", s, f"{R5}/preds/paddleocr_vl_1_6/leader/{s}.tsv"))
t.append(("Qwen3-VL-2B_sealed24nov", s, f"{R5}/preds/qwen3_vl_2b/leader/{s}.tsv"))
t.append(("M2_PP-OCRv6-medium_labelfree_greedy", s, f"{TP}/m2lf_{s}/A1/long2x_labelfree/{s}.tsv"))
t.append(("M2_PP-OCRv6-medium_labelfree_gatedLM", s, f"{TP}/m2lf_{s}/A1/long2x_labelfree_lm_gated/{s}.tsv"))
return t
def n0(x):
return " ".join(unicodedata.normalize("NFC", x).split())
def read_tsv(p):
rows = []
with open(p, encoding="utf-8", newline="\n") as f:
head = f.readline().rstrip("\n").split("\t")
ii, ir, ih = head.index("id"), head.index("ref"), head.index("hyp")
for line in f:
c = line.rstrip("\n").split("\t")
if len(c) <= max(ii, ir):
continue
rows.append((c[ii], c[ir], c[ih] if len(c) > ih else ""))
return rows
def lang_of(set_name, rid):
if set_name == "kohtd_test":
return "kk"
if set_name == "az_localdoc_test":
return "az"
if set_name == "rukopys_test":
return "ru"
m = LANG_RX.search(rid)
return m.group(1) if m else "unknown"
def script_of(ch):
if not unicodedata.category(ch).startswith("L"):
return None
n = unicodedata.name(ch, "")
if n.startswith("LATIN"):
return "Latn"
if n.startswith("CYRILLIC"):
return "Cyrl"
return None
# marked letters: the project table pagesynth/text.py PROFILES[lang]['special'] (both cases);
# uz_latn: U+02BB (o', g') and U+02BC.
MANUAL_BASE = {"ә": "а", "ғ": "г", "қ": "к", "ң": "н", "ө": "о", "ұ": "у", "ү": "у", "ҳ": "х", "җ": "ж", "ҙ": "з",
"ҡ": "к", "ҫ": "с", "ҕ": "г", "ҥ": "н", "ə": "e", "ı": "i"}
MANUAL_BASE.update({k.upper(): v.upper() for k, v in list(MANUAL_BASE.items()) if k != "ı"})
MANUAL_BASE["İ"] = "I"
def base_of(ch):
if ch in MANUAL_BASE:
return MANUAL_BASE[ch]
d = unicodedata.normalize("NFD", ch)
b = "".join(c for c in d if not unicodedata.category(c).startswith("M"))
return b if b and b != ch else None # һ, і: no base letter defined
def marked_set(lang):
if lang == "uz_latn":
return {"ʻ", "ʼ"}
if lang in ptext.PROFILES:
return set(ptext.PROFILES[lang]["special"].replace(" ", ""))
return set()
ALPHA = {l: {c for c in ptext.alphabet(l) if unicodedata.category(c).startswith("L")} for l in LANGS}
UNIQUE = {l: ALPHA[l] - set().union(*[ALPHA[o] for o in LANGS if o != l]) for l in LANGS}
def boot(num, den, rng):
num = np.asarray(num, float); den = np.asarray(den, float)
n = len(num)
if n == 0 or den.sum() == 0:
return None
out = []
for _ in range(B // 100):
idx = rng.integers(0, n, (100, n))
d = den[idx].sum(1)
out.append(np.where(d > 0, num[idx].sum(1) / np.maximum(d, 1), np.nan))
v = np.concatenate(out)
v = v[~np.isnan(v)]
return [round(float(np.percentile(v, 2.5)), 5), round(float(np.percentile(v, 97.5)), 5)]
def rate(num, den, rng, ci=True):
s, d = float(np.sum(num)), float(np.sum(den))
r = {"num": s, "den": d, "rate": round(s / d, 5) if d else None}
if ci:
r["ci95"] = boot(num, den, rng)
return r
def run(task):
model, set_name, path = task
rng = np.random.default_rng(SEED)
rows = read_tsv(path)
K = {k: [] for k in ["ce", "rl", "we", "rw", "lang", "mk_tot", "mk_ok", "mk_del", "mk_oth", "base_tot", "mk_ins",
"out_let", "out_wrong", "uq_tot", "uq_err", "sh_tot", "sh_err", "id"]}
for rid, ref, hyp in rows:
r, h = n0(ref), n0(hyp)
lang = lang_of(set_name, rid)
dist, ops = align_ops(r, h)
K["id"].append(rid); K["lang"].append(lang)
K["ce"].append(dist); K["rl"].append(len(r))
rwords, hwords = r.split(" ") if r else [], h.split(" ") if h else []
K["we"].append(lev_fast(rwords, hwords) if rwords or hwords else 0); K["rw"].append(len(rwords))
mk = marked_set(lang)
bases = {base_of(c) for c in mk if base_of(c)}
if lang == "uz_latn":
bases = set()
mt = mo = md = mx = bt = mi = 0
ut = ue = st = se = 0
uq = UNIQUE.get(lang, set()); al = ALPHA.get(lang, set())
for op, i, j in ops:
if i < 0:
if lang == "uz_latn" and h[j] in ("ʻ", "ʼ"):
mi += 1
continue
c = r[i]
if c in mk:
mt += 1
if op == "M":
mo += 1
elif op == "D" and lang == "uz_latn":
md += 1
elif op == "S" and base_of(c) is not None and h[j] == base_of(c):
md += 1
else:
mx += 1
elif c in bases:
bt += 1
if op == "S" and h[j] in mk and base_of(h[j]) == c:
mi += 1
if lang in UNIQUE and unicodedata.category(c).startswith("L"):
if c in uq:
ut += 1; ue += op != "M"
elif c in al:
st += 1; se += op != "M"
if lang == "uz_latn":
bt = sum(1 for k in range(len(r)) if r[k] in "oOgG")
K["mk_tot"].append(mt); K["mk_ok"].append(mo); K["mk_del"].append(md); K["mk_oth"].append(mx)
K["base_tot"].append(bt); K["mk_ins"].append(mi)
rs = [script_of(c) for c in r]; nl, nc = rs.count("Latn"), rs.count("Cyrl")
rscript = "Latn" if nl > nc else ("Cyrl" if nc > nl else None)
hs = [script_of(c) for c in h]
ol = sum(1 for x in hs if x)
ow = sum(1 for x in hs if x and rscript and x != rscript)
K["out_let"].append(ol if rscript else 0); K["out_wrong"].append(ow)
K["uq_tot"].append(ut); K["uq_err"].append(ue); K["sh_tot"].append(st); K["sh_err"].append(se)
A = {k: np.asarray(v) for k, v in K.items() if k not in ("id", "lang")}
langs = np.asarray(K["lang"])
res = {"model": model, "set": set_name, "source": path, "rows": len(rows),
"langs": {str(l): int((langs == l).sum()) for l in sorted(set(K["lang"]))}}
with open(path, "rb") as f:
res["source_sha256"] = hashlib.sha256(f.read()).hexdigest()
res["CER"] = rate(A["ce"], A["rl"], rng)
res["WER"] = rate(A["we"], A["rw"], rng)
short = A["rl"] <= 40
res["CER_ref_len_le40"] = rate(A["ce"][short], A["rl"][short], rng) | {"rows": int(short.sum())}
res["CER_ref_len_gt40"] = rate(A["ce"][~short], A["rl"][~short], rng) | {"rows": int((~short).sum())}
res["marks"] = {
"marked_ref_letters": int(A["mk_tot"].sum()),
"correct": rate(A["mk_ok"], A["mk_tot"], rng, False),
"mark_deleted_output_base": rate(A["mk_del"], A["mk_tot"], rng),
"otherwise_wrong": rate(A["mk_oth"], A["mk_tot"], rng, False),
"mark_inserted_on_base": rate(A["mk_ins"], A["base_tot"], rng)}
res["wrong_script_share_of_output_letters"] = rate(A["out_wrong"], A["out_let"], rng)
per = {}
for l in sorted(set(K["lang"])):
m = langs == l
d = {"rows": int(m.sum()),
"CER": rate(A["ce"][m], A["rl"][m], rng, False),
"WER": rate(A["we"][m], A["rw"][m], rng, False),
"marks_correct": rate(A["mk_ok"][m], A["mk_tot"][m], rng, False),
"mark_deleted": rate(A["mk_del"][m], A["mk_tot"][m], rng),
"marks_otherwise_wrong": rate(A["mk_oth"][m], A["mk_tot"][m], rng, False),
"mark_inserted": rate(A["mk_ins"][m], A["base_tot"][m], rng, False),
"wrong_script_share": rate(A["out_wrong"][m], A["out_let"][m], rng, False)}
if set_name == "synth_hand_test" and l in UNIQUE:
d["unique_letter_error"] = rate(A["uq_err"][m], A["uq_tot"][m], rng)
d["shared_letter_error"] = rate(A["sh_err"][m], A["sh_tot"][m], rng)
d["unique_letters_in_alphabet"] = len(UNIQUE[l])
per[l] = d
res["per_language"] = per
if set_name == "kohtd_test":
p2 = set(r[0] for r in read_tsv(f"{R5}/preds/paddleocr_vl_1_6/leader/kohtd_test_p2.tsv"))
m = np.asarray([i in p2 for i in K["id"]])
res["unseen_words_registry_P2"] = rate(A["ce"][m], A["rl"][m], rng) | {"rows": int(m.sum()), "p2_ids": len(p2)}
res["seen_words_rest"] = rate(A["ce"][~m], A["rl"][~m], rng) | {"rows": int((~m).sum())}
return res
if __name__ == "__main__":
out = sys.argv[1]
with Pool(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) as pool:
results = pool.map(run, tasks(), chunksize=1)
doc = {"written_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"plan": "records/R5/TESTPASS2/plan.json amendment n 8 (amendment 7): descriptive, existing predictions only, no model choice affected",
"bootstrap": f"percentile bootstrap over ROWS (lines or word crops), B {B}, seed {SEED}; rows from one page or writer are not independent, so these intervals are too narrow for the real sets",
"unique_letters_by_language": {l: "".join(sorted(UNIQUE[l])) for l in LANGS},
"results": results}
json.dump(doc, open(out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("wrote", out, len(results))
|