File size: 2,832 Bytes
64563dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""Reference scorer for form-field-v1-benchmark — COCO mAP50-95 (pycocotools), per-variant + per-class.

Predictions: a JSON list of {"image_id": <page_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()