File size: 9,687 Bytes
fa8b928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3
"""kobench v1 scorer (copy of kbench score_kbench_mp.py + FOREIGN_W / MD_TABLES / th-td normalisation / bbox).
Score engine outputs on kbench v1. Format-neutral: HTML tags and Markdown syntax are stripped before text metrics
(the 2026-09-29 GT audit showed markup-sensitive CER misranks engines). Per slice:
  tables        TEDS and TEDS-S (apted, odlb's evaluator) of the best-matching predicted table vs the HWPX grid,
                plus grid_exact (row-width sequence equal)
  suneung2026   CER vs PDF text; retention of ㉠~㉤, ⓐ~ⓔ, ①~⑤, <보기> (count in pred / count in truth, capped at 1)
  user_real     CER vs PDF text
  kdi_headings  heading recall (truth bookmark titles found in a heading line: Native title block or Markdown '#'), CER
Usage: score_kbench.py MANIFEST ENGINE=PRED.jsonl ... [--tier core|full]   (PRED rows: {"id": kbench id, "text": output})"""

import json, re, sys, unicodedata, collections, html as H

sys.path.insert(
    0,
    __import__("os").environ.get("ODLB_SRC", "opendataloader-bench/src"),
)
from evaluator_table import TEDSEvaluator
from converter_markdown_table import convert_to_markdown_with_html_tables
from rapidfuzz.distance import (
    Levenshtein,
)  # runs in the odlb uv env (apted + rapidfuzz)

argv = sys.argv[1:]
tier = "full"
if "--tier" in argv:
    i = argv.index("--tier")
    tier = argv[i + 1]
    argv = argv[:i] + argv[i + 2 :]
args = argv
M = [json.loads(l) for l in open(args[0])]
M = [r for r in M if tier in r["tier"]]
import os as _o
FOREIGN_W = float(_o.environ.get("FOREIGN_W", "2"))   # extra errors per foreign char not in truth (1 edit + W)
MD_TABLES = _o.environ.get("MD_TABLES", "zero")  # owner 10/04: our HTML output is the standard    # convert | zero (only real HTML <table> counts)
FOREIGN_RE = re.compile("[㐀-䶿一-鿿豈-﫿぀-ヿㇰ-ㇿЀ-ӿ"
                        "฀-๿؀-ۿ֐-׿,。:;!?]")


NORM = _o.environ.get("NORM", "strong")  # basic = kbench plain() | strong = + NFKC, letters/digits only


def nrm(x):
    # strong: NFKC and keep letters/digits only, so punctuation, bullets, arrows, quotes and dashes never count
    if NORM == "basic":
        return x
    x = unicodedata.normalize("NFKC", x)
    return "".join(ch for ch in x if ch.isalnum())


def foreign_extra(p, t):
    """Foreign-script chars (Han, kana, Cyrillic, Thai, Arabic, Hebrew, Chinese full-width punctuation) the prediction
    has beyond the truth's own count of the same char. Hanja that the truth really contains costs nothing."""
    pc = collections.Counter(FOREIGN_RE.findall(p)); tc = collections.Counter(FOREIGN_RE.findall(t))
    return sum(max(0, n - tc[c]) for c, n in pc.items())


BOX_RE = re.compile(r"<\|det\|>[^<]*?\[\[?\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\]\]?[^<]*?<\|/det\|>")


def bbox_rate(out):
    """Share of output blocks that carry a 4-number box: boxed det spans / (det spans + unboxed paragraphs)."""
    boxed = len(BOX_RE.findall(out))
    rest = re.sub(r"<\|det\|>.*?<\|/det\|>[^\n]*", "\n", out, flags=re.S)
    rest = re.sub(r"<\|ref\|>.*?<\|/ref\|>", "", rest, flags=re.S)
    loose = [b for b in re.split(r"\n\s*\n|</table>|<table", rest) if plain(b)]
    return boxed / max(1, boxed + len(loose))


def order_score(pp, t):
    """Reading order: truth lines (>=6 chars) located in the prediction by a 10-char key; score = longest increasing
    subsequence of their positions / located lines. None when fewer than 2 lines are located."""
    import bisect
    pos = []
    for ln in t.splitlines():
        k = plain(ln)[:10]
        if len(k) >= 6:
            i = pp.find(k)
            if i >= 0:
                pos.append(i)
    if len(pos) < 2:
        return None
    tails = []
    for x in pos:
        j = bisect.bisect_left(tails, x)
        tails[j:j + 1] = [x]
    return len(tails) / len(pos)


def norm_table(t):
    t = re.sub(r"<(/?)th\b", r"<\1td", t, flags=re.I)
    t = re.sub(r"</?(thead|tbody|tfoot)[^>]*>", "", t, flags=re.I)
    return re.sub(r"<(td|tr|table)\b([^>]*)>", lambda m: "<" + m[1] + "".join(re.findall(r"\s(?:rowspan|colspan)=\"?\d+\"?", m[2])) + ">", t, flags=re.I)


MARKS = list("㉠㉡㉢㉣㉤ⓐⓑⓒⓓⓔ①②③④⑤") + ["<보기>"]


def plain(s):
    s = unicodedata.normalize("NFC", s)
    s = re.sub(r"<\|det\|>.*?<\|/det\|>", "\n", s)
    s = re.sub(
        r"<\|ref\|>.*?<\|/ref\|>", "\n", s
    )  # DeepSeek-OCR grounding labels (table, sub_title, ...)
    s = re.sub(r"<[^>]+>", " ", s)
    s = H.unescape(s)
    s = re.sub(r"(?m)^\s*#{1,6}\s*", "", s)
    s = re.sub(r"[|*_`]|:?-{3,}:?|!\[[^\]]*\]\([^)]*\)|\$\$?|\\\\[()\[\]]", " ", s)
    return re.sub(r"\s+", "", s)


def cer(p, t):
    p, t = plain(p), plain(t)
    return min(1.0, Levenshtein.distance(p, t) / max(1, len(t)))


def grid_html(rows):
    return (
        "<table>"
        + "".join(
            "<tr>"
            + "".join(
                f'<td colspan="{c["cs"]}" rowspan="{c["rs"]}">{H.escape(c["text"])}</td>'
                for c in r
            )
            + "</tr>"
            for r in rows
        )
        + "</table>"
    )


def widths(t):
    return [len(re.findall(r"<td", r)) for r in re.findall(r"<tr>(.*?)</tr>", t, re.S)]


_t, _ts = TEDSEvaluator(structure_only=False), TEDSEvaluator(structure_only=True)
wrap = lambda t: f"<html><body>{t}</body></html>"


class _W:
    def __init__(s, e):
        s.e = e

    def evaluate(s, p, g):
        return s.e.evaluate(wrap(p), wrap(g))


teds, teds_s = _W(_t), _W(_ts)


def tables_of(out):
    out = re.sub(r"<\|det\|>.*?<\|/det\|>", "\n", out)
    if MD_TABLES == "convert":
        out = convert_to_markdown_with_html_tables(out)
    # 2026-10-01: malformed span (rowspan="" / "abc" / "0") crashed odlb int(); treat it as span 1
    out = re.sub(r'''\s(?:rowspan|colspan)\b(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?''', lambda m: m[0] if re.fullmatch(r'\s*[1-9]\d*\s*', next((g for g in m.groups() if g is not None), '')) else ' ', out, flags=re.I)
    return [norm_table(x) for x in re.findall(r"<table.*?</table>", out, re.S | re.I)]


def headings_of(out):
    hs = [m for m in re.findall(r"<\|det\|>title \[[^\]]*\]<\|/det\|>([^\n]*)", out)]
    hs += re.findall(r"(?m)^\s*#{1,6}\s*(.+)$", out)
    return [plain(h) for h in hs]


