File size: 14,906 Bytes
39c7cdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Convert the retargeted YAM HDF5 clips -> a LeRobot v2.1 dataset, using the
downloaded EgoDex egocentric videos as the image observation.

Each retargeted clip (/workspace/retargeted/<cat>/clip_file-YYY_epN/retargeted.hdf5)
becomes one LeRobot episode:
    data/chunk-CCC/episode_EEEEEE.parquet
    videos/chunk-CCC/observation.images.camera/episode_EEEEEE.mp4   (EgoDex clip, hardlinked)

Trajectory -> LeRobot columns (matching angkul07/abc-teleop, also v2.1):
    observation.state[t] = joint_positions[t]            (14-D, absolute)
    action[t]            = joint_positions[t+1]          (next absolute target;
                                                          last frame repeated)
    + timestamp, frame_index, episode_index, index, task_index
The 14 dims are [R_j1..6, R_gripper, L_j1..6, L_gripper]; gripper already
normalized to [0,1], arm joints in radians β€” same convention as abc-teleop.

Frame alignment: retargeting only ever drops frames, so T <= source frames =
video frames. We use T; the EgoDex mp4 (>= T frames, 30 fps, from t=0) lines up.
Video is HARDLINKED (same filesystem) β€” no re-encode, no extra disk.

Usage:
    python to_lerobot_v21.py --out /workspace/retargeted_lerobot [--limit N] [--workers K]
