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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""T3/T4 — batch retarget over selected_clips.json with live, human-readable progress.
|
| 2 |
+
|
| 3 |
+
Runs under .venv-retarget. For each shortlisted clip: materialize a single-episode parquet
|
| 4 |
+
→ run the real M1..M6 engine → emit per-clip friendly-stage progress + metrics into
|
| 5 |
+
transform_report.json (written incrementally so the console can poll it live).
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import contextlib
|
| 9 |
+
import io
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import ssl
|
| 13 |
+
import sys
|
| 14 |
+
import urllib.request
|
| 15 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pyarrow.compute as pc
|
| 20 |
+
import pyarrow.parquet as pq
|
| 21 |
+
|
| 22 |
+
# macOS Python's urllib has no CA bundle by default → HF downloads fail with
|
| 23 |
+
# CERTIFICATE_VERIFY_FAILED. Use certifi's bundle (fall back to unverified only if absent).
|
| 24 |
+
try:
|
| 25 |
+
import certifi
|
| 26 |
+
|
| 27 |
+
_SSL_CTX = ssl.create_default_context(cafile=certifi.where())
|
| 28 |
+
except Exception:
|
| 29 |
+
_SSL_CTX = ssl._create_unverified_context()
|
| 30 |
+
|
| 31 |
+
REPO = os.environ.get("FD_EGO_REPO", "Kavin60606/EgoDex-PickPlace-10hr")
|
| 32 |
+
PREFIX = os.environ.get("FD_EGO_PREFIX", "") # "" = 10hr root layout; "train/" = griffinlabs
|
| 33 |
+
RESOLVE = "https://huggingface.co/datasets/%s/resolve/main/%s"
|
| 34 |
+
|
| 35 |
+
# customer-facing stage names (replace M1..M6)
|
| 36 |
+
STAGES = [
|
| 37 |
+
("load", "Reading human demo"),
|
| 38 |
+
("retarget", "Retargeting motion to robot"),
|
| 39 |
+
("base", "Placing the robot"),
|
| 40 |
+
("ik", "Solving arm joints (IK)"),
|
| 41 |
+
("collision", "Checking arm collisions"),
|
| 42 |
+
("smooth", "Smoothing trajectory"),
|
| 43 |
+
("qa", "Quality check"),
|
| 44 |
+
("output", "Saving robot trajectory"),
|
| 45 |
+
]
|
| 46 |
+
STAGE_KEYS = [k for k, _ in STAGES]
|
| 47 |
+
# order matters: match "[M3.5]" before "[M3]"
|
| 48 |
+
MARKERS = [("[M6]", "output"), ("[M5]", "qa"), ("[M4]", "smooth"),
|
| 49 |
+
("[M3.5]", "collision"), ("[M3]", "ik"), ("[M2]", "base"), ("[M1]", "retarget")]
|
| 50 |
+
|
| 51 |
+
KP_COLS = [f"observation.state.{h}{k}" for h in ("right", "left")
|
| 52 |
+
for k in ("ThumbTip", "IndexFingerTip", "MiddleFingerTip", "Hand")]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _ensure(cache: Path, rel: str) -> Path:
|
| 56 |
+
local = cache / REPO.replace("/", "__") / rel
|
| 57 |
+
if not local.exists():
|
| 58 |
+
local.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
req = urllib.request.Request(RESOLVE % (REPO, rel), headers={"User-Agent": "fd-studio"})
|
| 60 |
+
with urllib.request.urlopen(req, context=_SSL_CTX) as r:
|
| 61 |
+
local.write_bytes(r.read())
|
| 62 |
+
return local
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _episode_range(cache: Path, subset: str, ep: int) -> dict:
|
| 66 |
+
base = f"{PREFIX}{subset}"
|
| 67 |
+
cols = ["episode_index", "length", "tasks", "data/chunk_index", "data/file_index",
|
| 68 |
+
"dataset_from_index", "dataset_to_index"]
|
| 69 |
+
for i in range(0, 12): # episodes/chunk-000/file-000.parquet, file-001, ...
|
| 70 |
+
rel = f"{base}/meta/episodes/chunk-000/file-{i:03d}.parquet"
|
| 71 |
+
try:
|
| 72 |
+
local = _ensure(cache, rel)
|
| 73 |
+
except Exception:
|
| 74 |
+
break
|
| 75 |
+
for row in pq.read_table(local, columns=cols).to_pylist():
|
| 76 |
+
if row["episode_index"] == ep:
|
| 77 |
+
return row
|
| 78 |
+
raise KeyError(f"episode {ep} not found in {subset}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _materialize(cache: Path, subset: str, ep: int, out_root: Path) -> str:
|
| 82 |
+
r = _episode_range(cache, subset, ep)
|
| 83 |
+
ci, fi = r["data/chunk_index"], r["data/file_index"]
|
| 84 |
+
data_rel = f"{PREFIX}{subset}/data/chunk-{ci:03d}/file-{fi:03d}.parquet"
|
| 85 |
+
local = _ensure(cache, data_rel)
|
| 86 |
+
# a data file concatenates many episodes; `dataset_from/to_index` are GLOBAL offsets,
|
| 87 |
+
# so filter by the file's own episode_index column instead of slicing.
|
| 88 |
+
table = pq.read_table(local, columns=KP_COLS + ["episode_index"])
|
| 89 |
+
table = table.filter(pc.equal(table["episode_index"], ep)).select(KP_COLS)
|
| 90 |
+
mat = out_root / "materialized" / subset / "data" / "chunk-000"
|
| 91 |
+
mat.mkdir(parents=True, exist_ok=True)
|
| 92 |
+
out = mat / f"file-{ep:06d}.parquet"
|
| 93 |
+
pq.write_table(table, out)
|
| 94 |
+
return str(out)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Report:
|
| 98 |
+
def __init__(self, path: Path, clips: list, teleop: dict):
|
| 99 |
+
self.path = path
|
| 100 |
+
self.teleop = teleop
|
| 101 |
+
self.data = {
|
| 102 |
+
"clips_total": len(clips),
|
| 103 |
+
"clips": [{
|
| 104 |
+
"clip_id": c["clip_id"], "task": c.get("task", ""), "n_frames": c.get("n_frames", 0),
|
| 105 |
+
"status": "pending",
|
| 106 |
+
"stages": [{"key": k, "label": lbl, "status": "pending"} for k, lbl in STAGES],
|
| 107 |
+
"metrics": {}, "error": None, "output": None,
|
| 108 |
+
} for c in clips],
|
| 109 |
+
"match_report": None, "done": False,
|
| 110 |
+
}
|
| 111 |
+
self.write()
|
| 112 |
+
|
| 113 |
+
def write(self):
|
| 114 |
+
self.path.write_text(json.dumps(self.data, indent=2))
|
| 115 |
+
|
| 116 |
+
def advance(self, i: int, key: str):
|
| 117 |
+
pos = STAGE_KEYS.index(key)
|
| 118 |
+
for j, s in enumerate(self.data["clips"][i]["stages"]):
|
| 119 |
+
s["status"] = "done" if j < pos else ("running" if j == pos else "pending")
|
| 120 |
+
self.data["clips"][i]["status"] = "running"
|
| 121 |
+
|
| 122 |
+
def start(self, i: int):
|
| 123 |
+
self.data["clips"][i]["status"] = "running"
|
| 124 |
+
self.data["clips"][i]["stages"][0]["status"] = "running"
|
| 125 |
+
|
| 126 |
+
def finish(self, i: int, res: dict, collision: str):
|
| 127 |
+
c = self.data["clips"][i]
|
| 128 |
+
for s in c["stages"]:
|
| 129 |
+
s["status"] = "done"
|
| 130 |
+
c["status"] = "done"
|
| 131 |
+
c["output"] = res.get("output")
|
| 132 |
+
c["metrics"] = {
|
| 133 |
+
"ik_R_cm": round(res.get("ik_R_cm", 0), 2), "ik_L_cm": round(res.get("ik_L_cm", 0), 2),
|
| 134 |
+
"ori_R_deg": round(res.get("ori_R_deg", 0), 1), "ori_L_deg": round(res.get("ori_L_deg", 0), 1),
|
| 135 |
+
"collision": collision, "qa": res.get("qa_verdict", "?"), "dof": 14,
|
| 136 |
+
"n_frames": res.get("n_frames_out", c["n_frames"]),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
def fail(self, i: int, msg: str):
|
| 140 |
+
c = self.data["clips"][i]
|
| 141 |
+
for s in c["stages"]:
|
| 142 |
+
if s["status"] == "running":
|
| 143 |
+
s["status"] = "fail"
|
| 144 |
+
c["status"] = "failed"
|
| 145 |
+
c["error"] = msg
|
| 146 |
+
|
| 147 |
+
def finalize(self):
|
| 148 |
+
done = [c for c in self.data["clips"] if c["status"] == "done"]
|
| 149 |
+
failed = sum(1 for c in self.data["clips"] if c["status"] == "failed")
|
| 150 |
+
teleop_hz = int(self.teleop.get("fps") or 30)
|
| 151 |
+
if done:
|
| 152 |
+
iks = [(c["metrics"]["ik_R_cm"] + c["metrics"]["ik_L_cm"]) / 2 for c in done]
|
| 153 |
+
ik_mean = round(float(np.mean(iks)), 2)
|
| 154 |
+
clean = sum(1 for c in done if c["metrics"]["collision"] == "clean")
|
| 155 |
+
fidelity = round(max(0.0, 1 - ik_mean / 10.0), 2)
|
| 156 |
+
clean_rate = round(clean / len(done), 2)
|
| 157 |
+
else: # nothing succeeded — report honestly, not a fake 100%
|
| 158 |
+
ik_mean = fidelity = clean_rate = None
|
| 159 |
+
self.data["match_report"] = {
|
| 160 |
+
"teleop_hz": teleop_hz, "ego_hz": 30,
|
| 161 |
+
"fps_variance": abs(teleop_hz - 30),
|
| 162 |
+
"action_hz_match": teleop_hz == 30,
|
| 163 |
+
"ik_mean_cm": ik_mean,
|
| 164 |
+
"traj_similarity": fidelity,
|
| 165 |
+
"collision_clean_rate": clean_rate,
|
| 166 |
+
"clips_done": len(done), "clips_failed": failed,
|
| 167 |
+
}
|
| 168 |
+
self.data["done"] = True
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class _Tee(io.TextIOBase):
|
| 172 |
+
def __init__(self, orig, on_line):
|
| 173 |
+
self.orig, self.on_line, self.buf = orig, on_line, ""
|
| 174 |
+
|
| 175 |
+
def write(self, s):
|
| 176 |
+
self.orig.write(s)
|
| 177 |
+
self.buf += s
|
| 178 |
+
while "\n" in self.buf:
|
| 179 |
+
line, self.buf = self.buf.split("\n", 1)
|
| 180 |
+
self.on_line(line)
|
| 181 |
+
return len(s)
|
| 182 |
+
|
| 183 |
+
def flush(self):
|
| 184 |
+
self.orig.flush()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _prewarm(cache: Path, clips: list) -> None:
|
| 188 |
+
"""Download each clip's episodes-meta + data parquet ONCE in the parent, so parallel
|
| 189 |
+
workers only read the cache (no concurrent-download races on the same 100 MB file)."""
|
| 190 |
+
seen: set = set()
|
| 191 |
+
for clip in clips:
|
| 192 |
+
try:
|
| 193 |
+
subset, ep_s = clip["clip_id"].split("#")
|
| 194 |
+
r = _episode_range(cache, subset, int(ep_s))
|
| 195 |
+
key = f"{subset}/{r['data/chunk_index']}/{r['data/file_index']}"
|
| 196 |
+
if key in seen:
|
| 197 |
+
continue
|
| 198 |
+
seen.add(key)
|
| 199 |
+
_ensure(cache, f"{PREFIX}{subset}/data/chunk-{r['data/chunk_index']:03d}/file-{r['data/file_index']:03d}.parquet")
|
| 200 |
+
except Exception:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _run_one(payload: dict) -> dict:
|
| 205 |
+
"""Worker: materialize + retarget one clip (cache already warm). Returns a picklable result."""
|
| 206 |
+
clip = payload["clip"]
|
| 207 |
+
cache, out_root = Path(payload["cache"]), Path(payload["out_root"])
|
| 208 |
+
from retarget import process_clip
|
| 209 |
+
|
| 210 |
+
try:
|
| 211 |
+
subset, ep_s = clip["clip_id"].split("#")
|
| 212 |
+
buf = io.StringIO()
|
| 213 |
+
with contextlib.redirect_stdout(buf):
|
| 214 |
+
mat = _materialize(cache, subset, int(ep_s), out_root)
|
| 215 |
+
res = process_clip(mat, source="lerobot", out_root=str(out_root / "retargeted"))
|
| 216 |
+
if res is None:
|
| 217 |
+
return {"clip_id": clip["clip_id"], "status": "failed", "error": "clip skipped (QA gate or too few valid frames)"}
|
| 218 |
+
txt = buf.getvalue()
|
| 219 |
+
collision = "resolved" if any(k in txt for k in ("moved apart", "still colliding", "pushed")) else "clean"
|
| 220 |
+
return {"clip_id": clip["clip_id"], "status": "done", "res": res, "collision": collision}
|
| 221 |
+
except Exception as e:
|
| 222 |
+
return {"clip_id": clip["clip_id"], "status": "failed", "error": str(e)}
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def main():
|
| 226 |
+
ap = argparse.ArgumentParser()
|
| 227 |
+
ap.add_argument("--selected", required=True)
|
| 228 |
+
ap.add_argument("--report", required=True)
|
| 229 |
+
ap.add_argument("--cache", required=True)
|
| 230 |
+
ap.add_argument("--out-root", required=True)
|
| 231 |
+
ap.add_argument("--limit", type=int, default=3)
|
| 232 |
+
ap.add_argument("--workers", type=int, default=0, help="0 = auto (cores-1); 1 = sequential")
|
| 233 |
+
args = ap.parse_args()
|
| 234 |
+
|
| 235 |
+
from retarget import process_clip
|
| 236 |
+
|
| 237 |
+
selected = json.loads(Path(args.selected).read_text())
|
| 238 |
+
all_clips = selected.get("clips", [])
|
| 239 |
+
clips = all_clips if args.limit <= 0 else all_clips[: args.limit] # limit<=0 → all
|
| 240 |
+
report = Report(Path(args.report), clips, selected.get("teleop", {}))
|
| 241 |
+
cache, out_root = Path(args.cache), Path(args.out_root)
|
| 242 |
+
|
| 243 |
+
workers = args.workers or max(1, min((os.cpu_count() or 2) - 1, len(clips)))
|
| 244 |
+
|
| 245 |
+
# ---- parallel path: process clips concurrently across cores ----
|
| 246 |
+
if workers > 1 and len(clips) > 1:
|
| 247 |
+
_prewarm(cache, clips)
|
| 248 |
+
idx = {c["clip_id"]: i for i, c in enumerate(clips)}
|
| 249 |
+
for i in range(len(clips)):
|
| 250 |
+
report.start(i)
|
| 251 |
+
report.write()
|
| 252 |
+
payloads = [{"clip": c, "cache": str(cache), "out_root": str(out_root)} for c in clips]
|
| 253 |
+
with ProcessPoolExecutor(max_workers=workers) as ex:
|
| 254 |
+
futs = [ex.submit(_run_one, p) for p in payloads]
|
| 255 |
+
for fut in as_completed(futs):
|
| 256 |
+
r = fut.result()
|
| 257 |
+
i = idx[r["clip_id"]]
|
| 258 |
+
if r["status"] == "done":
|
| 259 |
+
report.finish(i, r["res"], r["collision"])
|
| 260 |
+
else:
|
| 261 |
+
report.fail(i, r.get("error", "failed"))
|
| 262 |
+
report.write()
|
| 263 |
+
report.finalize()
|
| 264 |
+
report.write()
|
| 265 |
+
print(f"BATCH DONE ({workers} workers)")
|
| 266 |
+
return
|
| 267 |
+
|
| 268 |
+
# ---- sequential path (workers==1): live per-stage streaming ----
|
| 269 |
+
for i, clip in enumerate(clips):
|
| 270 |
+
report.start(i)
|
| 271 |
+
report.write()
|
| 272 |
+
try:
|
| 273 |
+
subset, ep_s = clip["clip_id"].split("#")
|
| 274 |
+
mat = _materialize(cache, subset, int(ep_s), out_root)
|
| 275 |
+
|
| 276 |
+
state = {"collision": "clean"}
|
| 277 |
+
|
| 278 |
+
def on_line(line, i=i, state=state):
|
| 279 |
+
for mk, key in MARKERS:
|
| 280 |
+
if mk in line:
|
| 281 |
+
report.advance(i, key)
|
| 282 |
+
report.write()
|
| 283 |
+
break
|
| 284 |
+
if "Collision check: clean" in line:
|
| 285 |
+
state["collision"] = "clean"
|
| 286 |
+
elif "moved apart" in line or "still colliding" in line or "pushed" in line:
|
| 287 |
+
state["collision"] = "resolved"
|
| 288 |
+
|
| 289 |
+
old = sys.stdout
|
| 290 |
+
sys.stdout = _Tee(old, on_line)
|
| 291 |
+
try:
|
| 292 |
+
res = process_clip(mat, source="lerobot", out_root=str(out_root / "retargeted"))
|
| 293 |
+
finally:
|
| 294 |
+
sys.stdout = old
|
| 295 |
+
|
| 296 |
+
if res is None:
|
| 297 |
+
raise RuntimeError("clip skipped (QA gate or too few valid frames)")
|
| 298 |
+
report.finish(i, res, state["collision"])
|
| 299 |
+
except Exception as e: # isolate — one bad clip must not abort the batch
|
| 300 |
+
report.fail(i, str(e))
|
| 301 |
+
report.write()
|
| 302 |
+
|
| 303 |
+
report.finalize()
|
| 304 |
+
report.write()
|
| 305 |
+
print("BATCH DONE")
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
main()
|