#!/usr/bin/env python3 """Random annotation audit: visualize sample episodes for manual review.""" from __future__ import annotations import argparse import json import random import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parent PY = sys.executable LABEL_ROOT = "/share/robotwin2.0-hard-cross-embodiment" VIDEO_ROOT = "/share/robotwin2.0-hard" ANN_ROOT = ROOT / "outputs" / "classification_probe" DEFAULT_OUT = ANN_ROOT / "annotation_audit" / "review_sample" DEMOS = ["demo_clean_100_arx", "demo_clean_100_franka", "demo_clean_100_ur5"] TASK = "blocks_ranking_rgb" def load_annotation_json(path: Path) -> dict | None: try: text = path.read_text(encoding="utf-8") if not text.strip(): return None return json.loads(text) except (json.JSONDecodeError, OSError): return None def count_protocol_version(demo: str, protocol_version: int | None) -> tuple[int, int]: ann_dir = ANN_ROOT / "annotations" / TASK / demo if not ann_dir.exists(): return 0, 0 files = sorted(ann_dir.glob("episode_*.json")) if protocol_version is None: return len(files), len(files) matched = 0 for p in files: data = load_annotation_json(p) if data and data.get("protocol_version") == protocol_version: matched += 1 return matched, len(files) def wait_for_protocol(protocol_version: int, expected_per_robot: int = 100, poll_sec: int = 120) -> None: while True: counts = {demo: count_protocol_version(demo, protocol_version) for demo in DEMOS} done = all(matched >= expected_per_robot for matched, _ in counts.values()) summary = ", ".join( f"{demo.replace('demo_clean_100_', '')}={matched}/{total}" for demo, (matched, total) in counts.items() ) print(f"[wait] protocol v{protocol_version}: {summary}", flush=True) if done: print(f"[wait] all {expected_per_robot} episodes per robot at v{protocol_version}", flush=True) return time.sleep(poll_sec) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--per-robot", type=int, default=4, help="Random episodes per robot") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--step", type=int, default=2, help="Frame step for overlay video") parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--require-protocol-version", type=int, default=None) parser.add_argument("--wait-for-protocol", type=int, default=None) parser.add_argument("--expected-per-robot", type=int, default=100) parser.add_argument("--poll-sec", type=int, default=120) args = parser.parse_args() if args.wait_for_protocol is not None: wait_for_protocol(args.wait_for_protocol, args.expected_per_robot, args.poll_sec) if args.require_protocol_version is None: args.require_protocol_version = args.wait_for_protocol out = Path(args.output_dir) rng = random.Random(args.seed) picks: list[dict] = [] for demo in DEMOS: robot = demo.replace("demo_clean_100_", "") ann_dir = ANN_ROOT / "annotations" / TASK / demo eligible = list(range(100)) if args.require_protocol_version is not None: eligible = [] for eid in range(100): ann_path = ann_dir / f"episode_{eid:05d}.json" data = load_annotation_json(ann_path) if data and data.get("protocol_version") == args.require_protocol_version: eligible.append(eid) if len(eligible) < args.per_robot: raise RuntimeError( f"{demo}: only {len(eligible)} v{args.require_protocol_version} episodes, need {args.per_robot}" ) for eid in sorted(rng.sample(eligible, args.per_robot)): out_dir = out / f"{robot}_ep{eid:03d}" cmd = [ PY, "classification_probe.py", "visualize-annotation", "--task", TASK, "--demo", demo, "--episode", str(eid), "--output-dir", str(out_dir), "--label-root", LABEL_ROOT, "--video-root", VIDEO_ROOT, "--annotation-root", str(ANN_ROOT), "--step", str(args.step), ] print("+", " ".join(cmd), flush=True) subprocess.run(cmd, check=True, cwd=str(ROOT)) picks.append( { "robot": robot, "demo": demo, "episode_id": eid, "overlay_mp4": str(out_dir / "annotation_overlay.mp4"), "annotation_json": str(ann_dir / f"episode_{eid:05d}.json"), } ) out.mkdir(parents=True, exist_ok=True) (out / "selection.json").write_text(json.dumps(picks, indent=2), encoding="utf-8") proto_note = ( f" (protocol v{args.require_protocol_version})" if args.require_protocol_version is not None else "" ) (out / "README.md").write_text( f"""# Annotation review sample Random {args.per_robot} episodes per robot (seed={args.seed}){proto_note}. Open `annotation_overlay.mp4` in each subfolder. Top bar shows GT primitive label. See `selection.json` for paths. """, encoding="utf-8", ) print(f"wrote {len(picks)} overlays to {out}", flush=True) if __name__ == "__main__": main()