"""Self-contained scorer for nutrientdocs/form-field-vlm-benchmark. Predictions are a JSON list of {page_id, box:[x,y,w,h], type, label?, group_id?} in original pixels. No checkout of the training repository is required. """ from __future__ import annotations import argparse import json from collections import Counter from pathlib import Path def iou(a, b): x0, y0 = max(a[0], b[0]), max(a[1], b[1]) x1, y1 = min(a[0] + a[2], b[0] + b[2]), min(a[1] + a[3], b[1] + b[3]) inter = max(0.0, x1 - x0) * max(0.0, y1 - y0) union = a[2] * a[3] + b[2] * b[3] - inter return inter / union if union else 0.0 def match(preds, golds, threshold): pb, gb = {}, {} for p in preds: pb.setdefault(p["page_id"], []).append(p) for g in golds: gb.setdefault(g["page_id"], []).append(g) matched, unp, ung = [], [], [] for page_id in sorted(set(pb) | set(gb)): ps, gs, candidates = pb.get(page_id, []), gb.get(page_id, []), [] for pi, p in enumerate(ps): for gi, g in enumerate(gs): overlap = iou(p["box"], g["box"]) if overlap >= threshold: candidates.append((overlap, pi, gi)) candidates.sort(key=lambda row: (-row[0], row[1], row[2])) used_p, used_g = set(), set() for overlap, pi, gi in candidates: if pi not in used_p and gi not in used_g: used_p.add(pi); used_g.add(gi); matched.append((ps[pi], gs[gi], overlap)) unp.extend(p for i, p in enumerate(ps) if i not in used_p) ung.extend(g for i, g in enumerate(gs) if i not in used_g) return matched, unp, ung def metric(matched, unp, ung, page_ids): n_pred, n_gold = len(matched) + len(unp), len(matched) + len(ung) correct = sum(p.get("type") == g.get("type") for p, g, _ in matched) precision = correct / n_pred if n_pred else 0.0 recall = correct / n_gold if n_gold else 0.0 f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 pc, gc = Counter(), Counter() for p, g, _ in matched: pc[p["page_id"]] += 1; gc[g["page_id"]] += 1 for p in unp: pc[p["page_id"]] += 1 for g in ung: gc[g["page_id"]] += 1 mae = sum(abs(pc[p] - gc[p]) for p in page_ids) / len(page_ids) if page_ids else 0.0 return {"correct": correct, "precision": precision, "recall": recall, "f1": f1, "n_pred": n_pred, "n_gold": n_gold, "fp_per_page": len(unp) / len(page_ids) if page_ids else 0.0, "count_mae": mae} def score_slice(matched, unp, ung, page_ids, predicate): return metric([m for m in matched if predicate(m[1])], [p for p in unp if predicate(p)], [g for g in ung if predicate(g)], page_ids) def score(preds, golds, page_ids, threshold): matched, unp, ung = match(preds, golds, threshold) gold_counts = Counter(g["page_id"] for g in golds) edges = ((1, 5), (6, 15), (16, 40), (41, 10**9)) density = lambda pid: next((f"{lo}-{hi}" if hi < 10**9 else f"{lo}+" for lo, hi in edges if lo <= gold_counts[pid] <= hi), "0") types = sorted({g["type"] for g in golds}) labels = [f"{lo}-{hi}" if hi < 10**9 else f"{lo}+" for lo, hi in edges] by_type = {t: score_slice(matched, unp, ung, page_ids, lambda x, t=t: x.get("type") == t) for t in types} by_density = {d: score_slice(matched, unp, ung, page_ids, lambda x, d=d: density(x["page_id"]) == d) for d in labels} by_type_density = {t: {d: score_slice(matched, unp, ung, page_ids, lambda x, t=t, d=d: x.get("type") == t and density(x["page_id"]) == d) for d in labels} for t in types} n_match = len(matched) label_hits = sum(str(p.get("label") or "").strip().casefold() == str(g.get("label") or "").strip().casefold() for p, g, _ in matched) group_pairs = [(p, g) for p, g, _ in matched if g.get("group_id") is not None] group_hits = sum(p.get("group_id") == g.get("group_id") for p, g in group_pairs) box_precision = n_match / len(preds) if preds else 0.0 box_recall = n_match / len(golds) if golds else 0.0 return {"overall": metric(matched, unp, ung, page_ids), "by_type": by_type, "by_density": by_density, "by_type_density": by_type_density, "box_precision": box_precision, "box_recall": box_recall, "box_f1": 2 * box_precision * box_recall / (box_precision + box_recall) if box_precision + box_recall else 0.0, "matched_label_exact": label_hits / n_match if n_match else None, "matched_radio_group_exact": group_hits / len(group_pairs) if group_pairs else None, "n_matched_radio_widgets": len(group_pairs)} def load_benchmark(repo, local): from datasets import load_dataset, load_from_disk if local: loaded = load_from_disk(local) return loaded["test"] if hasattr(loaded, "keys") else loaded return load_dataset(repo, split="test") def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--benchmark-repo", default="nutrientdocs/form-field-vlm-benchmark") ap.add_argument("--benchmark", help="optional local datasets.save_to_disk directory") ap.add_argument("--predictions", required=True) ap.add_argument("--out", default="result.json") args = ap.parse_args() ds = load_benchmark(args.benchmark_repo, args.benchmark) page_ids, golds = [], [] for row in ds: page_ids.append(row["page_id"]) for field in row["fields"]: golds.append({"page_id": row["page_id"], "box": list(field["box"]), "type": field["type"], "label": field.get("label"), "group_id": field.get("group_id")}) preds = json.loads(Path(args.predictions).read_text(encoding="utf-8")) required = {"page_id", "box", "type"} if not isinstance(preds, list) or any(not isinstance(p, dict) or not required <= p.keys() for p in preds): raise SystemExit("predictions must be a JSON list with page_id, box, and type on every item") report = {"benchmark": args.benchmark_repo, "n_pages": len(page_ids), "n_gold": len(golds), "headline": "field-level exact F1 at IoU 0.5", "by_iou": {str(t): score(preds, golds, page_ids, t) for t in (0.5, 0.2)}} Path(args.out).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(f"F1@0.5={report['by_iou']['0.5']['overall']['f1']:.3f} " f"F1@0.2={report['by_iou']['0.2']['overall']['f1']:.3f} -> {args.out}") if __name__ == "__main__": main()