"""Failure mining: after every scored benchmark run, collect the pages the model gets wrong, say why, and write a brief the synthetic-data team can generate from. python -m common.failure_mining mine --subset g_dev_ar --tag F1_focus [--base base] python -m common.failure_mining summarize # all runs mined so far -> one brief Runs automatically at the end of `python -m common.mdpbench score/run`. Per page it records: score (and the base model's, if given), the official per-part edit distances (text blocks, tables, reading order, formulas), output and label lengths, and failure types: loop output hit the token limit or repeats a chunk many times table table edit distance > 0.3 (structure or cell order) reading_order reading-order edit distance > 0.2 formula formula edit distance > 0.3 text text-block edit distance > 0.1 missing_text output under 60% of the label's length (no loop) extra_text output over 150% of the label's length (no loop): invented or duplicated text diacritics (Arabic) errors mostly in diacritic marks: CER drops by half once marks are removed dots (Arabic) letters confused by their dots: CER drops by half once letters are reduced to their undotted skeleton (rasm), e.g. ر/ز, ت/ث/ن, ج/ح/خ regression page score more than 5 points below the base model A page is a failure if its score is below --min-score (default 0.85) or it has any flag. Outputs in /failures///: failures.jsonl (one row per failed page: image path, label, output, scores, flags, language, document type, capture conditions), images/ (copies), report.md (counts by type, language, document type and capture; worst examples) and brief.md (what to generate, with counts and example ids). Every row also goes to /failures/bank.jsonl. Use policy: pages from benchmark subsets are evaluation data. Their failures may be described to the data team (pattern, layout, script, capture conditions) but the images and labels must never enter training; pages of the final-test subset are marked use="describe-only". Synthetic pages may be used freely. """ import argparse import json import re import shutil import statistics as st from collections import Counter, defaultdict from pathlib import Path from .paths import WORK_DIR MARKS = re.compile("[ً-ْٰـ]") # harakat, superscript alef, tatweel RASM = str.maketrans({c: k for k, cs in { "ب": "بتثنيىئ", "ج": "جحخ", "د": "دذ", "ر": "رز", "س": "سش", "ص": "صض", "ط": "طظ", "ع": "عغ", "ف": "فق", "ه": "هة", "ا": "اأإآ"}.items() for c in cs}) TEST_SUBSETS = {"t_aez", "g_test", "q_test", "f_test"} PARTS = ["text_block", "table", "reading_order", "display_formula"] LIMITS = {"table": 0.3, "reading_order": 0.2, "display_formula": 0.3, "text_block": 0.1} FLAG_OF = {"table": "table", "reading_order": "reading_order", "display_formula": "formula", "text_block": "text"} def _cer(a, b): import Levenshtein return Levenshtein.distance(a, b) / max(1, len(b)) def strip_marks(s): return MARKS.sub("", s) def rasm(s): """Arabic letters reduced to their undotted skeleton (dots no longer distinguish letters).""" return strip_marks(s).translate(RASM) def arabic_flags(pred, gt): """'diacritics' / 'dots' when most of the character error disappears once marks / dots are ignored.""" flags = [] c = _cer(pred, gt) if c < 0.02: return flags c_nomark = _cer(strip_marks(pred), strip_marks(gt)) if c_nomark < 0.5 * c: flags.append("diacritics") c_rasm = _cer(rasm(pred), rasm(gt)) if c_rasm < 0.5 * c_nomark and c_nomark > 0.01: flags.append("dots") return flags def page_text(gt_page): """Label text of one benchmark page (reading order; headers / footers / page numbers left out).""" dets = [d for d in gt_page["layout_dets"] if d.get("order") is not None] dets.sort(key=lambda d: d["order"]) return "\n\n".join((d.get("text") or d.get("html") or d.get("latex") or "").strip() for d in dets).strip() def describe_id(pid): """language, document type and capture conditions from an MDPBench-style id (ar_book_11_indoor_light_...).""" parts = pid.split("_") lang = parts[0] if len(parts) > 1 and parts[1] == "synth": return lang, "_".join(parts[2:-2]) or "synthetic", "synthetic" doc = parts[1] if len(parts) > 1 else "?" capture = "digital" if len(parts) == 3 else "photo:" + "_".join(parts[3:]) return lang, doc, capture def load_run(subset, tag): from .mdpbench import BENCH_DIR, run_dir d = run_dir(subset, tag) pages = json.loads((d / "pages.json").read_text(encoding="utf-8")) res = d / "score" / "result" / "md_result" parts = {} for p in PARTS: f = res / f"md_result_{p}_All_per_page_edit.json" parts[p] = json.loads(f.read_text()) if f.exists() else {} preds = {} for line in open(d / "predictions.jsonl", encoding="utf-8"): r = json.loads(line) preds[r["id"]] = r sub = BENCH_DIR / "subsets" / subset items = {json.loads(l)["id"]: json.loads(l) for l in open(sub / "items.jsonl", encoding="utf-8")} gts = {g["page_info"]["image_path"].rsplit(".", 1)[0]: g for g in json.load(open(sub / "gt.json", encoding="utf-8"))} return pages, parts, preds, items, gts def mine(subset, tag, base=None, min_score=0.85, out_root=None, copy_images=True): from .mdpbench import has_loop, run_dir pages, parts, preds, items, gts = load_run(subset, tag) bpages = {} if base and base != tag and (run_dir(subset, base) / "pages.json").exists(): bpages = json.loads((run_dir(subset, base) / "pages.json").read_text(encoding="utf-8")) out = Path(out_root or WORK_DIR / "failures") / subset / tag if out.exists(): shutil.rmtree(out) (out / "images").mkdir(parents=True) use = "describe-only" if subset in TEST_SUBSETS else ("free" if subset.startswith("synth") else "describe-only (dev)") rows = [] for pid, score in pages.items(): pr = preds.get(pid, {}) pred = pr.get("pred") or "" gt = page_text(gts[pid]) if pid in gts else "" flags = [] if pr.get("truncated") or has_loop(pred): flags.append("loop") for p, lim in LIMITS.items(): v = parts[p].get(pid) if isinstance(v, (int, float)) and v > lim: flags.append(FLAG_OF[p]) if "loop" not in flags and gt: ratio = len(pred) / max(1, len(gt)) if ratio < 0.6: flags.append("missing_text") elif ratio > 1.5: flags.append("extra_text") lang, doc, capture = describe_id(pid) if lang == "ar" and gt and "loop" not in flags: flags += arabic_flags(re.sub(r"<[^>]+>", " ", pred), re.sub(r"<[^>]+>", " ", gt)) b = bpages.get(pid) if b is not None and score < b - 0.05: flags.append("regression") if score >= min_score and not flags: continue img = items.get(pid, {}).get("image") local = None if copy_images and img and Path(img).exists(): local = out / "images" / Path(img).name shutil.copy(img, local) rows.append({"subset": subset, "tag": tag, "id": pid, "language": lang, "doc_type": doc, "capture": capture, "score": round(score, 4), "base_score": None if b is None else round(b, 4), "flags": flags, "parts": {p: parts[p].get(pid) for p in PARTS if parts[p].get(pid) is not None}, "pred_chars": len(pred), "label_chars": len(gt), "out_tokens": pr.get("out_tokens"), "image": img, "image_copy": str(local) if local else None, "use": use, "label": gt[:4000], "output": pred[:4000]}) rows.sort(key=lambda r: r["score"]) with open(out / "failures.jsonl", "w", encoding="utf-8") as fh: for r in rows: fh.write(json.dumps(r, ensure_ascii=False) + "\n") bank = Path(out_root or WORK_DIR / "failures") / "bank.jsonl" with open(bank, "a", encoding="utf-8") as fh: for r in rows: fh.write(json.dumps({k: v for k, v in r.items() if k not in ("label", "output")}, ensure_ascii=False) + "\n") (out / "report.md").write_text(report(rows, len(pages), subset, tag, base), encoding="utf-8") (out / "brief.md").write_text(brief(rows, f"{subset} / {tag}"), encoding="utf-8") print(f"failure mining: {len(rows)} of {len(pages)} pages failed -> {out}") return rows def report(rows, n_pages, subset, tag, base): by_flag = Counter(f for r in rows for f in r["flags"]) lines = [f"# Failures: {subset} / {tag}", "", f"{len(rows)} of {n_pages} pages failed (score below threshold or a failure flag)." + (f" Compared with `{base}` for regressions." if base else ""), "", "## By failure type", "", "| type | pages |", "|---|---|"] lines += [f"| {f} | {n} |" for f, n in by_flag.most_common()] for key in ("language", "doc_type", "capture"): c = Counter(r[key] if key != "capture" else r[key].split(":")[0] for r in rows) lines += ["", f"## By {key.replace('_', ' ')}", "", "| value | pages |", "|---|---|"] lines += [f"| {k} | {n} |" for k, n in c.most_common()] lines += ["", "## Worst pages", "", "| page | score | base | flags | text / table / order |", "|---|---|---|---|---|"] for r in rows[:25]: p = r["parts"] lines.append(f"| {r['id']} | {100 * r['score']:.1f} | {'' if r['base_score'] is None else round(100 * r['base_score'], 1)} | " f"{', '.join(r['flags'])} | {p.get('text_block', '-')!s:.5} / {p.get('table', '-')!s:.5} / " f"{p.get('reading_order', '-')!s:.5} |") return "\n".join(lines) + "\n" GENERATE = { "loop": "long, dense pages (classical, fully diacritised text; long tables; newspapers) where the model must keep " "going and then stop: correct end-of-page behaviour", "table": "tables like the failing ones: same script and direction, merged header cells (rowspan / colspan), " "numeric columns, captions inside the table; labels in visual left-to-right cell order", "reading_order": "multi-column layouts, side boxes, footnotes and captions placed like the failing pages", "formula": "display formulas mixed into running text", "text": "running text in the same script, font sizes and density", "missing_text": "pages whose content the model skips: small or faint text, marginal notes, text over images", "extra_text": "pages where the model invents or repeats content: sparse pages, repeated headers, watermarks", "diacritics": "fully diacritised Arabic (Quran, hadith, poetry, dictionaries) at the same size and capture quality", "dots": "dense Arabic where dots decide the letter (ر/ز, ت/ث/ن, ج/ح/خ), small fonts, mild blur and JPEG", "regression": "the pages where the trained model became worse than the base: generate their type to protect it", } def brief(rows, scope): lines = [f"# Synthetic data brief ({scope})", "", "What to generate so the next training round covers these failures. Counts are failing pages. " "Evaluation pages are described, never copied: do not render the benchmark's own text or images.", ""] groups = defaultdict(list) for r in rows: for f in r["flags"] or ["low_score"]: groups[f].append(r) for f, rs in sorted(groups.items(), key=lambda x: -len(x[1])): langs = Counter(r["language"] for r in rs).most_common() docs = Counter(r["doc_type"] for r in rs).most_common(4) caps = Counter(r["capture"].split(":")[0] for r in rs).most_common() photo = Counter(c for r in rs if r["capture"].startswith("photo:") for c in r["capture"][6:].split("_")).most_common(5) lines += [f"## {f}: {len(rs)} pages", "", f"- Generate: {GENERATE.get(f, 'pages like these')}", f"- Languages: {', '.join(f'{k} {n}' for k, n in langs)}", f"- Document types: {', '.join(f'{k} {n}' for k, n in docs)}", f"- Capture: {', '.join(f'{k} {n}' for k, n in caps)}" + (f"; photo conditions: {', '.join(f'{k} {n}' for k, n in photo)}" if photo else ""), f"- Examples: {', '.join(r['id'] for r in rs[:6])}", f"- Use: {', '.join(sorted({r['use'] for r in rs}))}", ""] return "\n".join(lines) def summarize(out_root=None): root = Path(out_root or WORK_DIR / "failures") pages, runs = {}, 0 for f in sorted(root.glob("*/*/failures.jsonl")): runs += 1 for line in open(f, encoding="utf-8"): r = json.loads(line) key = (r["subset"], r["id"]) if key in pages: # one row per page: failure types merged over every run it failed in p = pages[key] p["flags"] = sorted(set(p["flags"]) | set(r["flags"])) p["failed_in"].append(r["tag"]) else: pages[key] = {**r, "failed_in": [r["tag"]]} rows = sorted(pages.values(), key=lambda r: -len(r["failed_in"])) with open(root / "pages_all.jsonl", "w", encoding="utf-8") as fh: for r in rows: fh.write(json.dumps({k: v for k, v in r.items() if k not in ("label", "output")}, ensure_ascii=False) + "\n") (root / "BRIEF_ALL.md").write_text(brief(rows, f"{len(rows)} unique failed pages over {runs} runs"), encoding="utf-8") print(f"{len(rows)} unique failed pages over {runs} runs -> {root / 'BRIEF_ALL.md'}") def main(argv=None): import sys for stream in (sys.stdout, sys.stderr): # Arabic examples in the help text: Windows consoles default to cp1252 try: stream.reconfigure(encoding="utf-8") except (AttributeError, ValueError): pass ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="cmd", required=True) m = sub.add_parser("mine") m.add_argument("--subset", required=True) m.add_argument("--tag", required=True) m.add_argument("--base", default="base", help="run to compare with for regressions ('' = none)") m.add_argument("--min-score", type=float, default=0.85) m.add_argument("--no-images", action="store_true") sub.add_parser("summarize") a = ap.parse_args(argv) if a.cmd == "mine": mine(a.subset, a.tag, a.base or None, a.min_score, copy_images=not a.no_images) else: summarize() if __name__ == "__main__": main()