Datasets:
Download code/koocr_score.py from schift-io/KoOCR-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.69 kB
-
https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/koocr_score.py
- Command line
-
hf download hf://datasets/schift-io/KoOCR-Bench/code/koocr_score.py
-
curl -L -o koocr_score.py https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/koocr_score.py
9.69 kB
| #!/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) | |
| ) | |