File size: 14,967 Bytes
aa7e82c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""

End-to-end lockdown AFTER Roboflow export.



Pipeline:

  COCO (cfg annot_file) -> scene track JSON -> *_queries.json

  -> evaluation/R4D-Bench_{queries,predictions}.json

  -> scripts/new_predictions_ground_truth_{all_queries,final}[+_with_paths].json

  -> data/scenes/*/query_masks[/ _36]

"""
from __future__ import annotations

import csv
import json
import sys
from collections import defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from scripts.coco_scene_paths import resolve_scene_coco_annotation
from scripts.predictions_ground_truth import (
    SCENES_CONFIG,
    _question_text_from_query,
    frame_number_from_coco_image,
)

ERRORS: list[str] = []
WARNINGS: list[str] = []


def err(msg: str) -> None:
    ERRORS.append(msg)


def warn(msg: str) -> None:
    WARNINGS.append(msg)


def load_json(path: Path):
    return json.loads(path.read_text(encoding="utf-8"))


def as_query_list(raw):
    if isinstance(raw, dict) and "queries" in raw:
        return raw["queries"]
    if isinstance(raw, list):
        return raw
    raise TypeError(type(raw))


def track_map(tracks_raw) -> dict:
    items = tracks_raw["tracks"] if isinstance(tracks_raw, dict) and "tracks" in tracks_raw else tracks_raw
    out = {}
    for t in items:
        tid = t.get("track_id") or t.get("id")
        out[str(tid)] = t
    return out


def segmentation_nonempty(seg) -> bool:
    if seg is None:
        return False
    if isinstance(seg, dict):
        return bool(seg.get("counts"))
    if isinstance(seg, list):
        if not seg:
            return False
        if isinstance(seg[0], (int, float)):
            return len(seg) >= 6
        return any(isinstance(p, list) and len(p) >= 6 for p in seg)
    return False


def main() -> int:
    scene_qs: dict[str, dict] = {}
    scene_of: dict[str, str] = {}
    for cfg in SCENES_CONFIG:
        scene_dir = ROOT / "data" / "scenes" / cfg["folder"]
        qpath = scene_dir / cfg["query_file"]
        if not qpath.is_file():
            err(f"MISSING query file {qpath}")
            continue
        for q in as_query_list(load_json(qpath)):
            qid = q["query_id"]
            if qid in scene_qs:
                err(f"DUPLICATE query_id {qid}")
            scene_qs[qid] = q
            scene_of[qid] = cfg["folder"]

    eval_q = {q["query_id"]: q for q in load_json(ROOT / "evaluation" / "R4D-Bench_queries.json")}
    eval_p = load_json(ROOT / "evaluation" / "R4D-Bench_predictions.json")
    gt89 = {
        q["query_id"]: q
        for q in load_json(ROOT / "scripts" / "new_predictions_ground_truth_all_queries.json")
    }
    gt89p = {
        q["query_id"]: q
        for q in load_json(
            ROOT / "scripts" / "new_predictions_ground_truth_all_queries_with_paths.json"
        )
    }
    gt36 = {
        q["query_id"]: q
        for q in load_json(ROOT / "scripts" / "new_predictions_ground_truth_final.json")
    }
    gt36p = {
        q["query_id"]: q
        for q in load_json(
            ROOT / "scripts" / "new_predictions_ground_truth_final_with_paths.json"
        )
    }
    curated = set()
    for cfg in SCENES_CONFIG:
        curated.update(cfg.get("queries") or [])

    print("=== LAYER COUNTS ===")
    print(
        f"scene={len(scene_qs)} eval_q={len(eval_q)} eval_p={len(eval_p)} "
        f"gt89={len(gt89)} gt89p={len(gt89p)} gt36={len(gt36)} gt36p={len(gt36p)} curated={len(curated)}"
    )

    for a, b, name in [
        (set(scene_qs), set(eval_q), "scene/eval"),
        (set(scene_qs), set(gt89), "scene/gt89"),
        (set(scene_qs), set(gt89p), "scene/gt89p"),
        (set(eval_p), set(scene_qs), "eval_p/scene"),
        (set(gt36), curated, "gt36/curated"),
        (set(gt36p), curated, "gt36p/curated"),
    ]:
        if a != b:
            err(f"{name} id mismatch {sorted(a ^ b)}")

    print("\n=== PER-SCENE COCO / TRACKS ===")
    scene_tracks: dict[str, dict] = {}
    for cfg in SCENES_CONFIG:
        folder = cfg["folder"]
        scene_dir = ROOT / "data" / "scenes" / folder
        annot_path = scene_dir / cfg["annot_file"]
        track_path = scene_dir / cfg["track_file"]
        if not annot_path.is_file():
            alt = resolve_scene_coco_annotation(scene_dir)
            err(f"{folder}: annot missing {cfg['annot_file']} (resolve={alt})")
            continue
        if not track_path.is_file():
            err(f"{folder}: missing track {cfg['track_file']}")
            continue
        coco = load_json(annot_path)
        tracks = track_map(load_json(track_path))
        scene_tracks[folder] = tracks
        cats = {int(c["id"]): c["name"] for c in coco.get("categories", [])}
        cat_names = set(cats.values())
        images = coco.get("images", [])
        anns = coco.get("annotations", [])
        print(
            f"  {folder}: annot={annot_path.name} images={len(images)} anns={len(anns)} tracks={len(tracks)}"
        )
        if not images:
            err(f"{folder}: 0 COCO images")
        if not tracks:
            err(f"{folder}: 0 tracks")
        unmapped = sum(1 for im in images if frame_number_from_coco_image(im) is None)
        if unmapped:
            err(f"{folder}: {unmapped} COCO images unmapped frame_id")
        for tid, t in tracks.items():
            cname = t.get("category")
            if cname and cname not in cat_names:
                err(f"{folder}: track {tid} category {cname!r} not in COCO categories {sorted(cat_names)}")

    print("\n=== QUERY IDENTITY + GT GEOMETRY (89) ===")
    type_counts: dict = defaultdict(int)
    for qid, sq in sorted(scene_qs.items()):
        folder = scene_of[qid]
        tracks = scene_tracks.get(folder, {})
        ids = list(sq.get("target_track_ids") or [])
        qtype = sq.get("query_type")
        type_counts[qtype] += 1

        eq = eval_q[qid]
        if sorted(eq.get("target_track_ids") or []) != sorted(ids):
            err(f"{qid}: eval ids != scene")
        if list(eq.get("target_track_ids") or []) != ids:
            warn(f"{qid}: eval id order differs from scene")
        if eq.get("text_en") != sq.get("text_en") or eq.get("text_zh") != sq.get("text_zh"):
            err(f"{qid}: eval text != scene")
        if eq.get("query_type") != qtype:
            err(f"{qid}: eval query_type mismatch")
        if sorted(eval_p.get(qid) or []) != sorted(ids):
            err(f"{qid}: predictions.json != scene")

        for tid in ids:
            if tid not in tracks:
                err(f"{qid}: target {tid} missing in {folder} tracks")

        if qtype == "C":
            if ids:
                err(f"{qid}: type C nonempty {ids}")
        else:
            if not ids:
                err(f"{qid}: type {qtype} empty targets")

        tc = sq.get("target_count")
        if tc is not None and int(tc) != len(ids):
            err(f"{qid}: target_count={tc} != len(ids)={len(ids)}")

        g = gt89[qid]
        gtracks = list(g.get("ground_truth", {}).get("target_tracks") or [])
        if sorted(gtracks) != sorted(ids):
            err(f"{qid}: gt89 tracks {gtracks} != {ids}")
        want_q = _question_text_from_query(sq)
        if g.get("question") != want_q:
            err(f"{qid}: gt89 question mismatch gt={g.get('question')!r} want={want_q!r}")

        frames = g.get("ground_truth", {}).get("frames") or []
        existence = g.get("ground_truth", {}).get("existence_frames") or []
        if qtype == "C":
            if frames:
                err(f"{qid}: type C has {len(frames)} frames")
            if existence:
                err(f"{qid}: type C has existence_frames")
        else:
            if not frames:
                err(f"{qid}: nonempty but gt frames empty")
            frame_ids = []
            for fr in frames:
                fid = fr.get("frame_id")
                frame_ids.append(int(fid))
                masks = fr.get("masks") or []
                if not masks:
                    err(f"{qid}: frame {fid} 0 masks")
                    continue
                if not any(segmentation_nonempty(m.get("segmentation")) for m in masks):
                    if not any(m.get("mask_image") or m.get("combined_mask_image") for m in masks):
                        err(f"{qid}: frame {fid} empty segmentation")
                for m in masks:
                    mid = m.get("track_id") or m.get("target_track_id")
                    if mid and mid not in ids:
                        err(f"{qid}: frame {fid} mask track {mid} not in targets")

            # existence_frames = positive (non-empty) frames; may be a subset when
            # temporal gating writes empty/black masks outside the anchor window.
            if existence:
                only_ex = sorted(set(int(x) for x in existence) - set(frame_ids))
                if only_ex:
                    err(f"{qid}: existence_frames not in frames[]: {only_ex[:8]}")
                # every existence frame must have at least one non-empty segmentation
                ex_set = set(int(x) for x in existence)
                for fr in frames:
                    fid = int(fr["frame_id"])
                    masks = fr.get("masks") or []
                    has_pos = any(
                        segmentation_nonempty(m.get("segmentation"))
                        and not m.get("temporally_inactive")
                        for m in masks
                    )
                    if fid in ex_set and not has_pos:
                        # empty RLE counts=[H*W] is "nonempty" structure but inactive
                        inactive = all(m.get("temporally_inactive") for m in masks) if masks else True
                        if inactive:
                            err(f"{qid}: existence frame {fid} has only empty/inactive masks")

            # query_masks sample
            qmask_root = ROOT / "data" / "scenes" / folder / "query_masks"
            if not qmask_root.is_dir():
                err(f"{qid}: missing query_masks for {folder}")
            else:
                for fid in frame_ids[:5]:
                    d = qmask_root / f"frame_{int(fid):06d}" / qid
                    if d.is_dir():
                        if not list(d.glob("*.png")):
                            err(f"{qid}: empty mask dir frame {fid}")
                            break
                    else:
                        alts = list(qmask_root.glob(f"frame_{int(fid):06d}/{qid}*"))
                        if not alts:
                            err(f"{qid}: missing query_masks frame {fid}")
                            break

        # categories vs tracks (GT stores unique category names; two hands → one "hand")
        tcats = g.get("ground_truth", {}).get("target_categories") or []
        if ids:
            expect_cats = {tracks[t].get("category") for t in ids if t in tracks}
            if tcats and set(tcats) != expect_cats:
                err(f"{qid}: gt categories {set(tcats)} != track cats {expect_cats}")

        gp = gt89p[qid]
        if sorted(gp["ground_truth"].get("target_tracks") or []) != sorted(ids):
            err(f"{qid}: gt89p tracks mismatch")
        if gp.get("question") != want_q:
            err(f"{qid}: gt89p question mismatch")

        if qid in curated:
            g3 = gt36[qid]
            if sorted(g3["ground_truth"].get("target_tracks") or []) != sorted(ids):
                err(f"{qid}: gt36 tracks mismatch")
            if g3.get("question") != want_q:
                err(f"{qid}: gt36 question mismatch")
            if sorted(gt36p[qid]["ground_truth"].get("target_tracks") or []) != sorted(ids):
                err(f"{qid}: gt36p tracks mismatch")

        ten = (sq.get("text_en") or "").lower()
        tzh = sq.get("text_zh") or ""
        if (
            "left side of the image" in ten
            or "right side of the image" in ten
            or "图像左侧" in tzh
            or "图像右侧" in tzh
        ):
            note = (sq.get("note") or "").lower()
            if "image" not in note and "viewer" not in note:
                warn(f"{qid}: L/R image wording without note")

    print(f"query_type counts: {dict(type_counts)}")

    print("\n=== CURATED IDS IN CONFIG ===")
    for cfg in SCENES_CONFIG:
        qmap = {
            q["query_id"]: q
            for q in as_query_list(
                load_json(ROOT / "data" / "scenes" / cfg["folder"] / cfg["query_file"])
            )
        }
        for qid in cfg.get("queries") or []:
            if qid not in qmap:
                err(f"curated id {qid} missing in {cfg['folder']}")

    print("\n=== track_metadata.csv ===")
    csv_ids = set()
    with (ROOT / "data" / "track_metadata.csv").open(encoding="utf-8") as f:
        for row in csv.DictReader(f):
            csv_ids.add(row["track_id"])
    all_track_ids = set()
    for tr in scene_tracks.values():
        all_track_ids.update(tr.keys())
    miss = sorted(all_track_ids - csv_ids)
    extra = sorted(csv_ids - all_track_ids)
    if miss:
        err(f"track_metadata missing {miss}")
    if extra:
        warn(f"track_metadata extra {extra}")
    print(f"tracks={len(all_track_ids)} csv={len(csv_ids)}")

    print("\n=== WITH_PATHS FILE EXISTENCE ===")
    checked = 0
    missing_paths = 0
    for qid, g in gt89p.items():
        if scene_qs[qid].get("query_type") == "C":
            continue
        frames = g.get("ground_truth", {}).get("frames") or []
        if not frames:
            continue
        # every frame should have combined_mask_image after enrich
        for fr in frames:
            rel = fr.get("combined_mask_image")
            if not rel:
                missing_paths += 1
                continue
            p = ROOT / str(rel).lstrip("./")
            if not p.is_file():
                err(f"{qid}: missing combined_mask_image={rel}")
            else:
                checked += 1
    if missing_paths:
        warn(f"{missing_paths} nonempty-query frames lack combined_mask_image field")
    print(f"combined_mask_image files ok={checked} missing_field_frames={missing_paths}")

    print("\n========== SUMMARY ==========")
    print(f"ERRORS={len(ERRORS)}")
    for e in ERRORS:
        print("  ERR:", e)
    print(f"WARNINGS={len(WARNINGS)}")
    for w in WARNINGS[:50]:
        print("  WARN:", w)
    if len(WARNINGS) > 50:
        print(f"  ... {len(WARNINGS) - 50} more")
    if not ERRORS:
        print("E2E LOCKDOWN PASSED (0 errors)")
    else:
        print("E2E LOCKDOWN FAILED")
    return len(ERRORS)


if __name__ == "__main__":
    raise SystemExit(main())