def score_one(job):
    eng, r, out = job
    sl = r["slice"]
    S = collections.defaultdict(list)
    if out is None:
        S["missing"].append(1)
        return eng, sl, dict(S), r["id"]
    tr = r["truth"]
    S["bbox"].append(bbox_rate(out))
    if tr["type"] == "table_grid":
        g = grid_html(tr["rows"])
        cands = tables_of(out)
        if not cands:
            S["teds"].append(0); S["teds_s"].append(0); S["grid_exact"].append(0)
            return eng, sl, dict(S), r["id"]
        def _safe(f, a, b):
            try:
                return f.evaluate(a, b)
            except Exception:
                return 0.0  # malformed pred table (e.g. rowspan="") scores 0; the sequential scorer crashes here
        sc = [(_safe(teds, c, g), c) for c in cands]
        best, c = max(sc, key=lambda x: x[0])
        gt_plain = plain(" ".join(x["text"] for row in tr["rows"] for x in row))
        S["foreign"].append(foreign_extra(plain(out), gt_plain))
        best = max(0.0, best - FOREIGN_W * S["foreign"][-1] / max(1, len(gt_plain)))
        S["teds"].append(best); S["teds_s"].append(_safe(teds_s, c, g)); S["grid_exact"].append(float(widths(c) == widths(g)))
    else:
        t = open(tr["text"]).read()
        if r["id"].startswith("suneung2026/math"):
            out = re.sub(r"\\\(.*?\\\)|\\\[.*?\\\]|\$\$.*?\$\$|\$[^$\n]*\$", " ", out, flags=re.S)
        pp, tp = plain(out), plain(t)
        fx = foreign_extra(pp, tp); S["foreign"].append(fx)
        _o_s = order_score(pp, t)
        if _o_s is not None:
            S["order"].append(_o_s)
        np_, nt_ = nrm(pp), nrm(tp)
        S["cer"].append(min(1.0, (Levenshtein.distance(np_, nt_) + FOREIGN_W * fx) / max(1, len(nt_))))
        if sl == "suneung2026":
            for mk in MARKS:
                n = t.count(mk)
                if n:
                    S["mark_keep"].append(min(1.0, out.count(mk) / n))
        if tr["type"] == "headings+page_text":
            hs = headings_of(out)
            for lv, title in tr["headings"]:
                k = plain(title)
                S["heading_recall"].append(float(any(k and (k in h or h in k) and len(h) >= 0.6 * len(k) for h in hs)))
    return eng, sl, dict(S), r["id"]


import multiprocessing as _mp, os as _os

jobs = []
for spec in args[1:]:
    eng, path = spec.split("=", 1)
    P = {}
    for l in open(path):
        d = json.loads(l)
        P[d["id"]] = d.get("text") or ""
    for r in M:
        jobs.append((eng, r, P.get(r["id"])))
res = collections.defaultdict(lambda: collections.defaultdict(list))
with _mp.get_context("fork").Pool(int(_os.environ.get("SCORE_PROCS", "32"))) as pool:
    _dump = open(_os.environ["DUMP"], "w") if _os.environ.get("DUMP") else None  # per-page metrics for re-weighting
    for eng, sl, S, pid in pool.imap(score_one, jobs, chunksize=2):
        if _dump:
            _dump.write(json.dumps({"engine": eng, "slice": sl, "id": pid, **S}, ensure_ascii=False) + "\n")
        for k, v in S.items():
            res[(eng, sl)][k] += v
print(f"tier={tier}")
for (eng, sl), S in sorted(res.items(), key=lambda x: (x[0][1], x[0][0])):
    parts = [f"{k} {sum(v) / len(v):.4f}" for k, v in S.items() if k != "missing" and v]
    print(
        f"{sl:14s} {eng:10s} n={max((len(v) for k, v in S.items() if k != 'missing'), default=0):4d} missing={len(S['missing'])} "
        + " ".join(parts)
    )