File size: 6,465 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
"""Test pass 2: score the TurkishOCR-Bench pages read by the two-model pipeline (YOLO11s stage 2 + M1).

Page CER exactly as linedet.det_eval.page_cers (imported, not copied): M28 reading order (hypothesis lines in the pipeline's order,
reference lines in file order, each joined by one space) and M29 order free (lines matched one to one by minimum edit distance,
unmatched lines charged in full). Micro average over pages: summed edits / summed reference characters.

Reference lines (pre-registered in plan.json, section pages.reference): the page's ground-truth file dogru_metin/<cat>/<id>.md, NFC;
HTML comments removed; </td> </th> -> space; </tr> and <br> -> line break; the tags header, footer, figure, table, thead, tbody,
tfoot, tr, td, th, br, sup, sub, span, div, p, b, i, u, em, strong, img, caption, colgroup, col removed (their text content kept);
per line: a leading Markdown heading marker (#..######) and the emphasis markers ** and __ removed, whitespace runs to one space,
empty lines dropped. LaTeX and all other characters kept. Case-sensitive (primary); Turkish case fold of both sides (secondary;
textnorm.fold_lower with lang tr, the benchmark's own handwriting rule ignores case).
Interval: 95% percentile bootstrap over source documents (field belge), B = 10000, seed 20261121, r5eval.stats.

usage: tp2_page_score.py --pages TSV --pred JSONL [--pred JSONL ...] --label NAME --gate-file F --out JSON
"""
import argparse
import collections
import csv
import json
import os
import re
import sys
import unicodedata

import numpy as np

CODE = "/path/to/TURKIC_OCR_CODE"
sys.path.insert(0, CODE + "/src")
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from linedet.det_eval import page_cers  # noqa: E402
from r5eval import stats, textnorm  # noqa: E402
from tp2_tob_img import tob_ref_lines  # noqa: E402


def boot(groups, cols, B, seed):
    """groups: list of group keys per page; cols: dict name -> per-page array. Returns per-group sums matrix and replicates."""
    keys = sorted(set(groups))
    pos = {k: i for i, k in enumerate(keys)}
    names = sorted(cols)
    M = np.zeros((len(keys), len(names)))
    for j, n in enumerate(names):
        for g, v in zip(groups, cols[n]):
            M[pos[g], j] += v
    reps = stats.boot_matmul(np.arange(len(keys)), M, len(keys), B, seed) if len(keys) >= 2 else None
    return keys, names, M, reps


def ratio(names, M, reps, num, den):
    i, j = names.index(num), names.index(den)
    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):
    groups = [p["belge"] for p in per]
    cols = {k: [p[k] for p in per] for k in ("ro", "of", "nref", "ro_cf", "of_cf", "nref_cf", "hyp_chars", "ref_line_chars")}
    keys, names, M, reps = boot(groups, cols, B, seed)
    return {"pages": len(per), "documents": len(keys), "reference_chars": int(sum(cols["nref"])),
            "reading_order_cer": ratio(names, M, reps, "ro", "nref"),
            "order_free_cer": ratio(names, M, reps, "of", "nref"),
            "reading_order_cer_casefold_tr": ratio(names, M, reps, "ro_cf", "nref_cf"),
            "order_free_cer_casefold_tr": ratio(names, M, reps, "of_cf", "nref_cf"),
            "output_to_reference_char_ratio": ratio(names, M, reps, "hyp_chars", "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) if per else None}


ap = argparse.ArgumentParser()
ap.add_argument("--pages", required=True)
ap.add_argument("--pred", action="append", required=True)
ap.add_argument("--label", 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", flush=True)
    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 p in a.pred:
    for ln in open(p, 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 = tob_ref_lines(open(pg["ref_md"], encoding="utf-8").read())
    hyp = r["hyp_lines"]
    ro, of, nref = page_cers(hyp, ref)
    hyp_cf = [textnorm.fold_lower(h, "tr") for h in hyp]
    ref_cf = [textnorm.fold_lower(x, "tr") for x in ref]
    ro_cf, of_cf, nref_cf = page_cers(hyp_cf, ref_cf)
    per.append({"id": pg["id"], "kategori": pg["kategori"], "belge": pg["belge"], "ro": ro, "of": of, "nref": nref, "ro_cf": ro_cf,
                "of_cf": of_cf, "nref_cf": nref_cf, "hyp_chars": sum(len(h) for h in hyp), "ref_line_chars": sum(len(x) for x in ref),
                "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)})
res = {"label": a.label, "pages_file": a.pages, "pred_files": a.pred, "scored_pages": len(per), "missing_pages": len(missing),
       "complete": not missing, "bootstrap": {"B": a.B, "seed": a.seed, "unit": "source document (belge)"},
       "metric": "linedet.det_eval.page_cers (M28 reading order, M29 order free), micro over pages",
       "all": cell(per, a.B, a.seed) if per else None, "by_category": {}}
cats = collections.defaultdict(list)
for p in per:
    cats[p["kategori"]].append(p)
if len(cats) > 1:
    for c, pp in sorted(cats.items()):
        res["by_category"][c] = cell(pp, a.B, a.seed)
res["per_page_counts"] = [{k: p[k] for k in ("id", "kategori", "belge", "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(a.label, "pages", res["scored_pages"], "missing", len(missing), "ro", c["reading_order_cer"]["value"] if c else None,
      "of", c["order_free_cer"]["value"] if c else None, flush=True)