File size: 5,379 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
"""Test pass 2: score the Kazakh real-document benchmark handwritten pages (DESCRIPTIVE ONLY: references model-drafted, then
corrected; human check claimed by the card but not proven, plan.json amendment 2).

Metric as tp2_page_score.py: linedet.det_eval.page_cers (M28 reading order, M29 order free), micro over pages, case-sensitive
(primary) and lower-cased with str.lower (secondary; Kazakh has no dotted/dotless I rule). Reference lines (kz_ref_lines): the data.csv
text, NFC, split at line breaks, whitespace runs to one space, empty lines dropped; no markup stripping (the card's scan found no
Markdown or HTML in the handwritten references). Also, as the card suggests: the per-page mean of M28 CER capped at 1.0, and the count
of pages whose uncapped M28 CER exceeds 1.0. Slices: all 150 pages; pages 0001-0030 (references 'drafted by a vision-language model,
then corrected by hand' per the card). Interval: 95% percentile bootstrap over pages, B 10000, seed 20261121.

usage: tp2_kzb_score.py --pages TSV --pred JSONL --gate-file F --out JSON
"""
import argparse
import csv
import json
import os
import sys
import unicodedata

import numpy as np

sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
from linedet.det_eval import page_cers  # noqa: E402
from r5eval import stats  # noqa: E402


def kz_ref_lines(text):
    out = []
    for ln in unicodedata.normalize("NFC", text).splitlines():
        ln = " ".join(ln.split())
        if ln:
            out.append(ln)
    return out


def ratio(M, reps, i, j):
    v = float(M[:, i].sum() / M[:, j].sum()) if M[:, j].sum() > 0 else None
    lo = hi = None
    if reps is not None:
        lo, hi, _ = stats.ratio_ci(reps[:, i], reps[:, j])
    return {"value": v, "lo": lo, "hi": hi, "num": float(M[:, i].sum()), "den": float(M[:, j].sum())}


def cell(per, B, seed):
    names = ["ro", "of", "nref", "ro_lc", "of_lc", "nref_lc", "hyp_chars", "ref_line_chars", "capped", "one"]
    M = np.array([[p[n] for n in names] for p in per], dtype=np.float64)
    reps = stats.boot_matmul(np.arange(len(per)), M, len(per), B, seed) if len(per) >= 2 else None
    ix = {n: k for k, n in enumerate(names)}
    return {"pages": len(per), "reference_chars": int(M[:, ix["nref"]].sum()),
            "reading_order_cer": ratio(M, reps, ix["ro"], ix["nref"]), "order_free_cer": ratio(M, reps, ix["of"], ix["nref"]),
            "reading_order_cer_lowercase": ratio(M, reps, ix["ro_lc"], ix["nref_lc"]),
            "order_free_cer_lowercase": ratio(M, reps, ix["of_lc"], ix["nref_lc"]),
            "per_page_mean_reading_order_cer_capped_1": ratio(M, reps, ix["capped"], ix["one"]),
            "pages_reading_order_cer_above_1": int(sum(1 for p in per if p["nref"] and p["ro"] / p["nref"] > 1.0)),
            "output_to_reference_char_ratio": ratio(M, reps, ix["hyp_chars"], ix["ref_line_chars"]),
            "pages_with_no_output_line": sum(1 for p in per if p["n_hyp"] == 0),
            "pages_with_hit_cap_lines": sum(1 for p in per if p["n_hit_cap"] > 0),
            "mean_seconds_per_page": round(float(np.mean([p["seconds"] for p in per])), 1)}


ap = argparse.ArgumentParser()
ap.add_argument("--pages", required=True)
ap.add_argument("--pred", required=True)
ap.add_argument("--gate-file", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--B", type=int, default=10000)
ap.add_argument("--seed", type=int, default=20261121)
a = ap.parse_args()
if not os.path.exists(a.gate_file):
    print("REFUSED: gate file missing")
    sys.exit(3)
with open(a.pages, encoding="utf-8", newline="") as f:
    pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
pred = {}
for ln in open(a.pred, encoding="utf-8"):
    r = json.loads(ln)
    pred[r["id"]] = r
per, missing = [], []
for pg in pages:
    r = pred.get(pg["id"])
    if r is None:
        missing.append(pg["id"])
        continue
    ref = kz_ref_lines(open(pg["ref_md"], encoding="utf-8").read())
    hyp = r["hyp_lines"]
    ro, of, nref = page_cers(hyp, ref)
    ro_lc, of_lc, nref_lc = page_cers([h.lower() for h in hyp], [x.lower() for x in ref])
    per.append({"id": pg["id"], "ro": ro, "of": of, "nref": nref, "ro_lc": ro_lc, "of_lc": of_lc, "nref_lc": nref_lc,
                "hyp_chars": sum(len(h) for h in hyp), "ref_line_chars": sum(len(x) for x in ref),
                "capped": min(ro / nref, 1.0) if nref else 0.0, "one": 1.0 if nref else 0.0, "n_hyp": len(hyp), "n_ref": len(ref),
                "n_boxes": r.get("n_boxes"), "n_hit_cap": r.get("n_hit_cap", 0), "seconds": r.get("seconds", 0.0)})
first30 = [p for p in per if p["id"].isdigit() and int(p["id"]) <= 30]
res = {"label": "kzb_hand", "status": "DESCRIPTIVE ONLY", "pages_file": a.pages, "pred_file": a.pred, "scored_pages": len(per),
       "missing_pages": len(missing), "complete": not missing, "bootstrap": {"B": a.B, "seed": a.seed, "unit": "page"},
       "all": cell(per, a.B, a.seed) if per else None,
       "pages_0001_0030_hand_corrected_per_card": cell(first30, a.B, a.seed) if first30 else None,
       "per_page_counts": [{k: p[k] for k in ("id", "nref", "ro", "of", "n_hyp", "n_ref", "n_boxes", "n_hit_cap")} for p in per]}
json.dump(res, open(a.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
c = res["all"]
print("kzb_hand pages", len(per), "missing", len(missing), "ro", c["reading_order_cer"]["value"] if c else None)