Download scripts/_final_e2e_lockdown.py from LiYacheng/r4d-bench-qa: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/datasets/LiYacheng/r4d-bench-qa/resolve/main/scripts/_final_e2e_lockdown.py
- Command line
-
hf download hf://datasets/LiYacheng/r4d-bench-qa/scripts/_final_e2e_lockdown.py
-
curl -L -o _final_e2e_lockdown.py https://huggingface.co/datasets/LiYacheng/r4d-bench-qa/resolve/main/scripts/_final_e2e_lockdown.py
15 kB
| """ | |
| 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()) | |