Kavin60606 commited on
Commit
39c7cdb
Β·
verified Β·
1 Parent(s): 1d6d9b2

Upload to_lerobot_v21.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. to_lerobot_v21.py +312 -0
to_lerobot_v21.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert the retargeted YAM HDF5 clips -> a LeRobot v2.1 dataset, using the
3
+ downloaded EgoDex egocentric videos as the image observation.
4
+
5
+ Each retargeted clip (/workspace/retargeted/<cat>/clip_file-YYY_epN/retargeted.hdf5)
6
+ becomes one LeRobot episode:
7
+ data/chunk-CCC/episode_EEEEEE.parquet
8
+ videos/chunk-CCC/observation.images.camera/episode_EEEEEE.mp4 (EgoDex clip, hardlinked)
9
+
10
+ Trajectory -> LeRobot columns (matching angkul07/abc-teleop, also v2.1):
11
+ observation.state[t] = joint_positions[t] (14-D, absolute)
12
+ action[t] = joint_positions[t+1] (next absolute target;
13
+ last frame repeated)
14
+ + timestamp, frame_index, episode_index, index, task_index
15
+ The 14 dims are [R_j1..6, R_gripper, L_j1..6, L_gripper]; gripper already
16
+ normalized to [0,1], arm joints in radians β€” same convention as abc-teleop.
17
+
18
+ Frame alignment: retargeting only ever drops frames, so T <= source frames =
19
+ video frames. We use T; the EgoDex mp4 (>= T frames, 30 fps, from t=0) lines up.
20
+ Video is HARDLINKED (same filesystem) β€” no re-encode, no extra disk.
21
+
22
+ Usage:
23
+ python to_lerobot_v21.py --out /workspace/retargeted_lerobot [--limit N] [--workers K]
24
+ """
25
+ import os, sys, re, glob, json, argparse, subprocess, shutil, random
26
+ from pathlib import Path
27
+ import numpy as np
28
+ import pyarrow as pa
29
+ import pyarrow.parquet as pq
30
+ import h5py
31
+ import multiprocessing as mp
32
+
33
+ RETGT = os.environ.get("RETGT", "/workspace/retargeted")
34
+ EGO = os.environ.get("EGO", "/workspace/ego")
35
+ FPS = 30
36
+ CHUNK = 1000
37
+ VIDEO_KEY = "observation.images.camera"
38
+ # EgoDex video properties (from ego meta/info.json)
39
+ VID_H, VID_W, VID_CODEC, VID_PIXFMT = 1080, 1920, "av1", "yuv420p"
40
+ DOF = 14
41
+ STATE_NAMES = [f"R_joint{i}" for i in range(1,7)] + ["R_gripper"] + \
42
+ [f"L_joint{i}" for i in range(1,7)] + ["L_gripper"]
43
+
44
+ OUT = "" # set in main
45
+ IMG_STATS = None # global image stats dict, set in main
46
+ TASK_INDEX = {} # task string -> index, set in main
47
+
48
+
49
+ # ─────────────────────────────────────────────────────────────────────────────
50
+ # discovery / mapping
51
+ # ─────────────────────────────────────────────────────────────────────────────
52
+ def clip_fileidx(name: str) -> str:
53
+ return re.search(r"(file-\d+)_ep", name).group(1)
54
+
55
+ def source_video(cat: str, fyy: str) -> str | None:
56
+ hits = glob.glob(f"{EGO}/{cat}/videos/{VIDEO_KEY}/chunk-*/{fyy}.mp4")
57
+ return hits[0] if hits else None
58
+
59
+ def discover() -> list[dict]:
60
+ """All clips, sorted by (category, file index), assigned a global episode
61
+ index. Returns dicts with hdf5/category/video/task."""
62
+ ego_tasks = ego_task_maps()
63
+ eps = []
64
+ for h in sorted(glob.glob(f"{RETGT}/*/clip_*/retargeted.hdf5")):
65
+ parts = h.split("/")
66
+ cat, name = parts[3], parts[4]
67
+ fyy = clip_fileidx(name)
68
+ eps.append({"hdf5": h, "category": cat, "name": name,
69
+ "fileidx": int(fyy.split("-")[1]),
70
+ "video": source_video(cat, fyy),
71
+ "task": ego_tasks.get((cat, int(fyy.split("-")[1])), "")})
72
+ eps.sort(key=lambda e: (e["category"], e["fileidx"]))
73
+ for i, e in enumerate(eps):
74
+ e["episode_index"] = i
75
+ return eps
76
+
77
+ def ego_task_maps() -> dict:
78
+ """(category, file_index) -> instruction string, from EgoDex meta/episodes.
79
+ Authoritative and complete (fixes clips whose HDF5 description was empty
80
+ because the meta had not downloaded yet at retarget time)."""
81
+ out = {}
82
+ for cat_dir in sorted(glob.glob(f"{EGO}/*/meta/episodes")):
83
+ cat = cat_dir.split("/")[3]
84
+ for mf in sorted(glob.glob(f"{cat_dir}/chunk-*/*.parquet")):
85
+ try:
86
+ t = pq.read_table(mf, columns=["tasks", "data/file_index"]).to_pydict()
87
+ except Exception:
88
+ continue
89
+ for tasks, fi in zip(t["tasks"], t["data/file_index"]):
90
+ s = (list(tasks) or [""])[0] if tasks is not None else ""
91
+ if ": " in s: # "<family>: <sentence>"
92
+ s = s.split(": ", 1)[1]
93
+ out[(cat, int(fi))] = s
94
+ return out
95
+
96
+
97
+ # ─────────────────────────────────────────────────────────────────────────────
98
+ # image stats (global, sampled via ffmpeg β€” no python decoder on this box)
99
+ # ───────────────────────────────────────────────────────────────────────────��─
100
+ def _decode_frames(mp4: str, n: int = 2, size: int = 224) -> list[np.ndarray]:
101
+ try:
102
+ dur = float(subprocess.run(
103
+ ["ffprobe","-v","error","-show_entries","format=duration",
104
+ "-of","csv=p=0",mp4], capture_output=True, text=True).stdout.strip())
105
+ except ValueError:
106
+ return []
107
+ frames = []
108
+ for k in range(n):
109
+ t = dur * (k + 0.5) / n
110
+ r = subprocess.run(
111
+ ["ffmpeg","-v","error","-ss",f"{t:.3f}","-i",mp4,"-frames:v","1",
112
+ "-vf",f"scale={size}:{size}","-f","rawvideo","-pix_fmt","rgb24","-"],
113
+ capture_output=True)
114
+ buf = r.stdout
115
+ if len(buf) == size*size*3:
116
+ frames.append(np.frombuffer(buf, np.uint8).reshape(size, size, 3))
117
+ return frames
118
+
119
+ def global_image_stats(videos: list[str], n_videos: int = 120) -> dict:
120
+ random.seed(0)
121
+ samp = random.sample(videos, min(n_videos, len(videos)))
122
+ px = []
123
+ for v in samp:
124
+ px.extend(_decode_frames(v))
125
+ if not px:
126
+ # ffmpeg/av1 unavailable β€” neutral [0,1] placeholder so the dataset is
127
+ # still valid; recompute later if image normalization matters.
128
+ z = np.zeros((3,1,1)); return {"min": z.tolist(), "max": (z+1).tolist(),
129
+ "mean": (z+0.5).tolist(), "std": (z+0.25).tolist(), "_placeholder": True}
130
+ arr = np.stack(px).astype(np.float32) / 255.0 # (N,H,W,3) in [0,1]
131
+ def perch(f): return f(arr, axis=(0,1,2)).reshape(3,1,1).tolist()
132
+ return {"min": perch(np.min), "max": perch(np.max),
133
+ "mean": perch(np.mean), "std": perch(np.std), "_placeholder": False,
134
+ "_n_frames": len(px)}
135
+
136
+
137
+ # ─────────────────────────────────────────────────────────────────────────────
138
+ # per-episode conversion
139
+ # ─────────────────────────────────────────────────────────────────────────────
140
+ def _stat(a: np.ndarray) -> dict:
141
+ """LeRobot per-feature stats. a: (L,) or (L,D)."""
142
+ a = np.asarray(a, np.float64)
143
+ if a.ndim == 1:
144
+ a = a[:, None]
145
+ return {"min": a.min(0).tolist(), "max": a.max(0).tolist(),
146
+ "mean": a.mean(0).tolist(), "std": a.std(0).tolist(),
147
+ "count": [a.shape[0]]}
148
+
149
+ def convert_one(e: dict) -> dict | None:
150
+ try:
151
+ with h5py.File(e["hdf5"], "r") as f:
152
+ q = f["joint_positions"][:].astype(np.float32) # (T,14)
153
+ except Exception as ex:
154
+ return {"episode_index": e["episode_index"], "error": f"hdf5: {ex}"}
155
+ if e["video"] is None or not os.path.exists(e["video"]):
156
+ return {"episode_index": e["episode_index"], "error": "no video"}
157
+
158
+ T = len(q)
159
+ state = q # (T,14)
160
+ action = np.vstack([q[1:], q[-1:]]) # next target
161
+ ts = (np.arange(T) / FPS).astype(np.float32)
162
+ fidx = np.arange(T, dtype=np.int64)
163
+ eidx = np.full(T, e["episode_index"], np.int64)
164
+ tidx = np.full(T, e["task_index"], np.int64)
165
+ gindex = e["index_offset"] + np.arange(T, dtype=np.int64)
166
+
167
+ ci = e["episode_index"] // CHUNK
168
+ # data parquet
169
+ dp = Path(OUT) / f"data/chunk-{ci:03d}/episode_{e['episode_index']:06d}.parquet"
170
+ dp.parent.mkdir(parents=True, exist_ok=True)
171
+ lst = pa.list_(pa.float32(), DOF)
172
+ table = pa.table({
173
+ "observation.state": pa.array(state.tolist(), type=lst),
174
+ "action": pa.array(action.tolist(), type=lst),
175
+ "timestamp": pa.array(ts, pa.float32()),
176
+ "frame_index": pa.array(fidx, pa.int64()),
177
+ "episode_index": pa.array(eidx, pa.int64()),
178
+ "index": pa.array(gindex, pa.int64()),
179
+ "task_index": pa.array(tidx, pa.int64()),
180
+ })
181
+ pq.write_table(table, dp)
182
+
183
+ # video: hardlink (same fs) -> canonical path; copy if cross-device
184
+ vp = Path(OUT) / f"videos/chunk-{ci:03d}/{VIDEO_KEY}/episode_{e['episode_index']:06d}.mp4"
185
+ vp.parent.mkdir(parents=True, exist_ok=True)
186
+ if vp.exists() or vp.is_symlink():
187
+ vp.unlink()
188
+ try:
189
+ os.link(e["video"], vp)
190
+ except OSError:
191
+ shutil.copy(e["video"], vp)
192
+
193
+ stats = {
194
+ VIDEO_KEY: {**{k: IMG_STATS[k] for k in ("min","max","mean","std")},
195
+ "count": [T]},
196
+ "observation.state": _stat(state),
197
+ "action": _stat(action),
198
+ "timestamp": _stat(ts),
199
+ "frame_index": _stat(fidx),
200
+ "episode_index": _stat(eidx),
201
+ "index": _stat(gindex),
202
+ "task_index": _stat(tidx),
203
+ }
204
+ return {"episode_index": e["episode_index"], "length": T,
205
+ "task": e["task"], "stats": stats}
206
+
207
+
208
+ # ───────────────���─────────────────────────────────────────────────────────────
209
+ # meta writers
210
+ # ─────────────────────────────────────────────────────────────────────────────
211
+ def feature_block():
212
+ v = lambda names, shape, dt="float32": {"dtype": dt, "shape": shape, "names": names}
213
+ return {
214
+ VIDEO_KEY: {"dtype": "video", "shape": [VID_H, VID_W, 3],
215
+ "names": ["height","width","channels"],
216
+ "info": {"video.height": VID_H, "video.width": VID_W,
217
+ "video.codec": VID_CODEC, "video.pix_fmt": VID_PIXFMT,
218
+ "video.is_depth_map": False, "video.fps": FPS,
219
+ "video.channels": 3, "has_audio": False}},
220
+ "observation.state": v(["state"], [DOF]),
221
+ "action": v(["action"], [DOF]),
222
+ "timestamp": v(None, [1]), "frame_index": v(None,[1],"int64"),
223
+ "episode_index": v(None,[1],"int64"), "index": v(None,[1],"int64"),
224
+ "task_index": v(None,[1],"int64"),
225
+ }
226
+
227
+ def write_meta(results, total_frames):
228
+ meta = Path(OUT) / "meta"; meta.mkdir(parents=True, exist_ok=True)
229
+ n = len(results)
230
+ n_chunks = (n + CHUNK - 1) // CHUNK
231
+ info = {
232
+ "codebase_version": "v2.1", "robot_type": "yam_bimanual",
233
+ "total_episodes": n, "total_frames": total_frames,
234
+ "total_tasks": len(TASK_INDEX), "total_videos": n,
235
+ "total_chunks": n_chunks, "chunks_size": CHUNK, "fps": FPS,
236
+ "splits": {"train": f"0:{n}"},
237
+ "data_path": "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
238
+ "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
239
+ "features": feature_block(),
240
+ }
241
+ (meta/"info.json").write_text(json.dumps(info, indent=4))
242
+ with (meta/"episodes.jsonl").open("w") as f:
243
+ for r in results:
244
+ f.write(json.dumps({"episode_index": r["episode_index"],
245
+ "tasks": [r["task"]], "length": r["length"]}) + "\n")
246
+ with (meta/"tasks.jsonl").open("w") as f:
247
+ for task, idx in sorted(TASK_INDEX.items(), key=lambda kv: kv[1]):
248
+ f.write(json.dumps({"task_index": idx, "task": task}) + "\n")
249
+ with (meta/"episodes_stats.jsonl").open("w") as f:
250
+ for r in results:
251
+ f.write(json.dumps({"episode_index": r["episode_index"],
252
+ "stats": r["stats"]}) + "\n")
253
+
254
+
255
+ def main():
256
+ global OUT, IMG_STATS, TASK_INDEX
257
+ ap = argparse.ArgumentParser()
258
+ ap.add_argument("--out", required=True)
259
+ ap.add_argument("--limit", type=int, default=0)
260
+ ap.add_argument("--workers", type=int, default=0)
261
+ args = ap.parse_args()
262
+ OUT = args.out
263
+ Path(OUT).mkdir(parents=True, exist_ok=True)
264
+
265
+ eps = discover()
266
+ if args.limit:
267
+ eps = eps[:args.limit]
268
+ print(f"episodes: {len(eps)}", flush=True)
269
+
270
+ # task strings -> index (single source of truth: EgoDex meta, fallback category)
271
+ for e in eps:
272
+ if not e["task"]:
273
+ e["task"] = f"{e['category'].replace('_',' ')} pick and place"
274
+ for t in sorted({e["task"] for e in eps}):
275
+ TASK_INDEX[t] = len(TASK_INDEX)
276
+ for e in eps:
277
+ e["task_index"] = TASK_INDEX[e["task"]]
278
+ print(f"unique tasks: {len(TASK_INDEX)}", flush=True)
279
+
280
+ # global index offsets (cumulative frame counter) β€” need per-episode T first
281
+ lengths = []
282
+ for e in eps:
283
+ with h5py.File(e["hdf5"], "r") as f:
284
+ lengths.append(int(f.attrs["n_frames"]))
285
+ off = np.concatenate([[0], np.cumsum(lengths)[:-1]])
286
+ for e, o in zip(eps, off):
287
+ e["index_offset"] = int(o)
288
+
289
+ print("computing global image stats (ffmpeg sample)...", flush=True)
290
+ IMG_STATS = global_image_stats([e["video"] for e in eps if e["video"]])
291
+ print(f" image stats placeholder={IMG_STATS.get('_placeholder')} "
292
+ f"mean={np.array(IMG_STATS['mean']).ravel().round(3).tolist()}", flush=True)
293
+
294
+ n = args.workers or min(len(eps), os.cpu_count() or 1)
295
+ print(f"converting with {n} workers...", flush=True)
296
+ with mp.Pool(n) as pool:
297
+ results = pool.map(convert_one, eps, chunksize=8)
298
+
299
+ ok = [r for r in results if r and "stats" in r]
300
+ err = [r for r in results if r and "error" in r]
301
+ ok.sort(key=lambda r: r["episode_index"])
302
+ total_frames = sum(r["length"] for r in ok)
303
+ write_meta(ok, total_frames)
304
+
305
+ print(f"\nDONE: {len(ok)} episodes, {total_frames} frames, {len(err)} errors")
306
+ for e in err[:10]:
307
+ print(" ERR", e["episode_index"], e["error"])
308
+ print(f"dataset -> {OUT}")
309
+
310
+
311
+ if __name__ == "__main__":
312
+ main()