Download src/r5eval/pages.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/r5eval/pages.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/src/r5eval/pages.py
-
curl -L -o pages.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/r5eval/pages.py
13.2 kB
| """Page-level metrics: line detection (M27), page CER with reading order (M28) and order-free (M29, clarification G5), page NED (M30), | |
| reading-order distance (M31) and the labelled-word error LWE of amendment 3.1 (M33, function only). | |
| INPUT FORMATS (documented here; no page prediction exists yet) | |
| Page predictions: one JSON object per line (JSONL), file <page_preds>/<pipeline>/<checkpoint>/<evalset>.jsonl | |
| {"page_id": "<id of the page row of the manifest>", | |
| "lines": [{"text": "...", "box": [x0, y0, x1, y1], "polygon": [[x, y], ...] (optional), "score": 0.93 (optional)}, ...]} | |
| `lines` are in the pipeline's own reading order; coordinates are pixels of the ORIGINAL page image (a pipeline that resized the | |
| page must scale its boxes back). A pipeline without boxes (a VLM reading the whole page) may omit box and score: only the text | |
| metrics are computed for it. | |
| Reference: the manifest rows of the evalset with unit == 'page'. Row 'id' = page id, 'text' = page text (reference lines joined by | |
| single spaces), 'source' = path of the page JSON written by the generator: {"lines": [{"id", "text", "polygon", "box"}, ...]}; the | |
| reference lines and their order are those of this JSON. (school_notebooks_ru polygons built by LINEDET use the same keys.) | |
| Text profile: output lines pass strip_wrappers (the frozen VLM post-processing script) and N0; reference lines N0. Empty lines are dropped. | |
| Detection: IoU of axis-aligned boxes (polygon IoU when shapely is importable and both sides have polygons; the kind is recorded); | |
| detections are matched greedily in score order (file order when no score), each to the unmatched reference line with the highest IoU at | |
| or above the threshold (COCO matching, cocoeval.py lines 255-296); thresholds 0.5 and 0.75. | |
| Cost conventions: M28 CER = summed edit distance of the page texts (lines joined by single spaces, output in file order) / summed length | |
| of the reference page texts. M29 = minimum-cost one-to-one assignment of reference lines to output lines (edit distance); an unassigned | |
| reference line costs its length, an unassigned output line costs its length (invented text is charged in full); denominator = summed | |
| length of the reference lines (no joining spaces). The two denominators differ by the (lines - 1) joining spaces per page. | |
| """ | |
| import json | |
| import os | |
| import unicodedata | |
| import numpy as np | |
| from . import stats, textnorm | |
| from .align import lev_fast, min_cost_line_assignment | |
| IOU_THRESHOLDS = (0.5, 0.75) | |
| def box_iou(a, b): | |
| ix0, iy0 = max(a[0], b[0]), max(a[1], b[1]) | |
| ix1, iy1 = min(a[2], b[2]), min(a[3], b[3]) | |
| iw, ih = max(0.0, ix1 - ix0), max(0.0, iy1 - iy0) | |
| inter = iw * ih | |
| ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter | |
| return inter / ua if ua > 0 else 0.0 | |
| def poly_box(poly): | |
| xs = [p[0] for p in poly] | |
| ys = [p[1] for p in poly] | |
| return [min(xs), min(ys), max(xs), max(ys)] | |
| def poly_iou(pa, pb): | |
| try: | |
| from shapely.geometry import Polygon | |
| except ImportError: | |
| return None | |
| a, b = Polygon(pa), Polygon(pb) | |
| if not a.is_valid or not b.is_valid: | |
| a, b = a.buffer(0), b.buffer(0) | |
| u = a.union(b).area | |
| return a.intersection(b).area / u if u > 0 else 0.0 | |
| def line_box(line): | |
| if line.get("box"): | |
| return [float(v) for v in line["box"]] | |
| if line.get("polygon"): | |
| return poly_box(line["polygon"]) | |
| return None | |
| def pair_iou(d, r, use_poly): | |
| if use_poly and d.get("polygon") and r.get("polygon"): | |
| v = poly_iou(d["polygon"], r["polygon"]) | |
| if v is not None: | |
| return v | |
| return box_iou(line_box(d), line_box(r)) | |
| def match_detections(dets, refs, thr, use_poly=False): | |
| """COCO-style greedy matching. dets: list of line dicts (score optional), refs: list of line dicts. Returns list of (det idx, ref idx).""" | |
| order = sorted(range(len(dets)), key=lambda i: -(dets[i].get("score") if dets[i].get("score") is not None else 0.0)) | |
| if all(d.get("score") is None for d in dets): | |
| order = list(range(len(dets))) | |
| used = set() | |
| pairs = [] | |
| for i in order: | |
| best, bj = thr - 1e-12, -1 | |
| for j, r in enumerate(refs): | |
| if j in used: | |
| continue | |
| v = pair_iou(dets[i], r, use_poly) | |
| if v >= best: | |
| if v > best or bj < 0: | |
| best, bj = v, j | |
| if bj >= 0: | |
| used.add(bj) | |
| pairs.append((i, bj)) | |
| return pairs | |
| def _clean_lines(lines, strip): | |
| out = [] | |
| for ln in lines: | |
| t = ln.get("text", "") | |
| t = textnorm.norm(textnorm.strip_wrappers_pp(t) if strip else t) | |
| d = dict(ln) | |
| d["text"] = t | |
| out.append(d) | |
| return [d for d in out if d["text"]] | |
| def kendall_tau(a): | |
| """Kendall tau between 0..n-1 and the sequence a (a permutation of ranks).""" | |
| n = len(a) | |
| if n < 2: | |
| return None | |
| conc = disc = 0 | |
| for i in range(n): | |
| for j in range(i + 1, n): | |
| if a[i] < a[j]: | |
| conc += 1 | |
| elif a[i] > a[j]: | |
| disc += 1 | |
| return (conc - disc) / (n * (n - 1) / 2) | |
| def page_scores(ref_lines, out_lines, strip=True, use_poly=False): | |
| """Per-page counts for every page metric.""" | |
| refs = _clean_lines(ref_lines, False) | |
| outs = _clean_lines(out_lines, strip) | |
| ref_texts = [r["text"] for r in refs] | |
| out_texts = [o["text"] for o in outs] | |
| ref_page = " ".join(ref_texts) | |
| out_page = " ".join(out_texts) | |
| f = {"pages": 1, "ref_len_page": len(ref_page), "ref_len_lines": sum(len(t) for t in ref_texts), "out_len_lines": sum(len(t) for t in out_texts), | |
| "n_ref_lines": len(refs), "n_out_lines": len(outs)} | |
| f["dist_ordered"] = lev_fast(ref_page, out_page) | |
| cost, pairs = min_cost_line_assignment(ref_texts, out_texts) | |
| f["cost_orderfree"] = cost | |
| f["page_ned_sum"] = f["dist_ordered"] / max(len(ref_page), len(out_page), 1) | |
| # reading order on matched lines | |
| if pairs: | |
| pr = sorted(pairs) # by reference index | |
| outpos = [j for _, j in pr] | |
| out_rank = {j: r for r, j in enumerate(sorted(outpos))} | |
| t = len(pr) | |
| ard = sum(abs(r - out_rank[j]) for r, (_, j) in enumerate(pr)) | |
| n = len(refs) | |
| f["ard_sum"] = (ard + (n - t) * n) / n if n else 0.0 | |
| tau = kendall_tau([out_rank[j] for _, j in pr]) | |
| if tau is not None: | |
| f["tau_sum"] = tau | |
| f["tau_pages"] = 1 | |
| elif refs: | |
| f["ard_sum"] = float(len(refs)) | |
| # detection (needs boxes on both sides) | |
| have_boxes = all(line_box(r) is not None for r in refs) and all(line_box(o) is not None for o in outs) and bool(outs or refs) | |
| if have_boxes: | |
| for thr in IOU_THRESHOLDS: | |
| m = match_detections(outs, refs, thr, use_poly) | |
| key = "iou%02d" % int(round(thr * 100)) | |
| f["tp_" + key] = len(m) | |
| f["det_" + key] = len(outs) | |
| f["gt_" + key] = len(refs) | |
| f["det_pages"] = 1 | |
| return f | |
| PAGE_RATIOS = [ | |
| ("page_cer_ordered", "dist_ordered", "ref_len_page", "M28 page CER with reading order (output lines in file order)"), | |
| ("page_cer_order_free", "cost_orderfree", "ref_len_lines", "M29 order-free page CER (line assignment, invented lines charged)"), | |
| ("page_ned_mean", "page_ned_sum", "pages", "M30 mean over pages of edit distance / max length (OmniDocBench style, comparison only)"), | |
| ("reading_order_ard", "ard_sum", "pages", "M31 average relative distance of reading order (mean over pages)"), | |
| ("reading_order_kendall_tau", "tau_sum", "tau_pages", "M31 Kendall tau of matched lines (mean over pages)"), | |
| ("out_to_ref_char_ratio", "out_len_lines", "ref_len_lines", "output characters per reference character"), | |
| ("det_precision_iou50", "tp_iou50", "det_iou50", "M27 line detection precision at IoU 0.5"), | |
| ("det_recall_iou50", "tp_iou50", "gt_iou50", "M27 line detection recall at IoU 0.5"), | |
| ("det_f1_iou50", "tp2_iou50", "dg_iou50", "M27 line detection F1 at IoU 0.5 (2 TP / (detections + reference lines))"), | |
| ("det_precision_iou75", "tp_iou75", "det_iou75", "M27 line detection precision at IoU 0.75"), | |
| ("det_recall_iou75", "tp_iou75", "gt_iou75", "M27 line detection recall at IoU 0.75"), | |
| ("det_f1_iou75", "tp2_iou75", "dg_iou75", "M27 line detection F1 at IoU 0.75"), | |
| ] | |
| def aggregate_pages(per_page, B=stats.B_DEFAULT, seed=stats.SEED_BASE): | |
| """per_page: list of feature dicts (from page_scores), one per page (the cluster is the page). Returns metrics with intervals.""" | |
| K = len(per_page) | |
| keys = set() | |
| for p in per_page: | |
| keys |= set(p) | |
| cols = {k: np.array([p.get(k, 0.0) for p in per_page], dtype=np.float64) for k in keys} | |
| for thr in ("iou50", "iou75"): | |
| if "tp_" + thr in cols: | |
| cols["tp2_" + thr] = 2 * cols["tp_" + thr] | |
| cols["dg_" + thr] = cols["det_" + thr] + cols["gt_" + thr] | |
| lst = [(n, cols[nf], cols[df], plain) for n, nf, df, plain in PAGE_RATIOS if nf in cols and df in cols and cols[df].sum() > 0] | |
| out = {} | |
| if not lst: | |
| return out | |
| M = np.hstack([np.column_stack([a for _, a, _, _ in lst]), np.column_stack([b for _, _, b, _ in lst])]) | |
| idx = np.arange(K) | |
| reps = stats.boot_matmul(idx, M, K, B, seed) if K >= 2 else None | |
| r = len(lst) | |
| for i, (n, a, b, plain) in enumerate(lst): | |
| rec = {"value": float(a.sum() / b.sum()), "num": float(a.sum()), "den": float(b.sum()), "lo": None, "hi": None, "plain_name": plain} | |
| if reps is not None: | |
| rec["lo"], rec["hi"], _ = stats.ratio_ci(reps[:, i], reps[:, r + i]) | |
| out[n] = rec | |
| out["order_cost_cer"] = {"value": out["page_cer_ordered"]["value"] - out["page_cer_order_free"]["value"], | |
| "plain_name": "M28 minus M29 (reading-order cost; denominators differ by the joining spaces)"} \ | |
| if "page_cer_ordered" in out and "page_cer_order_free" in out else None | |
| return out | |
| def load_ref_lines(source_json): | |
| d = json.load(open(source_json, encoding="utf-8")) | |
| return [{"text": unicodedata.normalize("NFC", ln.get("text", "")), "box": ln.get("box"), "polygon": ln.get("polygon")} for ln in d["lines"]] | |
| def score_page_file(pred_jsonl, page_rows, B=stats.B_DEFAULT, seed=stats.SEED_BASE, strip=True, use_poly=False): | |
| """page_rows: manifest rows with unit == 'page' (id, source). Returns dict with metrics, coverage and per-page counts.""" | |
| preds = {} | |
| with open(pred_jsonl, encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| d = json.loads(line) | |
| except ValueError: | |
| continue | |
| if "page_id" in d: | |
| preds[d["page_id"]] = d | |
| per, missing = [], 0 | |
| for r in page_rows: | |
| d = preds.get(r["id"]) | |
| if d is None: | |
| missing += 1 | |
| continue | |
| per.append(page_scores(load_ref_lines(r["source"]), d.get("lines", []), strip=strip, use_poly=use_poly)) | |
| res = {"coverage": {"manifest_pages": len(page_rows), "scored_pages": len(per), "missing_pages": missing, | |
| "complete": missing == 0 and len(per) > 0}, | |
| "iou_kind": "polygon" if use_poly else "axis-aligned box", "text_profile": "strip_wrappers + N0" if strip else "N0", | |
| "bootstrap": {"B": B, "seed": seed, "unit": "page", "label": "page bootstrap"}} | |
| res["metrics"] = aggregate_pages(per, B, seed) if per else {} | |
| return res | |
| # ---------------------------------------------------------------- labelled-word error of amendment 3.1 (M33), function only --- | |
| def lwe_page(ref_words, out_tokens, min_len=3): | |
| """Amendment 3.1 C1 for one sheet. Reference words shorter than min_len are left out. A minimum-cost one-to-one assignment between | |
| reference words and output tokens with cost = edit distance; a reference word may stay unassigned at a cost equal to its length; | |
| a pair whose distance is not smaller than the length of the reference word counts as unassigned; output tokens assigned to no | |
| reference word cost nothing. Returns dict(cost, ref_chars, exact_words, ref_words, out_chars).""" | |
| from scipy.optimize import linear_sum_assignment | |
| refs = [textnorm.norm(w) for w in ref_words] | |
| refs = [w for w in refs if len(w) >= min_len] | |
| outs = [textnorm.norm(t) for t in out_tokens] | |
| outs = [t for t in outs if t] | |
| R, O = len(refs), len(outs) | |
| ref_chars = sum(len(w) for w in refs) | |
| if R == 0: | |
| return {"cost": 0.0, "ref_chars": 0, "exact_words": 0, "ref_words": 0, "out_chars": sum(len(t) for t in outs)} | |
| big = 1e9 | |
| c = np.full((R, O + R), big) | |
| dmat = np.zeros((R, O)) | |
| for i, r in enumerate(refs): | |
| for j, h in enumerate(outs): | |
| dmat[i, j] = lev_fast(r, h) | |
| c[i, j] = dmat[i, j] if dmat[i, j] < len(r) else len(r) # a pair not better than leaving the word unassigned is unassigned | |
| c[i, O + i] = len(r) | |
| ri, ci = linear_sum_assignment(c) | |
| cost = float(c[ri, ci].sum()) | |
| exact = sum(1 for i, j in zip(ri, ci) if j < O and dmat[i, j] == 0) | |
| return {"cost": cost, "ref_chars": ref_chars, "exact_words": exact, "ref_words": R, "out_chars": sum(len(t) for t in outs)} | |