Download scripts/r5_loopguard/om_score.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 23.8 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_loopguard/om_score.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_loopguard/om_score.py
-
curl -L -o om_score.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_loopguard/om_score.py
23.8 kB
| """ONEMODEL pilot (design ONEMODEL-pilot-1): page scoring and the pre-registered decision. Runs in .venv_kraken (rapidfuzz, | |
| scipy, numpy); imports om_text only (no torch, no transformers). | |
| Page CER: page_cers, iou_matrix and match_count are copied byte for byte from CODE/src/linedet/det_eval.py (M28 reading order: | |
| ' '.join of lines; M29 order free: Hungarian matching of lines by edit distance, unmatched lines count in full); micro over | |
| pages. References come from the build records (det_eval page files): generated = generator order; School = R_SCHOOL (stored | |
| det_prep order partitioned by the gutter); School M28 against the stored order is reported as well (continuity). | |
| Candidate lines = parsed spotting output in output order (om_text.parse_output). Baseline lines = det_eval-cropped leader readings, | |
| empty readings dropped, ordered (design amendment A1) like the set's reference: School = det_order_columns (det_eval key + gutter | |
| split), generated = plain det_order; the other ordering is reported as descriptive. | |
| Detection: parsed boxes in the 1280-px frame vs boxes1280 at IoU 0.5 and 0.75, every prediction scored 1.0, lines without a box | |
| count as unmatched predictions. | |
| Crop gates: R5 scorer outputs <crop-scores>/<arm>/<name>/{V1,synth_clutter_val}.json (plain profile, group all: cer, hr1). | |
| usage: om_score.py --name seed1_final [--baseline-dir DIR] [--out DIR] (full scoring + decision) | |
| om_score.py --baseline-only --baseline-dir DIR (the baseline alone) | |
| om_score.py --smoke-repro (det_eval reproduction on the stored A1 outputs) | |
| LOOPGUARD-1 copy (scripts/r5_loopguard). Unchanged: page_cers, iou_matrix, match_count, boot, boot_diff, the G1/G2/G3 | |
| expressions, B_BOOT and SEED. Added: load_records takes the expected split; --sets may name gen_test / school_test, which are | |
| read from --heldout-root only under the unseal token (role 'score'); the School comparator ordering applies to school_test as | |
| to school_val; --fallback-flags FILE (JSON {set: [page ids]}): the candidate row of a flagged page is replaced by the | |
| baseline row (arm B; the detection block is then not computed); --crop-name (default --name) names the stored crop scores | |
| read for G2/G3; --tag (default --name) names the output files; --exclude-ids FILE (JSON {set: [page ids]}) drops those | |
| pages of a set before scoring (decision of 26 Nov 2026: the 2 generated test pages with near-duplicate images in | |
| the page model's training are left out of the primary held-out confirmation; the run script also scores all pages as a | |
| sensitivity line). With default arguments plus an --out folder the output equals the original's; an --out under | |
| outputs/r6_onemodel (the original default) is refused, so the 55172 score files cannot be overwritten (review F8). | |
| """ | |
| import argparse | |
| import collections | |
| import glob | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import numpy as np | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import om_text as T # noqa: E402 | |
| DATA = "/path/to/TURKIC_OCR_DATA" | |
| CODE = "/path/to/TURKIC_OCR_CODE" | |
| LEADER_V1_CER = 0.04609564538015543 # DATA/outputs/r5/preds/paddleocr_vl_1_6/leader/V1.score.json plain cer (1121/24319) | |
| LEADER_CLUTTER_NONEMPTY = 0 # DATA/outputs/r5/preds/paddleocr_vl_1_6/leader/synth_clutter_val.score.json | |
| G2_MARGIN = 0.0050 | |
| B_BOOT = 2000 | |
| SEED = 20261125 | |
| # ----------------------------------------------------------------------------- copied from CODE/src/linedet/det_eval.py | |
| def iou_matrix(a, b): | |
| a = np.asarray(a, dtype=np.float64).reshape(-1, 4) | |
| b = np.asarray(b, dtype=np.float64).reshape(-1, 4) | |
| ix0 = np.maximum(a[:, None, 0], b[None, :, 0]) | |
| iy0 = np.maximum(a[:, None, 1], b[None, :, 1]) | |
| ix1 = np.minimum(a[:, None, 2], b[None, :, 2]) | |
| iy1 = np.minimum(a[:, None, 3], b[None, :, 3]) | |
| inter = np.clip(ix1 - ix0, 0, None) * np.clip(iy1 - iy0, 0, None) | |
| aa = (a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]) | |
| bb = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1]) | |
| return inter / (aa[:, None] + bb[None, :] - inter + 1e-9) | |
| def match_count(pred, scores, gt, thr): | |
| """Greedy one-to-one matching by descending score; returns the number of true positives.""" | |
| if len(pred) == 0 or len(gt) == 0: | |
| return 0 | |
| order = np.argsort(-np.asarray(scores)) | |
| M = iou_matrix(np.asarray(pred)[order], gt) | |
| used = np.zeros(len(gt), dtype=bool) | |
| tp = 0 | |
| for i in range(M.shape[0]): | |
| row = np.where(used, -1.0, M[i]) | |
| j = int(row.argmax()) | |
| if row[j] >= thr: | |
| used[j] = True | |
| tp += 1 | |
| return tp | |
| def page_cers(hyp_lines, ref_lines): | |
| from rapidfuzz import process | |
| from rapidfuzz.distance import Levenshtein | |
| from scipy.optimize import linear_sum_assignment | |
| nref = sum(len(r) for r in ref_lines) | |
| ro = Levenshtein.distance(" ".join(hyp_lines), " ".join(ref_lines)) | |
| if not hyp_lines or not ref_lines: | |
| of = sum(len(h) for h in hyp_lines) + nref | |
| else: | |
| C = process.cdist(hyp_lines, ref_lines, scorer=Levenshtein.distance, dtype=np.int32) | |
| ri, ci = linear_sum_assignment(C) | |
| matched = int(C[ri, ci].sum()) | |
| un_h = sum(len(hyp_lines[i]) for i in range(len(hyp_lines)) if i not in set(ri.tolist())) | |
| un_r = sum(len(ref_lines[j]) for j in range(len(ref_lines)) if j not in set(ci.tolist())) | |
| of = matched + un_h + un_r | |
| return ro, of, nref | |
| # ----------------------------------------------------------------------------- end of copy | |
| def utc(): | |
| return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) | |
| def load_records(data_root, s, split="val", token=None): | |
| p = os.path.join(data_root, "records", s + ".jsonl") | |
| if split == "test": | |
| assert s in T.HELDOUT_SETS, s | |
| f = T.open_sealed(p, token, "score") | |
| else: | |
| T.guard_not_test(p) | |
| f = open(p, encoding="utf-8") | |
| out = {} | |
| with f: | |
| for line in f: | |
| r = json.loads(line) | |
| assert r["split"] == split | |
| out[r["id"]] = {k: r[k] for k in ("id", "kind", "lang", "page_type", "ref_lines", "boxes1280", "order", "w1280", "h1280", | |
| "gutter")} | |
| return out | |
| def read_jsonl_glob(pattern): | |
| out = {} | |
| for p in sorted(glob.glob(pattern)): | |
| with open(p, encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| r = json.loads(line) | |
| out[r["id"]] = r | |
| except (ValueError, KeyError): | |
| pass # blank line or a line torn by a hard kill (the writer re-reads that page on resume) | |
| return out | |
| def overlong_or_loop(hyp_text, ref_text): | |
| over = len(hyp_text) > 1.5 * len(ref_text) + 50 | |
| loop = False | |
| if len(hyp_text) >= 100: | |
| cnt = collections.Counter(hyp_text[i:i + 20] for i in range(0, len(hyp_text) - 19)) | |
| for sub, n in cnt.items(): | |
| if n >= 5 and ref_text.count(sub) < 5: | |
| loop = True | |
| break | |
| return over, loop | |
| def boot(rows, keys, B=B_BOOT, seed=SEED): | |
| """page bootstrap of micro ratios; rows: list of dicts with the numerator keys and 'nref'""" | |
| n = len(rows) | |
| if n < 2: | |
| return {} | |
| rng = np.random.default_rng(seed) | |
| idx = rng.integers(0, n, size=(B, n)) | |
| den = np.array([r["nref"] for r in rows], dtype=np.float64) | |
| out = {} | |
| for k in keys: | |
| num = np.array([r[k] for r in rows], dtype=np.float64) | |
| v = num[idx].sum(1) / np.maximum(den[idx].sum(1), 1) | |
| out[k] = [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] | |
| return out | |
| def boot_diff(rows_a, rows_b, key, B=B_BOOT, seed=SEED): | |
| ids = sorted(set(r["id"] for r in rows_a) & set(r["id"] for r in rows_b)) | |
| A = {r["id"]: r for r in rows_a} | |
| Bm = {r["id"]: r for r in rows_b} | |
| if len(ids) < 2: | |
| return None | |
| rng = np.random.default_rng(seed + 7) | |
| idx = rng.integers(0, len(ids), size=(B, len(ids))) | |
| den = np.array([A[i]["nref"] for i in ids], dtype=np.float64) | |
| na = np.array([A[i][key] for i in ids], dtype=np.float64) | |
| nb = np.array([Bm[i][key] for i in ids], dtype=np.float64) | |
| d = (na[idx].sum(1) - nb[idx].sum(1)) / np.maximum(den[idx].sum(1), 1) | |
| point = (na.sum() - nb.sum()) / max(den.sum(), 1) | |
| return {"point": float(point), "ci95": [float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))], "pages": len(ids)} | |
| def summarise(rows, has_boxes): | |
| tot = {k: sum(r[k] for r in rows) for k in ("ro", "of", "nref")} | |
| s = {"pages": len(rows), "reference_chars": tot["nref"], | |
| "M28": round(tot["ro"] / max(tot["nref"], 1), 6), "M29": round(tot["of"] / max(tot["nref"], 1), 6), | |
| "ci95": boot(rows, ["ro", "of"])} | |
| if rows and "ro_stored" in rows[0]: | |
| s["M28_stored_order"] = round(sum(r["ro_stored"] for r in rows) / max(tot["nref"], 1), 6) | |
| s["lines_out"] = sum(r["n_hyp"] for r in rows) | |
| s["lines_ref"] = sum(r["n_ref"] for r in rows) | |
| s["overlong_pages"] = sum(1 for r in rows if r["overlong"]) | |
| s["loop_pages"] = sum(1 for r in rows if r["loop"]) | |
| if has_boxes: | |
| for thr in ("0.50", "0.75"): | |
| tp = sum(r["tp" + thr] for r in rows) | |
| npred = sum(r["n_pred_det"] for r in rows) | |
| ngt = sum(r["n_gt"] for r in rows) | |
| P, R = tp / max(npred, 1), tp / max(ngt, 1) | |
| s["det_iou_" + thr] = {"tp": tp, "n_pred": npred, "n_gt": ngt, "precision": P, "recall": R, "f1": (2 * P * R / (P + R)) if P + R else 0.0} | |
| s["hit_cap_pages"] = sum(1 for r in rows if r.get("hit_cap")) | |
| s["malformed_instances"] = sum(r.get("malformed", 0) for r in rows) | |
| s["instances_without_box"] = sum(r.get("no_box", 0) for r in rows) | |
| by = collections.defaultdict(list) | |
| for r in rows: | |
| by["lang:" + r["lang"]].append(r) | |
| by["type:" + r["page_type"]].append(r) | |
| s["by_group"] = {g: {"pages": len(v), "M28": round(sum(x["ro"] for x in v) / max(sum(x["nref"] for x in v), 1), 6), | |
| "M29": round(sum(x["of"] for x in v) / max(sum(x["nref"] for x in v), 1), 6)} for g, v in sorted(by.items())} | |
| return s | |
| def page_row(rec, hyp, extra): | |
| refs_dec = [rec["ref_lines"][i] for i in rec["order"]] | |
| ro, of, nref = page_cers(hyp, refs_dec) | |
| row = {"id": rec["id"], "lang": rec["lang"], "page_type": rec["page_type"], "ro": ro, "of": of, "nref": nref, | |
| "n_hyp": len(hyp), "n_ref": len(refs_dec)} | |
| if rec["kind"] == "school": | |
| row["ro_stored"] = page_cers(hyp, rec["ref_lines"])[0] | |
| row["overlong"], row["loop"] = overlong_or_loop(" ".join(hyp), " ".join(refs_dec)) | |
| row.update(extra) | |
| return row | |
| def score_candidate(recs, preds): | |
| rows, missing = [], [] | |
| for pid, rec in recs.items(): | |
| p = preds.get(pid) | |
| if p is None: | |
| missing.append(pid) | |
| continue | |
| inst = T.parse_output(p["raw"]) | |
| hyp = T.page_lines(inst) | |
| boxes = T.boxes_to_frame(inst, rec["w1280"], rec["h1280"]) | |
| n_pred = len(inst) | |
| extra = {"n_pred_det": n_pred, "n_gt": len(rec["boxes1280"]), "hit_cap": bool(p.get("hit_cap")), | |
| "malformed": sum(1 for x in inst if x["malformed"]), "no_box": sum(1 for x in inst if x["box"] is None), | |
| "n_new": p.get("n_new")} | |
| for thr in (0.5, 0.75): | |
| extra["tp%.2f" % thr] = match_count(boxes, [1.0] * len(boxes), rec["boxes1280"], thr) | |
| rows.append(page_row(rec, hyp, extra)) | |
| return rows, missing | |
| def score_baseline(recs, preds, columns): | |
| rows, missing = [], [] | |
| for pid, rec in recs.items(): | |
| p = preds.get(pid) | |
| if p is None: | |
| missing.append(pid) | |
| continue | |
| boxes, rd = p["boxes"], p["readings"] | |
| order = T.det_order_columns(boxes, p["w1280"])[0] if columns else T.det_order(boxes) | |
| hyp = [rd[i] for i in order if rd[i]] | |
| rows.append(page_row(rec, hyp, {})) | |
| return rows, missing | |
| def crop_gate_values(crop_scores, arm, name): | |
| out = {} | |
| for s in ("V1", "synth_clutter_val"): | |
| p = os.path.join(crop_scores, arm, name, s + ".json") | |
| if not os.path.exists(p): | |
| out[s] = {"missing": p} | |
| continue | |
| d = json.load(open(p, encoding="utf-8")) | |
| m = d.get("profiles", {}).get("plain", {}).get("groups", {}).get("all", {}).get("metrics", {}) | |
| out[s] = {"path": p, "complete": d.get("coverage", {}).get("complete"), "rows": d.get("coverage", {}).get("scored_rows"), | |
| "cer": (m.get("cer") or {}).get("value"), "cer_ci95": [(m.get("cer") or {}).get("lo"), (m.get("cer") or {}).get("hi")], | |
| "hr1_num": (m.get("hr1") or {}).get("num"), "hr1_den": (m.get("hr1") or {}).get("den")} | |
| return out | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--name", default="final") | |
| ap.add_argument("--data-root", default=DATA + "/data/processed/r6_onemodel") | |
| ap.add_argument("--page-preds", default=DATA + "/outputs/r6_onemodel/page_preds") | |
| ap.add_argument("--baseline-dir", default=DATA + "/outputs/r6_onemodel/baseline/gpu") | |
| ap.add_argument("--crop-scores", default=DATA + "/outputs/r6_onemodel/scores") | |
| ap.add_argument("--arm", default="onemodel") | |
| ap.add_argument("--out", default=DATA + "/outputs/r6_onemodel/page_scores") | |
| ap.add_argument("--sets", default="gen_val,school_val") | |
| ap.add_argument("--baseline-only", action="store_true") | |
| ap.add_argument("--smoke-repro", action="store_true") | |
| ap.add_argument("--smoke-pages", type=int, default=5) | |
| ap.add_argument("--heldout-root", default=DATA + "/data/processed/r6_loopguard") | |
| ap.add_argument("--sealed-token", default=T.OFFICIAL_UNSEAL) | |
| ap.add_argument("--fallback-flags", default="") | |
| ap.add_argument("--crop-name", default="") | |
| ap.add_argument("--tag", default="") | |
| ap.add_argument("--exclude-ids", default="") | |
| a = ap.parse_args() | |
| sets = [s for s in a.sets.split(",") if s] | |
| if os.path.realpath(a.out).startswith(os.path.realpath(DATA + "/outputs/r6_onemodel")): | |
| raise SystemExit("REFUSED: the LOOPGUARD copy of om_score never writes under outputs/r6_onemodel (pass --out)") | |
| for s in sets: # refuse held-out sets before anything is opened or written | |
| if s in T.HELDOUT_SETS: | |
| T.check_unsealed(a.sealed_token, "score") | |
| os.makedirs(a.out, exist_ok=True) | |
| if a.smoke_repro: | |
| return smoke_repro(a) | |
| flags = json.load(open(a.fallback_flags, encoding="utf-8")) if a.fallback_flags else None | |
| res = {"design": T.DESIGN_ID, "name": a.name, "created_utc": utc(), "baseline_dir": a.baseline_dir, "sets": {}} | |
| if flags is not None: | |
| res["fallback_flags"] = {"file": a.fallback_flags, "pages": {s: len(v) for s, v in flags.items() if isinstance(v, list)}} | |
| excl = json.load(open(a.exclude_ids, encoding="utf-8")) if a.exclude_ids else None | |
| if excl is not None: | |
| res["excluded_pages"] = {"file": a.exclude_ids, "ids": {s: v for s, v in excl.items() if isinstance(v, list)}} | |
| per_page = {} | |
| for s in sets: | |
| held = s in T.HELDOUT_SETS | |
| recs = load_records(a.heldout_root if held else a.data_root, s, "test" if held else "val", a.sealed_token) | |
| if excl is not None and isinstance(excl.get(s), list): | |
| drop = set(excl[s]) | |
| assert drop <= set(recs), "an excluded id is not a page of %s" % s | |
| recs = {k: v for k, v in recs.items() if k not in drop} | |
| cell = {} | |
| base = read_jsonl_glob(os.path.join(a.baseline_dir, s + "*.jsonl")) | |
| # amendment A1 (design.json): the comparator orders its lines with the same construction as the set's reference - | |
| # School: det_eval key + the R_SCHOOL gutter split (the School reference is gutter-split); generated: the plain | |
| # det_eval key (the generator's reference order is never gutter-split). The other variant is reported, descriptive. | |
| cols = s in ("school_val", "school_test") | |
| b_rows, b_miss = score_baseline(recs, base, columns=cols) | |
| b2_rows, _ = score_baseline(recs, base, columns=not cols) | |
| cell["baseline"] = dict(summarise(b_rows, False), missing_pages=len(b_miss), complete=not b_miss, | |
| order="det_eval key + gutter split" if cols else "det_eval key") | |
| cell["baseline_other_order_descriptive"] = dict(summarise(b2_rows, False), | |
| order="det_eval key" if cols else "det_eval key + gutter split") | |
| per_page[s + "/baseline"] = b_rows | |
| if not a.baseline_only: | |
| cand = read_jsonl_glob(os.path.join(a.page_preds, a.name, s + ".jsonl")) | |
| c_rows, c_miss = score_candidate(recs, cand) | |
| has_boxes = True | |
| if flags is not None: | |
| fl = set(flags.get(s, [])) | |
| bmap = {r["id"]: r for r in b_rows} | |
| switched = [r["id"] for r in c_rows if r["id"] in fl and r["id"] in bmap] | |
| assert len(switched) == len(fl & {r["id"] for r in c_rows}), "a flagged page has no baseline row" | |
| c_rows = [dict(bmap[r["id"]], fallback=True) if r["id"] in fl else r for r in c_rows] | |
| cell["fallback_pages"] = sorted(switched) | |
| has_boxes = False | |
| cell["candidate"] = dict(summarise(c_rows, has_boxes), missing_pages=len(c_miss), complete=not c_miss) | |
| cell["paired_candidate_minus_baseline"] = {"M28": boot_diff(c_rows, b_rows, "ro"), "M29": boot_diff(c_rows, b_rows, "of")} | |
| per_page[s + "/candidate"] = c_rows | |
| res["sets"][s] = cell | |
| if not a.baseline_only: | |
| for who, nm in (("candidate", a.name), ("leader", "leader")): | |
| cs = read_jsonl_glob(os.path.join(a.page_preds, nm, "clutter_spot.jsonl")) | |
| if cs: | |
| nonempty = sum(1 for r in cs.values() if T.page_lines(T.parse_output(r["raw"]))) | |
| res.setdefault("clutter_spotting_mode_descriptive", {})[who] = {"images": len(cs), "nonempty_page_text": nonempty, | |
| "hit_cap": sum(1 for r in cs.values() if r.get("hit_cap"))} | |
| res["crop"] = crop_gate_values(a.crop_scores, a.arm, a.crop_name or a.name) | |
| g = {} | |
| ok_pages = all(res["sets"][s].get("candidate", {}).get("complete") and res["sets"][s]["baseline"]["complete"] for s in sets) | |
| g1 = {} | |
| for s in sets: | |
| c, b = res["sets"][s]["candidate"], res["sets"][s]["baseline"] | |
| g1[s] = {"M28_candidate": c["M28"], "M28_baseline": b["M28"], "M29_candidate": c["M29"], "M29_baseline": b["M29"], | |
| "pass": round(c["M28"], 4) <= round(b["M28"], 4) and round(c["M29"], 4) <= round(b["M29"], 4)} | |
| g["G1_page_cer"] = {"per_set": g1, "inputs_complete": ok_pages, "pass": ok_pages and all(v["pass"] for v in g1.values())} | |
| v1 = res["crop"].get("V1", {}) | |
| g["G2_crop_cer_V1"] = {"candidate": v1.get("cer"), "leader": LEADER_V1_CER, "limit": LEADER_V1_CER + G2_MARGIN, | |
| "complete": v1.get("complete"), | |
| "pass": bool(v1.get("complete")) and v1.get("cer") is not None and v1["cer"] <= LEADER_V1_CER + G2_MARGIN} | |
| cl = res["crop"].get("synth_clutter_val", {}) | |
| g["G3_clutter_nonempty"] = {"candidate": cl.get("hr1_num"), "of": cl.get("hr1_den"), "leader": LEADER_CLUTTER_NONEMPTY, | |
| "complete": cl.get("complete"), | |
| "pass": bool(cl.get("complete")) and cl.get("hr1_num") is not None and cl["hr1_num"] <= LEADER_CLUTTER_NONEMPTY} | |
| res["gates"] = g | |
| res["release_candidate"] = all(v["pass"] for v in g.values()) | |
| res["decision_applies"] = a.name == "final" or a.name.endswith("_final") # run_gpu.sh names it <run>_final | |
| tag = (a.tag or a.name) if not a.baseline_only else "baseline_" + (a.tag or os.path.basename(a.baseline_dir.rstrip("/"))) | |
| json.dump(res, open(os.path.join(a.out, "page_scores_%s.json" % tag), "w"), indent=1, ensure_ascii=False) | |
| with open(os.path.join(a.out, "per_page_%s.jsonl" % tag), "w", encoding="utf-8") as f: | |
| for k, rows in per_page.items(): | |
| for r in rows: | |
| f.write(json.dumps(dict(r, cell=k), ensure_ascii=False) + "\n") | |
| brief = {s: {k: {m: v.get(m) for m in ("M28", "M29", "M28_stored_order", "pages")} for k, v in c.items() if isinstance(v, dict) and "M28" in v} | |
| for s, c in res["sets"].items()} | |
| print(json.dumps({"sets": brief, "gates": res.get("gates"), "release_candidate": res.get("release_candidate")}, indent=1)) | |
| return 0 | |
| def smoke_repro(a): | |
| """(1) per-page: this file's page_cers == linedet.det_eval.page_cers on the stored A1 long outputs for N pages of each set; | |
| (2) whole sets: the stored det_eval end_to_end figures are reproduced from the stored per-page outputs.""" | |
| # det_eval.page_cers is taken from the source file itself (ast), not by importing the module: det_eval imports cv2 at the | |
| # top, and cv2 needs libGL.so.1, which some ZEN4 nodes lack (one node, 25 Nov 2026) | |
| import ast | |
| import types | |
| src = open(CODE + "/src/linedet/det_eval.py", encoding="utf-8").read() | |
| fn = [n for n in ast.parse(src).body if isinstance(n, ast.FunctionDef) and n.name == "page_cers"][0] | |
| ns = {"np": np} | |
| exec(compile(ast.Module(body=[fn], type_ignores=[]), CODE + "/src/linedet/det_eval.py", "exec"), ns) | |
| DE = types.SimpleNamespace(page_cers=ns["page_cers"]) | |
| import csv | |
| csv.field_size_limit(10 ** 9) | |
| out = {"created_utc": utc(), "per_page": [], "whole_set": {}} | |
| for s, tsv in (("gen", DATA + "/data/processed/r5_linedet_det/gen/pages_gen_val.tsv"), | |
| ("school", DATA + "/data/processed/r5_linedet_det/school2/pages_school_val.tsv")): | |
| refs = {} | |
| with open(tsv, encoding="utf-8", newline="") as f: | |
| for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): | |
| refs[r["id"]] = json.loads(r["ref_lines_json"]) if r.get("ref_lines_json") else [] | |
| stored = read_jsonl_glob(DATA + "/outputs/r5/linedet/det_eval/e2e_yolo_s2_%s_val_A1_long_pages.jsonl" % s) | |
| summ = json.load(open(DATA + "/outputs/r5/linedet/det_eval/e2e_yolo_s2_%s_val_A1_long.json" % s))["end_to_end"] | |
| ro = of = n = 0 | |
| for k, (pid, r) in enumerate(stored.items()): | |
| mine = page_cers(r["hyp_lines"], refs[pid]) | |
| if k < a.smoke_pages: | |
| theirs = DE.page_cers(r["hyp_lines"], refs[pid]) | |
| out["per_page"].append({"set": s, "id": pid, "mine": list(mine), "det_eval": list(theirs), "equal": tuple(mine) == tuple(theirs)}) | |
| ro, of, n = ro + mine[0], of + mine[1], n + mine[2] | |
| out["whole_set"][s] = {"pages": len(stored), "reading_order_page_cer": ro / max(n, 1), "order_free_page_cer": of / max(n, 1), | |
| "reference_chars": n, "stored": summ, | |
| "equal": abs(ro / n - summ["reading_order_page_cer"]) < 1e-12 and abs(of / n - summ["order_free_page_cer"]) < 1e-12 | |
| and n == summ["reference_chars"]} | |
| out["passed"] = all(x["equal"] for x in out["per_page"]) and all(v["equal"] for v in out["whole_set"].values()) | |
| json.dump(out, open(os.path.join(a.out, "smoke_repro.json"), "w"), indent=1, ensure_ascii=False) | |
| print(json.dumps({"passed": out["passed"], "whole_set": {k: {m: v[m] for m in ("reading_order_page_cer", "order_free_page_cer", "equal")} | |
| for k, v in out["whole_set"].items()}}, indent=1)) | |
| return 0 if out["passed"] else 2 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |