#!/usr/bin/env python3 """prep_lerobot.py — bridge fd-studio's flat transform output to the layout to_lerobot_v21 + multiview expect, then those scripts run unmodified. fd-studio's transform writes /workspace/transform/retargeted/clip_file-XXXXXX/retargeted.hdf5 (flat, one dir per episode; the hdf5 carries attrs task= and clip="file-XXXXXX"). to_lerobot_v21.discover() wants /workspace/retargeted//clip_file-FFF_epN/retargeted.hdf5 and finds the ego video at //videos/observation.images.camera/chunk-CCC/file-FFF.mp4. This script, per retargeted clip: • re-derives the source (chunk, file) via transform_batch._episode_range (the same mapping the transform used), so file-FFF matches the ego data+video file index, • symlinks the hdf5 into /workspace/retargeted//clip_file-FFF_epN/, • downloads that clip's ego VIDEO into the cache (transform only fetched keypoints). EGO for to_lerobot is then just the cache's repo dir (already /videos + /meta). Runs in the retarget venv (h5py). Usage: python prep_lerobot.py --flat /workspace/transform/retargeted --cache /workspace/ego_cache \ [--retgt-out /workspace/retargeted] Prints a JSON line: {"clips": N, "retgt": ..., "ego": ...}. """ import argparse import glob import json import os import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path import h5py sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import transform_batch as tb # noqa: E402 (reuse _episode_range/_ensure/REPO/PREFIX) def _verdict(m: dict, th: dict) -> str: """Re-grade one clip's metrics with the user's thresholds (mirror of the console re-grade).""" rank = {"PASS": 0, "WARN": 1, "FAIL": 2, "?": 0} ik = max(float(m.get("ik_R_cm", 0) or 0), float(m.get("ik_L_cm", 0) or 0)) ori = max(float(m.get("ori_R_deg", 0) or 0), float(m.get("ori_L_deg", 0) or 0)) track = "FAIL" if ik >= th["ik_fail"] else "WARN" if ik >= th["ik_warn"] else "PASS" ori_g = "FAIL" if ori >= th["ori_fail"] else "WARN" if ori >= th["ori_warn"] else "PASS" arms = "PASS" if m.get("collision") == "clean" else {"allow": "PASS", "warn": "WARN", "fail": "FAIL"}.get(th["arms"], "PASS") mraw = m.get("qa_motion") or m.get("qa") or "PASS" arm_m = th["motion"] motion = "PASS" if arm_m == "off" else ("FAIL" if (arm_m == "strict" and mraw in ("WARN", "FAIL")) else mraw) return max([track, ori_g, arms, motion], key=lambda v: rank.get(v, 0)) def _excluded_ids(report_path: str, th: dict) -> set: """clip_ids ('#') the user's thresholds flag as FAIL — skipped from the dataset.""" try: rep = json.loads(Path(report_path).read_text()) except Exception: return set() out = set() for c in rep.get("clips", []): if c.get("status") == "done" and _verdict(c.get("metrics") or {}, th) == "FAIL": out.add(c.get("clip_id")) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--flat", required=True, help="/workspace/transform/retargeted") ap.add_argument("--cache", required=True, help="/workspace/ego_cache") ap.add_argument("--retgt-out", default="/workspace/retargeted") # Exclude-enforcement: if --exclude, drop clips the user's thresholds flag as FAIL (read from # the retarget report). Off by default — we never auto-drop unless the user opts in. ap.add_argument("--report", default="", help="/workspace/report.json (for --exclude)") ap.add_argument("--exclude", type=int, default=0, help="1 = drop FAIL-flagged clips") ap.add_argument("--ik-warn", type=float, default=3.0) ap.add_argument("--ik-fail", type=float, default=6.0) ap.add_argument("--ori-warn", type=float, default=15.0) ap.add_argument("--ori-fail", type=float, default=30.0) ap.add_argument("--arms", default="allow") ap.add_argument("--motion", default="off") a = ap.parse_args() cache = Path(a.cache) ego_root = cache / tb.REPO.replace("/", "__") # to_lerobot EGO = this (/videos + meta) done, vids, skipped, excluded = 0, 0, 0, 0 th = {"ik_warn": a.ik_warn, "ik_fail": a.ik_fail, "ori_warn": a.ori_warn, "ori_fail": a.ori_fail, "arms": a.arms, "motion": a.motion} exclude_set = _excluded_ids(a.report, th) if (a.exclude and a.report) else set() if exclude_set: print(f"[exclude] user opted to drop {len(exclude_set)} FAIL-flagged clips", file=sys.stderr) # Pass 1 — resolve each retargeted clip to (cat, ep, chunk, file) and symlink it into the # category layout. Cheap (local hdf5 attrs + cached meta parquets), so keep it sequential. items = [] # (cat, ep, ci, fi, vid_rel) for hp in sorted(glob.glob(f"{a.flat}/*/retargeted.hdf5")): try: with h5py.File(hp, "r") as h: cat = str(h.attrs["task"]) ep = int(str(h.attrs["clip"]).split("-")[1]) if f"{cat}#{ep}" in exclude_set: # user opted to drop this FAIL-flagged clip excluded += 1 continue r = tb._episode_range(cache, cat, ep) ci, fi = r["data/chunk_index"], r["data/file_index"] fyy = f"file-{fi:03d}" # Prefer the VALIDATED+CORRECTED trajectory if Data Validation wrote one (clamp+smooth); # fall back to the raw retarget. This is what makes the pushed dataset the corrected one. corrected = str(Path(hp).with_name("corrected.hdf5")) src = corrected if os.path.exists(corrected) else hp dst = Path(a.retgt_out) / cat / f"clip_{fyy}_ep{ep}" dst.mkdir(parents=True, exist_ok=True) link = dst / "retargeted.hdf5" if link.is_symlink() or link.exists(): link.unlink() os.symlink(os.path.abspath(src), link) vid_rel = f"{tb.PREFIX}{cat}/videos/observation.images.camera/chunk-{ci:03d}/{fyy}.mp4" items.append(vid_rel) done += 1 except Exception as e: skipped += 1 print(f"[warn] {hp}: {e}", file=sys.stderr) # Pass 2 — download the ego VIDEOS in PARALLEL (transform only fetched keypoints). These are the # big files; a sequential loop dominated packaging wall-clock. Dedup + bounded per-file timeout # in tb._ensure make concurrent fetches safe. A failed video is a non-fatal warn. def _dlvid(vid_rel: str) -> bool: try: tb._ensure(cache, vid_rel) return True except Exception as e: print(f"[warn] video dl {vid_rel}: {e}", file=sys.stderr) return False uniq = list(dict.fromkeys(items)) # preserve order, drop dup video files with ThreadPoolExecutor(max_workers=min(24, max(1, len(uniq)))) as ex: vids = sum(1 for ok in ex.map(_dlvid, uniq) if ok) print(json.dumps({"clips": done, "videos": vids, "skipped": skipped, "excluded": excluded, "retgt": a.retgt_out, "ego": str(ego_root)})) if __name__ == "__main__": main()