"""
import os, sys, re, glob, json, argparse, subprocess, shutil, random
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import h5py
import multiprocessing as mp

RETGT = os.environ.get("RETGT", "/workspace/retargeted")
EGO   = os.environ.get("EGO", "/workspace/ego")
FPS   = 30
CHUNK = 1000
VIDEO_KEY = "observation.images.camera"
# EgoDex video properties (from ego meta/info.json)
VID_H, VID_W, VID_CODEC, VID_PIXFMT = 1080, 1920, "av1", "yuv420p"
DOF = 14
STATE_NAMES = [f"R_joint{i}" for i in range(1,7)] + ["R_gripper"] + \
              [f"L_joint{i}" for i in range(1,7)] + ["L_gripper"]

OUT = ""            # set in main
IMG_STATS = None    # global image stats dict, set in main
TASK_INDEX = {}     # task string -> index, set in main


# ─────────────────────────────────────────────────────────────────────────────
# discovery / mapping
# ─────────────────────────────────────────────────────────────────────────────
def clip_fileidx(name: str) -> str:
    return re.search(r"(file-\d+)_ep", name).group(1)

def source_video(cat: str, fyy: str) -> str | None:
    hits = glob.glob(f"{EGO}/{cat}/videos/{VIDEO_KEY}/chunk-*/{fyy}.mp4")
    return hits[0] if hits else None

def discover() -> list[dict]:
    """All clips, sorted by (category, file index), assigned a global episode
    index. Returns dicts with hdf5/category/video/task."""
    ego_tasks = ego_task_maps()
    eps = []
    for h in sorted(glob.glob(f"{RETGT}/*/clip_*/retargeted.hdf5")):
        parts = h.split("/")
        cat, name = parts[3], parts[4]
        fyy = clip_fileidx(name)
        eps.append({"hdf5": h, "category": cat, "name": name,
                    "fileidx": int(fyy.split("-")[1]),
                    "video": source_video(cat, fyy),
                    "task": ego_tasks.get((cat, int(fyy.split("-")[1])), "")})
    eps.sort(key=lambda e: (e["category"], e["fileidx"]))
    for i, e in enumerate(eps):
        e["episode_index"] = i
    return eps

def ego_task_maps() -> dict:
    """(category, file_index) -> instruction string, from EgoDex meta/episodes.
    Authoritative and complete (fixes clips whose HDF5 description was empty
    because the meta had not downloaded yet at retarget time)."""
    out = {}
    for cat_dir in sorted(glob.glob(f"{EGO}/*/meta/episodes")):
        cat = cat_dir.split("/")[3]
        for mf in sorted(glob.glob(f"{cat_dir}/chunk-*/*.parquet")):
            try:
                t = pq.read_table(mf, columns=["tasks", "data/file_index"]).to_pydict()
            except Exception:
                continue
            for tasks, fi in zip(t["tasks"], t["data/file_index"]):
                s = (list(tasks) or [""])[0] if tasks is not None else ""
                if ": " in s:                      # "<family>: <sentence>"
                    s = s.split(": ", 1)[1]
                out[(cat, int(fi))] = s
    return out


# ─────────────────────────────────────────────────────────────────────────────
# image stats (global, sampled via ffmpeg β€” no python decoder on this box)
# ─────────────────────────────────────────────────────────────────────────────
def _decode_frames(mp4: str, n: int = 2, size: int = 224) -> list[np.ndarray]:
    try:
        dur = float(subprocess.run(
            ["ffprobe","-v","error","-show_entries","format=duration",
             "-of","csv=p=0",mp4], capture_output=True, text=True).stdout.strip())
    except ValueError:
        return []
    frames = []
    for k in range(n):
        t = dur * (k + 0.5) / n
        r = subprocess.run(
            ["ffmpeg","-v","error","-ss",f"{t:.3f}","-i",mp4,"-frames:v","1",
             "-vf",f"scale={size}:{size}","-f","rawvideo","-pix_fmt","rgb24","-"],
            capture_output=True)
        buf = r.stdout
        if len(buf) == size*size*3:
            frames.append(np.frombuffer(buf, np.uint8).reshape(size, size, 3))
    return frames

def global_image_stats(videos: list[str], n_videos: int = 120) -> dict:
    random.seed(0)
    samp = random.sample(videos, min(n_videos, len(videos)))
    px = []
    for v in samp:
        px.extend(_decode_frames(v))
    if not px:
        # ffmpeg/av1 unavailable β€” neutral [0,1] placeholder so the dataset is
        # still valid; recompute later if image normalization matters.
        z = np.zeros((3,1,1)); return {"min": z.tolist(), "max": (z+1).tolist(),
            "mean": (z+0.5).tolist(), "std": (z+0.25).tolist(), "_placeholder": True}
    arr = np.stack(px).astype(np.float32) / 255.0        # (N,H,W,3) in [0,1]
    def perch(f): return f(arr, axis=(0,1,2)).reshape(3,1,1).tolist()
    return {"min": perch(np.min), "max": perch(np.max),
            "mean": perch(np.mean), "std": perch(np.std), "_placeholder": False,
            "_n_frames": len(px)}


# ─────────────────────────────────────────────────────────────────────────────
# per-episode conversion
# ─────────────────────────────────────────────────────────────────────────────
def _stat(a: np.ndarray) -> dict:
    """LeRobot per-feature stats. a: (L,) or (L,D)."""
    a = np.asarray(a, np.float64)
    if a.ndim == 1:
        a = a[:, None]
    return {"min": a.min(0).tolist(), "max": a.max(0).tolist(),
            "mean": a.mean(0).tolist(), "std": a.std(0).tolist(),
            "count": [a.shape[0]]}

def convert_one(e: dict) -> dict | None:
    try:
        with h5py.File(e["hdf5"], "r") as f:
            q = f["joint_positions"][:].astype(np.float32)      # (T,14)
    except Exception as ex:
        return {"episode_index": e["episode_index"], "error": f"hdf5: {ex}"}
    if e["video"] is None or not os.path.exists(e["video"]):
        return {"episode_index": e["episode_index"], "error": "no video"}

    T = len(q)
    state  = q                                                   # (T,14)
    action = np.vstack([q[1:], q[-1:]])                          # next target
    ts     = (np.arange(T) / FPS).astype(np.float32)
    fidx   = np.arange(T, dtype=np.int64)
    eidx   = np.full(T, e["episode_index"], np.int64)
    tidx   = np.full(T, e["task_index"], np.int64)
    gindex = e["index_offset"] + np.arange(T, dtype=np.int64)

    ci = e["episode_index"] // CHUNK
    # data parquet
    dp = Path(OUT) / f"data/chunk-{ci:03d}/episode_{e['episode_index']:06d}.parquet"
    dp.parent.mkdir(parents=True, exist_ok=True)
    lst = pa.list_(pa.float32(), DOF)
    table = pa.table({
        "observation.state": pa.array(state.tolist(), type=lst),
        "action":            pa.array(action.tolist(), type=lst),
        "timestamp":         pa.array(ts, pa.float32()),
        "frame_index":       pa.array(fidx, pa.int64()),
        "episode_index":     pa.array(eidx, pa.int64()),
        "index":             pa.array(gindex, pa.int64()),
        "task_index":        pa.array(tidx, pa.int64()),
    })
    pq.write_table(table, dp)

    # video: hardlink (same fs) -> canonical path; copy if cross-device
    vp = Path(OUT) / f"videos/chunk-{ci:03d}/{VIDEO_KEY}/episode_{e['episode_index']:06d}.mp4"
    vp.parent.mkdir(parents=True, exist_ok=True)
    if vp.exists() or vp.is_symlink():
        vp.unlink()
    try:
        os.link(e["video"], vp)
    except OSError:
        shutil.copy(e["video"], vp)

    stats = {
        VIDEO_KEY:            {**{k: IMG_STATS[k] for k in ("min","max","mean","std")},
                               "count": [T]},
        "observation.state":  _stat(state),
        "action":             _stat(action),
        "timestamp":          _stat(ts),
        "frame_index":        _stat(fidx),
        "episode_index":      _stat(eidx),
        "index":              _stat(gindex),
        "task_index":         _stat(tidx),
    }
    return {"episode_index": e["episode_index"], "length": T,
            "task": e["task"], "stats": stats}


# ─────────────────────────────────────────────────────────────────────────────
# meta writers
# ─────────────────────────────────────────────────────────────────────────────
def feature_block():
    v = lambda names, shape, dt="float32": {"dtype": dt, "shape": shape, "names": names}
    return {
        VIDEO_KEY: {"dtype": "video", "shape": [VID_H, VID_W, 3],
                    "names": ["height","width","channels"],
                    "info": {"video.height": VID_H, "video.width": VID_W,
                             "video.codec": VID_CODEC, "video.pix_fmt": VID_PIXFMT,
                             "video.is_depth_map": False, "video.fps": FPS,
                             "video.channels": 3, "has_audio": False}},
        "observation.state": v(["state"], [DOF]),
        "action":            v(["action"], [DOF]),
        "timestamp":     v(None, [1]), "frame_index": v(None,[1],"int64"),
        "episode_index": v(None,[1],"int64"), "index": v(None,[1],"int64"),
        "task_index":    v(None,[1],"int64"),
    }

def write_meta(results, total_frames):
    meta = Path(OUT) / "meta"; meta.mkdir(parents=True, exist_ok=True)
    n = len(results)
    n_chunks = (n + CHUNK - 1) // CHUNK
    info = {
        "codebase_version": "v2.1", "robot_type": "yam_bimanual",
        "total_episodes": n, "total_frames": total_frames,
        "total_tasks": len(TASK_INDEX), "total_videos": n,
        "total_chunks": n_chunks, "chunks_size": CHUNK, "fps": FPS,
        "splits": {"train": f"0:{n}"},
        "data_path": "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
        "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
        "features": feature_block(),
    }
    (meta/"info.json").write_text(json.dumps(info, indent=4))
    with (meta/"episodes.jsonl").open("w") as f:
        for r in results:
            f.write(json.dumps({"episode_index": r["episode_index"],
                                "tasks": [r["task"]], "length": r["length"]}) + "\n")
    with (meta/"tasks.jsonl").open("w") as f:
        for task, idx in sorted(TASK_INDEX.items(), key=lambda kv: kv[1]):
            f.write(json.dumps({"task_index": idx, "task": task}) + "\n")
    with (meta/"episodes_stats.jsonl").open("w") as f:
        for r in results:
            f.write(json.dumps({"episode_index": r["episode_index"],
                                "stats": r["stats"]}) + "\n")


def main():
    global OUT, IMG_STATS, TASK_INDEX
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", required=True)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--workers", type=int, default=0)
    args = ap.parse_args()
    OUT = args.out
    Path(OUT).mkdir(parents=True, exist_ok=True)

    eps = discover()
    if args.limit:
        eps = eps[:args.limit]
    print(f"episodes: {len(eps)}", flush=True)

    # task strings -> index (single source of truth: EgoDex meta, fallback category)
    for e in eps:
        if not e["task"]:
            e["task"] = f"{e['category'].replace('_',' ')} pick and place"
    for t in sorted({e["task"] for e in eps}):
        TASK_INDEX[t] = len(TASK_INDEX)
    for e in eps:
        e["task_index"] = TASK_INDEX[e["task"]]
    print(f"unique tasks: {len(TASK_INDEX)}", flush=True)

    # global index offsets (cumulative frame counter) β€” need per-episode T first
    lengths = []
    for e in eps:
        with h5py.File(e["hdf5"], "r") as f:
            lengths.append(int(f.attrs["n_frames"]))
    off = np.concatenate([[0], np.cumsum(lengths)[:-1]])
    for e, o in zip(eps, off):
        e["index_offset"] = int(o)

    print("computing global image stats (ffmpeg sample)...", flush=True)
    IMG_STATS = global_image_stats([e["video"] for e in eps if e["video"]])
    print(f"  image stats placeholder={IMG_STATS.get('_placeholder')} "
          f"mean={np.array(IMG_STATS['mean']).ravel().round(3).tolist()}", flush=True)

    n = args.workers or min(len(eps), os.cpu_count() or 1)
    print(f"converting with {n} workers...", flush=True)
    with mp.Pool(n) as pool:
        results = pool.map(convert_one, eps, chunksize=8)

    ok  = [r for r in results if r and "stats" in r]
    err = [r for r in results if r and "error" in r]
    ok.sort(key=lambda r: r["episode_index"])
    total_frames = sum(r["length"] for r in ok)
    write_meta(ok, total_frames)

    print(f"\nDONE: {len(ok)} episodes, {total_frames} frames, {len(err)} errors")
    for e in err[:10]:
        print("  ERR", e["episode_index"], e["error"])
    print(f"dataset -> {OUT}")


if __name__ == "__main__":
    main()