| |
| """Materialize the ISR-standardized teleop set as a native LeRobot v3.0 dataset. |
| |
| `teleop_std_poc` only emits npz + report artifacts; SmolVLA needs a real dataset. This takes |
| source frames : /workspace/mm_teleop (LeRobot v3.0, SO-101, 30 fps) |
| kept indices : /workspace/std_mm_teleop/out/isr/ep{N}.npz ["keep"] |
| and writes the kept frames — parquet rows AND the matching video frames — as a new v3.0 tree. |
| |
| TIME: ISR frames are non-uniform in real time, so the original timestamps cannot be carried over |
| (LeRobot enforces timestamp ≈ frame_index / fps within tolerance_s). Frames are renumbered onto a |
| uniform grid at the dataset's EFFECTIVE rate (30 fps / mean compression ≈ 10 fps), which keeps |
| episode durations within a few percent of the real ones. Pass --fps 30 to renumber at the source |
| rate instead (episodes then play ~3x fast). |
| |
| Videos are decoded sequentially per camera file (episodes are contiguous and ordered inside them), |
| so each source frame is touched exactly once. |
| """ |
| import argparse |
| import json |
| import os |
| import time |
| from pathlib import Path |
|
|
| os.environ.setdefault("HF_HUB_OFFLINE", "1") |
| os.environ.setdefault("HF_DATASETS_OFFLINE", "1") |
|
|
| import av |
| import numpy as np |
| import pyarrow.parquet as pq |
|
|
| from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
| SRC = Path("/workspace/mm_teleop") |
| ISR = Path("/workspace/std_mm_teleop/out/isr") |
| OUT = Path("/workspace/std_mm_teleop/lerobot_v30") |
|
|
|
|
| class CamReader: |
| """Sequential decoder over one camera's concatenated v3.0 video files.""" |
|
|
| def __init__(self, root: Path, cam: str): |
| self.dir = root / "videos" / cam / "chunk-000" |
| self.file_index = None |
| self.container = None |
| self.iter = None |
|
|
| def _open(self, file_index: int): |
| if self.container is not None: |
| self.container.close() |
| path = self.dir / f"file-{file_index:03d}.mp4" |
| self.container = av.open(str(path)) |
| self.iter = self.container.decode(video=0) |
| self.file_index = file_index |
|
|
| def take(self, file_index: int, count: int, keep_local: set[int]) -> dict[int, np.ndarray]: |
| """Consume `count` frames of that file, returning only the ones in keep_local.""" |
| if file_index != self.file_index: |
| self._open(file_index) |
| out = {} |
| for i in range(count): |
| frame = next(self.iter) |
| if i in keep_local: |
| out[i] = frame.to_ndarray(format="rgb24") |
| return out |
|
|
| def close(self): |
| if self.container is not None: |
| self.container.close() |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--fps", type=int, default=0, help="0 = effective rate (source fps / compression)") |
| ap.add_argument("--repo-id", default="angkul07/std_mm_teleop") |
| ap.add_argument("--out", default=str(OUT)) |
| ap.add_argument("--limit", type=int, default=0, help="debug: only N episodes") |
| a = ap.parse_args() |
|
|
| out_root = Path(a.out) |
| if out_root.exists(): |
| raise SystemExit(f"{out_root} exists — remove it first") |
|
|
| info = json.loads((SRC / "meta" / "info.json").read_text()) |
| src_fps = int(info["fps"]) |
| features = {k: dict(v, shape=tuple(v["shape"])) |
| for k, v in info["features"].items() |
| if k in ("action", "observation.state") or k.startswith("observation.images")} |
| cams = [k for k in features if k.startswith("observation.images")] |
|
|
| ep_meta = pq.read_table(SRC / "meta" / "episodes" / "chunk-000" / "file-000.parquet").to_pydict() |
| n_eps = len(ep_meta["episode_index"]) |
| data = pq.read_table(SRC / "data" / "chunk-000" / "file-000.parquet") |
| state_all = np.array(data["observation.state"].to_pylist(), dtype=np.float32) |
| action_all = np.array(data["action"].to_pylist(), dtype=np.float32) |
| task_by_index = dict(zip(*pq.read_table(SRC / "meta" / "tasks.parquet").to_pydict().values())) |
| task_index_all = np.array(data["task_index"].to_pylist()) |
|
|
| keeps = {} |
| for ep in range(n_eps): |
| keeps[ep] = np.load(ISR / f"ep{ep}.npz")["keep"].astype(int) |
| kept_total = sum(len(v) for v in keeps.values()) |
| src_total = int(info["total_frames"]) |
| compression = src_total / kept_total |
| fps = a.fps or max(1, round(src_fps / compression)) |
| print(f"{src_total} -> {kept_total} frames ({100*kept_total/src_total:.1f}%), " |
| f"compression {compression:.2f}x -> writing at {fps} fps " |
| f"({'effective rate' if not a.fps else 'forced'})") |
|
|
| ds = LeRobotDataset.create( |
| repo_id=a.repo_id, fps=fps, features=features, root=out_root, |
| robot_type=info.get("robot_type"), use_videos=True, |
| image_writer_processes=0, image_writer_threads=4, vcodec="h264", |
| ) |
|
|
| readers = {c: CamReader(SRC, c) for c in cams} |
| t0 = time.time() |
| todo = n_eps if not a.limit else min(a.limit, n_eps) |
| for ep in range(todo): |
| lo, hi = ep_meta["dataset_from_index"][ep], ep_meta["dataset_to_index"][ep] |
| length = hi - lo |
| keep = keeps[ep] |
| keep_set = set(keep.tolist()) |
| frames = {} |
| for cam in cams: |
| fi = ep_meta[f"videos/{cam}/file_index"][ep] |
| frames[cam] = readers[cam].take(fi, length, keep_set) |
| if len(frames[cam]) != len(keep): |
| raise SystemExit(f"ep{ep} {cam}: got {len(frames[cam])} frames, expected {len(keep)}") |
| task = task_by_index[int(task_index_all[lo])] |
| for j in keep: |
| ds.add_frame({ |
| "observation.state": state_all[lo + j], |
| "action": action_all[lo + j], |
| **{c: frames[c][int(j)] for c in cams}, |
| "task": task, |
| }) |
| ds.save_episode() |
| if ep % 10 == 0 or ep == todo - 1: |
| el = time.time() - t0 |
| print(f" ep{ep:>3}: {length} -> {len(keep)} frames | {el:.0f}s elapsed, " |
| f"eta {el/(ep+1)*(todo-ep-1):.0f}s", flush=True) |
|
|
| for r in readers.values(): |
| r.close() |
| print(f"done in {time.time()-t0:.0f}s -> {out_root}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|