"""Reference scorer for form-field-v1-benchmark — COCO mAP50-95 (pycocotools), per-variant + per-class. Predictions: a JSON list of {"image_id": , "category_id": 1|2|3, "score": float, "bbox": [x,y,w,h]} (category 1=Text, 2=ChoiceButton, 3=Signature; bbox in page pixels). pip install datasets pycocotools python score_detector.py preds.json # overall + per variant + per class """ import sys, json, contextlib, io from datasets import load_dataset from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval CATS = [(1, "Text"), (2, "ChoiceButton"), (3, "Signature")] CAT_ID = {"Text": 1, "ChoiceButton": 2, "Signature": 3} def build_gt(split_rows): images, anns, aid = [], [], 1 idmap = {} for i, r in enumerate(split_rows): idmap[r["page_id"]] = i images.append({"id": i, "file_name": r["page_id"], "width": r["width"], "height": r["height"], "variant": r["variant"]}) for f in r["fields"]: x, y, w, h = f["box"] anns.append({"id": aid, "image_id": i, "category_id": CAT_ID[f["category"]], "bbox": [x, y, w, h], "area": w * h, "iscrowd": 0}); aid += 1 coco = COCO(); coco.dataset = {"images": images, "categories": [{"id": c, "name": n} for c, n in CATS], "annotations": anns} with contextlib.redirect_stdout(io.StringIO()): coco.createIndex() return coco, idmap def score(coco, dets, tag): with contextlib.redirect_stdout(io.StringIO()): dt = coco.loadRes(dets) ev = COCOeval(coco, dt, "bbox"); ev.params.maxDets = [1, 100, 1000] ev.evaluate(); ev.accumulate(); ev.summarize() per = [] for cid, nm in CATS: with contextlib.redirect_stdout(io.StringIO()): e = COCOeval(coco, dt, "bbox"); e.params.maxDets = [1, 100, 1000]; e.params.catIds = [cid] e.evaluate(); e.accumulate(); e.summarize() per.append(f"{nm} {e.stats[0]:.3f}") print(f"{tag:14s} mAP50-95={ev.stats[0]:.4f} AP50={ev.stats[1]:.4f} ({' / '.join(per)})") def main(): preds = json.load(open(sys.argv[1])) rows = list(load_dataset("nutrientdocs/form-field-v1-benchmark", split="test")) # map page_id (string image_id in preds) -> integer id used by the GT coco_all, idmap = build_gt(rows) dets = [{**d, "image_id": idmap[d["image_id"]]} for d in preds if d["image_id"] in idmap] score(coco_all, dets, "OVERALL") for variant in ("empty", "filled", "handwritten"): sub = [r for r in rows if r["variant"] == variant] coco_v, idm_v = build_gt(sub) dv = [{**d, "image_id": idm_v[d["image_id"]]} for d in preds if d["image_id"] in idm_v] score(coco_v, dv, variant) if __name__ == "__main__": main()