""" Ultimate post-Roboflow audit: identity + temporal + masks + eval sync. Exit code = number of HARD errors (warnings printed separately). """ from __future__ import annotations import csv import json import re import sys from collections import defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) 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(m: str) -> None: ERRORS.append(m) def warn(m: str) -> None: WARNINGS.append(m) def load(p: Path): return json.loads(p.read_text(encoding="utf-8")) def as_qs(raw): return raw["queries"] if isinstance(raw, dict) and "queries" in raw else raw def seg_pos(m: dict) -> bool: if m.get("temporally_inactive"): return False seg = m.get("segmentation") if isinstance(seg, dict): c = seg.get("counts") if isinstance(c, list) and len(c) == 1: h, w = seg.get("size") or [0, 0] if h and w and c[0] == int(h) * int(w): return False # empty RLE return bool(c) 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 = {} scene_of = {} scene_tracks = {} for cfg in SCENES_CONFIG: folder = cfg["folder"] sd = ROOT / "data/scenes" / folder annot = sd / cfg["annot_file"] if not annot.is_file(): err(f"missing annot {folder}/{cfg['annot_file']}") continue tracks = {t["track_id"]: t for t in load(sd / cfg["track_file"])["tracks"]} scene_tracks[folder] = tracks coco = load(annot) cat_names = {c["name"] for c in coco.get("categories", [])} for tid, t in tracks.items(): if t.get("category") not in cat_names: err(f"{folder}: track {tid} cat {t.get('category')!r} not in COCO") for q in as_qs(load(sd / cfg["query_file"])): qid = q["query_id"] if qid in scene_qs: err(f"duplicate qid {qid}") scene_qs[qid] = q scene_of[qid] = folder eval_q = {q["query_id"]: q for q in load(ROOT / "evaluation/R4D-Bench_queries.json")} eval_p = load(ROOT / "evaluation/R4D-Bench_predictions.json") gt89 = { q["query_id"]: q for q in load(ROOT / "scripts/new_predictions_ground_truth_all_queries.json") } gt89p = { q["query_id"]: q for q in load(ROOT / "scripts/new_predictions_ground_truth_all_queries_with_paths.json") } gt36 = { q["query_id"]: q for q in load(ROOT / "scripts/new_predictions_ground_truth_final.json") } curated = set() for cfg in SCENES_CONFIG: curated.update(cfg.get("queries") or []) print("COUNTS", len(scene_qs), len(eval_q), len(gt89), len(gt36), 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), "pred/scene"), (set(gt36), curated, "gt36/curated"), ]: if a != b: err(f"{name} mismatch {sorted(a ^ b)[:20]}") # CSV csv_ids = {r["track_id"] for r in csv.DictReader((ROOT / "data/track_metadata.csv").open(encoding="utf-8"))} all_t = set() for tr in scene_tracks.values(): all_t |= set(tr) if all_t - csv_ids: err(f"csv missing {sorted(all_t - csv_ids)}") if csv_ids - all_t: warn(f"csv extra {sorted(csv_ids - all_t)}") # static / C helpers static_keys = ( "never move", "completely still", "motionless", "remain stationary", "remain still", "remain physically motionless", "never move at any point", ) by_targets = defaultdict(list) for qid, sq in sorted(scene_qs.items()): folder = scene_of[qid] tracks = scene_tracks[folder] ids = list(sq.get("target_track_ids") or []) qtype = sq.get("query_type") eq = eval_q[qid] if sorted(eq.get("target_track_ids") or []) != sorted(ids): err(f"{qid}: eval ids") if eq.get("text_en") != sq.get("text_en") or eq.get("text_zh") != sq.get("text_zh"): err(f"{qid}: eval text") if sorted(eval_p.get(qid) or []) != sorted(ids): err(f"{qid}: predictions.json") for tid in ids: if tid not in tracks: err(f"{qid}: missing track {tid}") g = gt89[qid] gtracks = list(g["ground_truth"].get("target_tracks") or []) if sorted(gtracks) != sorted(ids): err(f"{qid}: gt tracks {gtracks} vs {ids}") want = _question_text_from_query(sq) if g.get("question") != want: err(f"{qid}: gt question") if sorted(gt89p[qid]["ground_truth"].get("target_tracks") or []) != sorted(ids): err(f"{qid}: gt89p tracks") if gt89p[qid].get("question") != want: err(f"{qid}: gt89p question") frames = g["ground_truth"].get("frames") or [] existence = [int(x) for x in (g["ground_truth"].get("existence_frames") or [])] tg = g["ground_truth"].get("temporal_gating") or {} if qtype == "C" or not ids: if ids: err(f"{qid}: C/empty with ids {ids}") if frames or existence: err(f"{qid}: C should have empty frames/existence") continue if not frames: err(f"{qid}: nonempty but no frames") continue if not existence: err( f"{qid}: nonempty but EMPTY existence_frames " f"(anchor={sq.get('expected_temporal_anchor')})" ) # categories unique set expect_cats = {tracks[t]["category"] for t in ids} tcats = set(g["ground_truth"].get("target_categories") or []) if tcats and tcats != expect_cats: err(f"{qid}: cats {tcats} vs {expect_cats}") # existence ⊆ frames; positive vs inactive frame_ids = [int(fr["frame_id"]) for fr in frames] if set(existence) - set(frame_ids): err(f"{qid}: existence not in frames") for fr in frames: fid = int(fr["frame_id"]) masks = fr.get("masks") or [] pos = any(seg_pos(m) for m in masks) if fid in existence and not pos: err(f"{qid}: existence frame {fid} has no positive mask") if fid not in existence: # should be inactive/empty if pos: err(f"{qid}: non-existence frame {fid} still has positive mask") for m in masks: mid = m.get("track_id") if mid and mid not in ids: err(f"{qid}: mask track {mid} not in targets") # query_masks PNGs sample all frames qroot = ROOT / "data/scenes" / folder / "query_masks" for fr in frames: fid = int(fr["frame_id"]) rel = fr.get("combined_mask_image") or ( f"data/scenes/{folder}/query_masks/frame_{fid:06d}/{qid}/answer.png" ) # prefer with_paths wp = gt89p[qid]["ground_truth"]["frames"] wpf = next((x for x in wp if int(x["frame_id"]) == fid), None) if wpf and wpf.get("combined_mask_image"): rel = wpf["combined_mask_image"] p = ROOT / str(rel).lstrip("./") if not p.is_file(): # try 6-digit layout p2 = qroot / f"frame_{fid:06d}" / qid / "answer.png" if not p2.is_file(): err(f"{qid}: missing mask png frame {fid}") break # anchor consistency anch = sq.get("expected_temporal_anchor") if anch: if not tg.get("temporal_gated"): # all targets missing anchor key have = any(anch in (tracks[t].get("temporal_profile") or {}) for t in ids) if have: err(f"{qid}: has anchor {anch} but GT not gated") else: err(f"{qid}: anchor {anch} missing on all target profiles") else: if tg.get("anchor") != anch: err(f"{qid}: gating anchor {tg.get('anchor')} != query {anch}") # static style must be full-span positive en = (sq.get("text_en") or "").lower() zh = sq.get("text_zh") or "" is_static = any(k in en for k in static_keys) or ( ("静止" in zh or "未曾移动" in zh) and "除了" not in zh ) if is_static: if len(existence) != len(frame_ids): err(f"{qid}: static query not full-span positive ex={len(existence)} fr={len(frame_ids)}") if tg.get("temporal_gated") and tg.get("empty_frames", 0) > 0: err(f"{qid}: static query has black frames") # L/R note if ( "left side of the image" in en or "right side of the image" in en or "图像左侧" in zh or "图像右侧" in zh ): note = (sq.get("note") or "").lower() if "image" not in note and "viewer" not in note and "图像" not in (sq.get("note") or ""): warn(f"{qid}: L/R without note") # frame wording vs existence span m = re.search(r"frames?\s*(\d+)\s*[–\-to]+\s*(\d+)", sq.get("text_en") or "", re.I) if m and existence: lo, hi = int(m.group(1)), int(m.group(2)) if min(existence) < lo - 5 or max(existence) > hi + 5: # allow small slack for sparse sampling warn( f"{qid}: text window {lo}-{hi} vs existence {min(existence)}-{max(existence)}" ) by_targets[tuple(sorted(ids))].append( ( qid, sq.get("temporal_relation"), sq.get("expected_temporal_anchor"), frozenset(existence), ) ) if qid in curated: g3 = gt36[qid] if sorted(g3["ground_truth"].get("target_tracks") or []) != sorted(ids): err(f"{qid}: gt36 tracks") if g3.get("question") != want: err(f"{qid}: gt36 question") # identical positives with different temporal labels = HARD error for our contract print("\n=== identical-positive temporal pairs ===") for ids, rows in by_targets.items(): for i in range(len(rows)): for j in range(i + 1, len(rows)): a, b = rows[i], rows[j] if a[3] == b[3] and a[3] and (a[1] != b[1] or a[2] != b[2]): err( f"identical positives: {a[0]}({a[1]}/{a[2]}) vs {b[0]}({b[1]}/{b[2]}) n={len(a[3])}" ) # except-style quick check via target_count for qid, sq in scene_qs.items(): tc = sq.get("target_count") ids = sq.get("target_track_ids") or [] if tc is not None and int(tc) != len(ids): err(f"{qid}: target_count") print(f"\nHARD_ERRORS={len(ERRORS)}") for e in ERRORS: print(" ERR", e) print(f"WARNINGS={len(WARNINGS)}") for w in WARNINGS: print(" WARN", w) if not ERRORS: print("ULTIMATE AUDIT: NO HARD ERRORS") return len(ERRORS) if __name__ == "__main__": raise SystemExit(main())