File size: 4,422 Bytes
3f3fbe2
3726258
 
 
3f3fbe2
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
"""Write ``<tier>/annotations_complete.json`` (the scenes in which every intended class is annotated) and a
CSV of completeness per sub-tier.
"""
from __future__ import annotations

import argparse
import ast
import csv
import datetime
import json
import pathlib
import sys
from typing import Dict, List, Optional

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from strangebench.common.variants import V1_LABELS, order_tiers  # noqa: E402

TIERS = list(V1_LABELS)


def discover_tiers(root: pathlib.Path) -> List[str]:

    return order_tiers([p.parent.name for p in root.glob("*/annotations.json")])


def complete_subset(d: Dict, anchor_of: Optional[Dict[str, str]] = None) -> Dict:
    """Return ``{"coco": filtered, "n_images", "n_complete", "n_anchor_unannotated"}`` for
    one tier's annotations.json. The anchor per scene comes from ``anchor_of`` (scene_specs),
    else the first intended label."""
    anchor_of = anchor_of or {}
    cat = {c['id']: c['name'].lower() for c in d['categories']}
    present: Dict[int, set] = {}
    for an in d['annotations']:
        present.setdefault(an['image_id'], set()).add(cat[an['category_id']])
    keep, n_missing_anchor = [], 0
    for im in d['images']:
        li = im.get('labels_intended', '[]')
        intended = {x.lower() for x in (json.loads(li.replace("'", '"')) if isinstance(li, str) else li)}
        ok = bool(intended) and intended <= present.get(im['id'], set())
        if ok:
            keep.append(im['id'])
        anchor = anchor_of.get(im.get('scene_id')) or (next(iter(intended)) if intended else None)
        if anchor and anchor not in present.get(im['id'], set()):
            n_missing_anchor += 1
    ks = set(keep)
    out = dict(d)
    out['images'] = [im for im in d['images'] if im['id'] in ks]
    out['annotations'] = [an for an in d['annotations'] if an['image_id'] in ks]
    out.setdefault('info', {})
    out['info'] = dict(out['info'], completeness_filter='every intended class annotated')
    return {"coco": out, "n_images": len(d['images']), "n_complete": len(keep),
            "n_anchor_unannotated": n_missing_anchor}


def main() -> None:
    ap = argparse.ArgumentParser(); ap.add_argument('--root', default='data/strange_bench/clean')
    ap.add_argument('--out-csv', default='strange_bench_annotation_completeness.csv')
    ap.add_argument('--scene-specs', default='scene_specs.json', help='anchor name per scene_id (authoritative)')
    a = ap.parse_args()
    _specs = json.load(open(a.scene_specs)) if pathlib.Path(a.scene_specs).exists() else []
    anchor_of = {s_['scene_id']: ast.literal_eval(s_['anchor'])['name'].lower() if isinstance(s_['anchor'], str) else s_['anchor']['name'].lower() for s_ in _specs}
    root = pathlib.Path(a.root)
    rows = []
    for t in discover_tiers(root):
        p = root / t / 'annotations.json'
        d = json.load(open(p))
        res = complete_subset(d, anchor_of)
        out = res["coco"]
        out['info'] = dict(out['info'], source=str(p), date=str(datetime.date.today()))
        json.dump(out, open(p.with_name('annotations_complete.json'), 'w'))
        n = res["n_images"]
        rows.append(dict(tier=t, n_images=n, n_complete=res["n_complete"], retention_pct=round(100*res["n_complete"]/max(n, 1), 1),
                         n_anchor_unannotated=res["n_anchor_unannotated"], anchor_unannotated_pct=round(100*res["n_anchor_unannotated"]/max(n, 1), 1)))
        print(rows[-1])
    if not rows:
        raise SystemExit(f"no <tier>/annotations.json under {root}")
    with open(a.out_csv, 'w') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys())); w.writeheader(); w.writerows(rows)
        tot = sum(r['n_images'] for r in rows); comp = sum(r['n_complete'] for r in rows); ma = sum(r['n_anchor_unannotated'] for r in rows)
        f.write(f"# description: per-tier annotation completeness of the released clean STRANGE-Bench tree; annotations_complete.json written next to each annotations.json\n")
        f.write(f"# totals: images={tot} complete={comp} ({100*comp/tot:.1f}%) anchor_unannotated={ma} ({100*ma/tot:.1f}%); anchor from scene_specs.json (fallback: first intended label)\n")
        f.write(f"# root: {a.root} | script: strangebench/audit/make_complete_annotations.py | generated: {datetime.date.today()}\n")
    print('wrote', a.out_csv)


if __name__ == "__main__":
    main()