File size: 15,934 Bytes
e9d1713
 
 
 
 
 
 
 
 
 
 
 
 
dc13165
e9d1713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc13165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d1713
 
 
 
dc13165
 
 
 
e9d1713
dc13165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d1713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6064aa
 
 
 
 
e9d1713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc13165
 
 
 
 
 
 
 
 
 
e9d1713
dc13165
 
 
 
e9d1713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc13165
 
 
 
 
 
 
 
e9d1713
 
 
 
 
dc13165
 
 
 
e9d1713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""T3/T4 β€” batch retarget over selected_clips.json with live, human-readable progress.

Runs under .venv-retarget. For each shortlisted clip: materialize a single-episode parquet
β†’ run the real M1..M6 engine β†’ emit per-clip friendly-stage progress + metrics into
transform_report.json (written incrementally so the console can poll it live).
"""
import argparse
import contextlib
import io
import json
import os
import ssl
import sys
import time
import urllib.request
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path

import numpy as np
import pyarrow.compute as pc
import pyarrow.parquet as pq

# macOS Python's urllib has no CA bundle by default β†’ HF downloads fail with
# CERTIFICATE_VERIFY_FAILED. Use certifi's bundle (fall back to unverified only if absent).
try:
    import certifi

    _SSL_CTX = ssl.create_default_context(cafile=certifi.where())
except Exception:
    _SSL_CTX = ssl._create_unverified_context()

REPO = os.environ.get("FD_EGO_REPO", "Kavin60606/EgoDex-PickPlace-10hr")
PREFIX = os.environ.get("FD_EGO_PREFIX", "")  # "" = 10hr root layout; "train/" = griffinlabs
RESOLVE = "https://huggingface.co/datasets/%s/resolve/main/%s"

# customer-facing stage names (replace M1..M6)
STAGES = [
    ("load", "Reading human demo"),
    ("retarget", "Retargeting motion to robot"),
    ("base", "Placing the robot"),
    ("ik", "Solving arm joints (IK)"),
    ("collision", "Checking arm collisions"),
    ("smooth", "Smoothing trajectory"),
    ("qa", "Quality check"),
    ("output", "Saving robot trajectory"),
]
STAGE_KEYS = [k for k, _ in STAGES]
# order matters: match "[M3.5]" before "[M3]"
MARKERS = [("[M6]", "output"), ("[M5]", "qa"), ("[M4]", "smooth"),
           ("[M3.5]", "collision"), ("[M3]", "ik"), ("[M2]", "base"), ("[M1]", "retarget")]


# ── QA verdict: fold FAITHFULNESS (tracking / orientation / arm-collision) into the per-clip
# PASS/WARN/FAIL alongside the motion-quality verdict. Was motion-only, which missed clips that
# move smoothly but don't actually follow the human demo. Thresholds are env-overridable so the
# UI can tune them per run (see config.py for the same defaults). higher value = worse.
def _envf(key: str, default: float) -> float:
    try:
        return float(os.environ.get(key, default))
    except (TypeError, ValueError):
        return default

_QA_IK_WARN = _envf("QA_IK_CM_WARN", 3.0)
_QA_IK_FAIL = _envf("QA_IK_CM_FAIL", 6.0)
_QA_ORI_WARN = _envf("QA_ORI_DEG_WARN", 15.0)
_QA_ORI_FAIL = _envf("QA_ORI_DEG_FAIL", 30.0)
_QA_ARMS_STRICT = os.environ.get("QA_ARMS_STRICT", "0") == "1"
_QA_RANK = {"PASS": 0, "WARN": 1, "FAIL": 2, "?": 0}


def _grade_high(v: float, warn: float, fail: float) -> str:
    """Grade a metric where higher is worse against warn/fail bounds."""
    if v is None:
        return "PASS"
    if v >= fail:
        return "FAIL"
    if v >= warn:
        return "WARN"
    return "PASS"


def _worst(*verdicts: str) -> str:
    return max(verdicts, key=lambda v: _QA_RANK.get(v, 0))

KP_COLS = [f"observation.state.{h}{k}" for h in ("right", "left")
           for k in ("ThumbTip", "IndexFingerTip", "MiddleFingerTip", "Hand")]


def _ensure(cache: Path, rel: str, timeout: int = 30, retries: int = 4) -> Path:
    """Download a repo file to cache, ONCE. Bounded per-request timeout + retries + atomic write so a
    single stalled host connection can't hang the whole run forever (urlopen has no default timeout β€”
    that infinite block was what froze prewarm at 0% CPU)."""
    local = cache / REPO.replace("/", "__") / rel
    if local.exists() and local.stat().st_size > 0:
        return local
    local.parent.mkdir(parents=True, exist_ok=True)
    url = RESOLVE % (REPO, rel)
    last = None
    for attempt in range(retries):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "fd-studio"})
            with urllib.request.urlopen(req, timeout=timeout, context=_SSL_CTX) as r:
                data = r.read()
            tmp = local.with_name(local.name + ".part")
            tmp.write_bytes(data)
            tmp.replace(local)   # atomic β€” a killed/partial download never looks complete
            return local
        except Exception as e:
            last = e
            time.sleep(min(5.0, 1.0 * (attempt + 1)))
    raise RuntimeError(f"download failed after {retries} tries: {rel}: {last}")


def _episode_range(cache: Path, subset: str, ep: int) -> dict:
    base = f"{PREFIX}{subset}"
    cols = ["episode_index", "length", "tasks", "data/chunk_index", "data/file_index",
            "dataset_from_index", "dataset_to_index"]
    for i in range(0, 12):  # episodes/chunk-000/file-000.parquet, file-001, ...
        rel = f"{base}/meta/episodes/chunk-000/file-{i:03d}.parquet"
        try:
            local = _ensure(cache, rel)
        except Exception:
            break
        for row in pq.read_table(local, columns=cols).to_pylist():
            if row["episode_index"] == ep:
                return row
    raise KeyError(f"episode {ep} not found in {subset}")


def _materialize(cache: Path, subset: str, ep: int, out_root: Path) -> str:
    r = _episode_range(cache, subset, ep)
    ci, fi = r["data/chunk_index"], r["data/file_index"]
    data_rel = f"{PREFIX}{subset}/data/chunk-{ci:03d}/file-{fi:03d}.parquet"
    local = _ensure(cache, data_rel)
    # a data file concatenates many episodes; `dataset_from/to_index` are GLOBAL offsets,
    # so filter by the file's own episode_index column instead of slicing.
    table = pq.read_table(local, columns=KP_COLS + ["episode_index"])
    table = table.filter(pc.equal(table["episode_index"], ep)).select(KP_COLS)
    mat = out_root / "materialized" / subset / "data" / "chunk-000"
    mat.mkdir(parents=True, exist_ok=True)
    # Name by SUBSET + episode. The retarget output dir is clip_<this-file-stem>, and episode numbers
    # repeat across categories (tools#157, dice_balls#157, …) β€” naming by episode alone made them
    # collide and OVERWRITE, silently dropping ~79% of clips. Subset uses "_" (never "-"), so
    # prep_lerobot's `clip.split("-")[1]` still recovers the episode from "<subset>__file-000157".
    out = mat / f"{subset}__file-{ep:06d}.parquet"
    pq.write_table(table, out)
    return str(out)


class Report:
    def __init__(self, path: Path, clips: list, teleop: dict):
        self.path = path
        self.teleop = teleop
        self.data = {
            "clips_total": len(clips),
            "clips": [{
                "clip_id": c["clip_id"], "task": c.get("task", ""), "n_frames": c.get("n_frames", 0),
                "status": "pending",
                "stages": [{"key": k, "label": lbl, "status": "pending"} for k, lbl in STAGES],
                "metrics": {}, "error": None, "output": None,
            } for c in clips],
            "match_report": None, "done": False,
        }
        self.write()

    def write(self):
        self.path.write_text(json.dumps(self.data, indent=2))

    def advance(self, i: int, key: str):
        pos = STAGE_KEYS.index(key)
        for j, s in enumerate(self.data["clips"][i]["stages"]):
            s["status"] = "done" if j < pos else ("running" if j == pos else "pending")
        self.data["clips"][i]["status"] = "running"

    def start(self, i: int):
        self.data["clips"][i]["status"] = "running"
        self.data["clips"][i]["stages"][0]["status"] = "running"

    def finish(self, i: int, res: dict, collision: str):
        c = self.data["clips"][i]
        for s in c["stages"]:
            s["status"] = "done"
        c["status"] = "done"
        c["output"] = res.get("output")
        ik_R = round(res.get("ik_R_cm", 0), 2)
        ik_L = round(res.get("ik_L_cm", 0), 2)
        ori_R = round(res.get("ori_R_deg", 0), 1)
        ori_L = round(res.get("ori_L_deg", 0), 1)
        motion = res.get("qa_verdict", "?")            # m5_qa motion-quality verdict
        # grade faithfulness on the worse of the two arms, then combine (worst wins)
        track_g = _grade_high(max(ik_R, ik_L), _QA_IK_WARN, _QA_IK_FAIL)
        ori_g = _grade_high(max(ori_R, ori_L), _QA_ORI_WARN, _QA_ORI_FAIL)
        arms_g = "PASS" if collision == "clean" else ("FAIL" if _QA_ARMS_STRICT else "WARN")
        verdict = _worst(motion, track_g, ori_g, arms_g)
        c["metrics"] = {
            "ik_R_cm": ik_R, "ik_L_cm": ik_L, "ori_R_deg": ori_R, "ori_L_deg": ori_L,
            "collision": collision, "qa": verdict, "qa_motion": motion, "dof": 14,
            # per-component grades so the UI can show WHAT drove the verdict + re-grade live
            "qa_components": {"tracking": track_g, "orientation": ori_g, "arms": arms_g, "motion": motion},
            "n_frames": res.get("n_frames_out", c["n_frames"]),
        }

    def fail(self, i: int, msg: str):
        c = self.data["clips"][i]
        for s in c["stages"]:
            if s["status"] == "running":
                s["status"] = "fail"
        c["status"] = "failed"
        c["error"] = msg

    def finalize(self):
        done = [c for c in self.data["clips"] if c["status"] == "done"]
        failed = sum(1 for c in self.data["clips"] if c["status"] == "failed")
        teleop_hz = int(self.teleop.get("fps") or 30)
        if done:
            iks = [(c["metrics"]["ik_R_cm"] + c["metrics"]["ik_L_cm"]) / 2 for c in done]
            ik_mean = round(float(np.mean(iks)), 2)
            clean = sum(1 for c in done if c["metrics"]["collision"] == "clean")
            fidelity = round(max(0.0, 1 - ik_mean / 10.0), 2)
            clean_rate = round(clean / len(done), 2)
        else:  # nothing succeeded β€” report honestly, not a fake 100%
            ik_mean = fidelity = clean_rate = None
        self.data["match_report"] = {
            "teleop_hz": teleop_hz, "ego_hz": 30,
            "fps_variance": abs(teleop_hz - 30),
            "action_hz_match": teleop_hz == 30,
            "ik_mean_cm": ik_mean,
            "traj_similarity": fidelity,
            "collision_clean_rate": clean_rate,
            "clips_done": len(done), "clips_failed": failed,
        }
        self.data["done"] = True


class _Tee(io.TextIOBase):
    def __init__(self, orig, on_line):
        self.orig, self.on_line, self.buf = orig, on_line, ""

    def write(self, s):
        self.orig.write(s)
        self.buf += s
        while "\n" in self.buf:
            line, self.buf = self.buf.split("\n", 1)
            self.on_line(line)
        return len(s)

    def flush(self):
        self.orig.flush()


def _prewarm(cache: Path, clips: list, workers: int = 24) -> None:
    """Download each clip's episodes-meta + data parquet up front so the retarget workers only read
    the cache. Runs in PARALLEL with bounded per-file timeouts β€” the old sequential + no-timeout
    version froze the whole run for good if a single host connection stalled (0% CPU, flat disk).
    Existence-check + atomic write make concurrent fetches of a shared file safe/idempotent."""
    from concurrent.futures import ThreadPoolExecutor

    def _warm(clip):
        try:
            subset, ep_s = clip["clip_id"].split("#")
            r = _episode_range(cache, subset, int(ep_s))
            _ensure(cache, f"{PREFIX}{subset}/data/chunk-{r['data/chunk_index']:03d}/file-{r['data/file_index']:03d}.parquet")
        except Exception:
            pass   # a clip that can't prefetch is retried lazily in its worker β€” never blocks prewarm

    with ThreadPoolExecutor(max_workers=min(workers, max(1, len(clips)))) as ex:
        list(ex.map(_warm, clips))


def _run_one(payload: dict) -> dict:
    """Worker: materialize + retarget one clip (cache already warm). Returns a picklable result."""
    clip = payload["clip"]
    cache, out_root = Path(payload["cache"]), Path(payload["out_root"])
    from retarget import process_clip

    try:
        subset, ep_s = clip["clip_id"].split("#")
        buf = io.StringIO()
        with contextlib.redirect_stdout(buf):
            mat = _materialize(cache, subset, int(ep_s), out_root)
            res = process_clip(mat, source="lerobot", out_root=str(out_root / "retargeted"))
        if res is None:
            return {"clip_id": clip["clip_id"], "status": "failed", "error": "clip skipped (QA gate or too few valid frames)"}
        txt = buf.getvalue()
        collision = "resolved" if any(k in txt for k in ("moved apart", "still colliding", "pushed")) else "clean"
        return {"clip_id": clip["clip_id"], "status": "done", "res": res, "collision": collision}
    except Exception as e:
        return {"clip_id": clip["clip_id"], "status": "failed", "error": str(e)}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--selected", required=True)
    ap.add_argument("--report", required=True)
    ap.add_argument("--cache", required=True)
    ap.add_argument("--out-root", required=True)
    ap.add_argument("--limit", type=int, default=3)
    ap.add_argument("--workers", type=int, default=0, help="0 = auto (cores-1); 1 = sequential")
    args = ap.parse_args()

    from retarget import process_clip

    selected = json.loads(Path(args.selected).read_text())
    all_clips = selected.get("clips", [])
    clips = all_clips if args.limit <= 0 else all_clips[: args.limit]  # limit<=0 β†’ all
    report = Report(Path(args.report), clips, selected.get("teleop", {}))
    cache, out_root = Path(args.cache), Path(args.out_root)

    workers = args.workers or max(1, min((os.cpu_count() or 2) - 1, len(clips)))

    # ---- parallel path: process clips concurrently across cores ----
    if workers > 1 and len(clips) > 1:
        _prewarm(cache, clips)
        idx = {c["clip_id"]: i for i, c in enumerate(clips)}
        for i in range(len(clips)):
            report.start(i)
        report.write()
        payloads = [{"clip": c, "cache": str(cache), "out_root": str(out_root)} for c in clips]
        with ProcessPoolExecutor(max_workers=workers) as ex:
            futs = [ex.submit(_run_one, p) for p in payloads]
            for fut in as_completed(futs):
                r = fut.result()
                i = idx[r["clip_id"]]
                if r["status"] == "done":
                    report.finish(i, r["res"], r["collision"])
                else:
                    report.fail(i, r.get("error", "failed"))
                report.write()
        report.finalize()
        report.write()
        print(f"BATCH DONE ({workers} workers)")
        return

    # ---- sequential path (workers==1): live per-stage streaming ----
    for i, clip in enumerate(clips):
        report.start(i)
        report.write()
        try:
            subset, ep_s = clip["clip_id"].split("#")
            mat = _materialize(cache, subset, int(ep_s), out_root)

            state = {"collision": "clean"}

            def on_line(line, i=i, state=state):
                for mk, key in MARKERS:
                    if mk in line:
                        report.advance(i, key)
                        report.write()
                        break
                if "Collision check: clean" in line:
                    state["collision"] = "clean"
                elif "moved apart" in line or "still colliding" in line or "pushed" in line:
                    state["collision"] = "resolved"

            old = sys.stdout
            sys.stdout = _Tee(old, on_line)
            try:
                res = process_clip(mat, source="lerobot", out_root=str(out_root / "retargeted"))
            finally:
                sys.stdout = old

            if res is None:
                raise RuntimeError("clip skipped (QA gate or too few valid frames)")
            report.finish(i, res, state["collision"])
        except Exception as e:  # isolate β€” one bad clip must not abort the batch
            report.fail(i, str(e))
        report.write()

    report.finalize()
    report.write()
    print("BATCH DONE")


if __name__ == "__main__":
    main()