File size: 3,611 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""LOOPGUARD-1 prep: the held-out detector boxes are made on CPU with tp2_tob_detect.py (det_eval settings); validation boxes
came from det_eval on a GPU. Before the held-out boxes are accepted, the same CPU run on the first N validation pages of each
set must give the stored det_eval boxes.

Criterion (fixed before the run, as test pass 2 smoke_compare.json): per page the same number of boxes, and every CPU box
matched one-to-one (greedy by IoU) to a stored box with IoU >= 0.9. Also reported: pages with identical box lists (after the
same 0.1-px rounding) and the largest coordinate difference of matched boxes. Pass = every page passes.

usage: lg_box_check.py --cpu gen_val=JSONL,school_val=JSONL --stored gen_val=JSONL,school_val=JSONL --n 20 --out JSON
"""
import argparse
import json

import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("--cpu", required=True)
ap.add_argument("--stored", required=True)
ap.add_argument("--n", type=int, default=20)
ap.add_argument("--iou", type=float, default=0.9)
ap.add_argument("--out", required=True)
a = ap.parse_args()


def load(p):
    out = {}
    with open(p, encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            out[r["id"]] = r["boxes"]
    return out


def iou(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)


cpu = dict(x.split("=", 1) for x in a.cpu.split(","))
sto = dict(x.split("=", 1) for x in a.stored.split(","))
rep = {"criterion": "same count and every CPU box matched one-to-one at IoU >= %.2f" % a.iou, "sets": {}}
allok = True
for s in cpu:
    C, S = load(cpu[s]), load(sto[s])
    pages = []
    for pid in list(C)[:a.n]:
        c, g = C[pid], S.get(pid)
        if g is None:
            pages.append({"id": pid, "pass": False, "why": "no stored boxes"})
            allok = False
            continue
        matched, maxd = 0, 0.0
        if c and g:
            M = iou(c, g)
            used = np.zeros(len(g), dtype=bool)
            for i in np.argsort(-M.max(1)):
                row = np.where(used, -1.0, M[i])
                j = int(row.argmax())
                if row[j] >= a.iou:
                    used[j] = True
                    matched += 1
                    maxd = max(maxd, float(np.abs(np.asarray(c[i]) - np.asarray(g[j])).max()))
        ok = len(c) == len(g) and matched == len(c)
        allok &= ok
        pages.append({"id": pid, "cpu_boxes": len(c), "stored_boxes": len(g), "matched_iou": matched,
                      "identical": c == g, "max_abs_coord_diff_px": round(maxd, 2), "pass": ok})
    rep["sets"][s] = {"pages": len(pages), "pass_pages": sum(1 for p in pages if p["pass"]),
                      "identical_pages": sum(1 for p in pages if p.get("identical")), "per_page": pages}
rep["passed"] = bool(allok) and all(v["pages"] == a.n for v in rep["sets"].values())
json.dump(rep, open(a.out, "w"), indent=1)
print(json.dumps({"passed": rep["passed"], "sets": {s: {k: v[k] for k in ("pages", "pass_pages", "identical_pages")} for s, v in rep["sets"].items()}}))
raise SystemExit(0 if rep["passed"] else 2)