"""LeRobotDataset v3.0 reader for the T-Rex dataset (/home/wujiayir/public_datasets/trex). Layout (meta/info.json, verified in --check): meta/episodes/chunk-000/file-000.parquet one row per episode: episode_index, length, tasks, caption, motor_primitive, object, target, data/{chunk_index,file_index}, dataset_{from,to}_index and per video key videos//{chunk_index,file_index,from_timestamp,to_timestamp} data/chunk-000/file-NNN.parquet per-frame rows (observation.state[58], action[58], observation.tactile_force[60], timestamp, frame_index, episode_index, index, task_index); an episode lives entirely in one file (data/file_index) videos//chunk-000/file-NNN.mp4 episodes concatenated per file; the frame of episode e at in-episode index k is file frame round(from_timestamp*FPS) + k. file_index differs per camera. State layout: observation.state (58) = [L_arm 7 | L_hand 22 | R_arm 7 | R_hand 22] (schema.py). Timestamps are nominal k/FPS within the episode (checked: |timestamp*30 - frame_index| < 1e-5). Usage (module): ds = TrexDataset() eps = ds.episodes() # list of dict (see Episode fields below) st, ts = ds.get_states(ep_idx) # (58, N) float64, (N,) nominal seconds path, first = ds.frame_location(ep_idx, "head_left") frames = ds.read_frames(ep_idx, "head_left", [0, 10, 20]) # list of BGR uint8 (360, 640, 3) CLI: python trex_data.py --check [--n 5] validate the mapping on episodes from different files (head_left decode) python trex_data.py --list [--available-only] """ import argparse import json import os import sys import time from pathlib import Path import cv2 import numpy as np import pyarrow.parquet as pq DATA_ROOT = Path(os.environ.get("TREX_DATA_ROOT", "/home/wujiayir/public_datasets/trex")) FPS = 30 W, H = 640, 360 CAMS = ("head_left", "left_wrist", "right_wrist") CAM_KEY = {c: f"observation.images.{c}" for c in CAMS} USE_CAMS = ("head_left",) # project scope (2026-10-18): head camera only; wrist cameras kept optional STATE_DIM = 58 ROOT = Path(__file__).resolve().parent.parent EP_CACHE = ROOT / "out/cache/episodes.json" _EP_COLS = ["episode_index", "length", "tasks", "caption", "motor_primitive", "object", "target", "data/chunk_index", "data/file_index", "dataset_from_index", "dataset_to_index"] class TrexDataset: def __init__(self, root=DATA_ROOT, use_cache=True): self.root = Path(root) self.info = json.load(open(self.root / "meta/info.json")) assert self.info["fps"] == FPS and self.info["codebase_version"] == "v3.0", self.info["codebase_version"] self._eps = None self._by_idx = None self.use_cache = use_cache self._data_cache = {} # data file path -> dict(episode_index -> (states, ts)) # ------------------------------------------------------------------ episodes def episodes(self): """List of episode dicts: episode_index, length, task, motor_primitive, object, target, data_file, cams: {cam: {chunk, file, from_ts, to_ts, first_frame}}.""" if self._eps is not None: return self._eps if self.use_cache and EP_CACHE.exists(): self._eps = json.load(open(EP_CACHE)) else: self._eps = self._load_episodes() if self.use_cache: EP_CACHE.parent.mkdir(parents=True, exist_ok=True) json.dump(self._eps, open(EP_CACHE, "w")) self._by_idx = {e["episode_index"]: e for e in self._eps} return self._eps def _load_episodes(self): files = sorted((self.root / "meta/episodes").glob("chunk-*/file-*.parquet")) eps = [] for f in files: t = pq.read_table(f) cols = set(t.column_names) want = [c for c in _EP_COLS if c in cols] for cam in CAMS: for k in ("chunk_index", "file_index", "from_timestamp", "to_timestamp"): want.append(f"videos/{CAM_KEY[cam]}/{k}") d = {c: t.column(c).to_pylist() for c in want} n = t.num_rows for i in range(n): e = { "episode_index": int(d["episode_index"][i]), "length": int(d["length"][i]), "task": (d["caption"][i] if "caption" in d else None) or (d["tasks"][i][0] if d.get("tasks") and d["tasks"][i] else None), "motor_primitive": d.get("motor_primitive", [None] * n)[i], "object": d.get("object", [None] * n)[i], "target": d.get("target", [None] * n)[i], "data_chunk": int(d["data/chunk_index"][i]), "data_file": int(d["data/file_index"][i]), "dataset_from_index": int(d["dataset_from_index"][i]), "cams": {}, } for cam in CAMS: p = f"videos/{CAM_KEY[cam]}/" fts = float(d[p + "from_timestamp"][i]) e["cams"][cam] = { "chunk": int(d[p + "chunk_index"][i]), "file": int(d[p + "file_index"][i]), "from_ts": fts, "to_ts": float(d[p + "to_timestamp"][i]), "first_frame": int(round(fts * FPS)), } eps.append(e) eps.sort(key=lambda e: e["episode_index"]) return eps def episode(self, ep_idx): self.episodes() return self._by_idx[int(ep_idx)] # ------------------------------------------------------------------ videos def video_path(self, ep_idx, cam): c = self.episode(ep_idx)["cams"][cam] return self.root / "videos" / CAM_KEY[cam] / f"chunk-{c['chunk']:03d}" / f"file-{c['file']:03d}.mp4" def frame_location(self, ep_idx, cam): """(video path, index of the episode's first frame in that file). Raises if the file is missing.""" p = self.video_path(ep_idx, cam) if not p.exists(): raise FileNotFoundError(f"episode {ep_idx} {cam}: {p} not downloaded yet") return p, self.episode(ep_idx)["cams"][cam]["first_frame"] def available(self, ep_idx, cams=USE_CAMS): """True if every requested camera's video file exists for this episode (default: head_left only).""" return all(self.video_path(ep_idx, c).exists() for c in cams) def available_episodes(self, cams=USE_CAMS): present = {c: {int(f.stem.split("-")[1]) for f in (self.root / "videos" / CAM_KEY[c]).glob("chunk-*/file-*.mp4")} for c in cams} return [e for e in self.episodes() if all(e["cams"][c]["file"] in present[c] for c in cams)] def read_frames(self, ep_idx, cam, frame_ids, reader=None): """Decode in-episode frame indices (sorted or not) -> list of BGR uint8 arrays, same order as frame_ids.""" path, first = self.frame_location(ep_idx, cam) n = self.episode(ep_idx)["length"] ids = [int(k) for k in frame_ids] for k in ids: if not 0 <= k < n: raise IndexError(f"frame {k} outside episode {ep_idx} (length {n})") rd = reader if reader is not None else VideoReader(path) try: out = {k: rd.get(first + k) for k in sorted(set(ids))} finally: if reader is None: rd.close() return [out[k] for k in ids] def iter_frames(self, ep_idx, cam, start=0, stop=None): """Sequential generator of (k, BGR frame) for in-episode indices start..stop-1.""" path, first = self.frame_location(ep_idx, cam) n = self.episode(ep_idx)["length"] stop = n if stop is None else min(int(stop), n) rd = VideoReader(path) try: rd.seek(first + start) for k in range(start, stop): fr = rd.next() if fr is None: raise RuntimeError(f"decode ended early at frame {k} of episode {ep_idx} {cam}") yield k, fr finally: rd.close() # ------------------------------------------------------------------ states def _data_path(self, ep): return self.root / "data" / f"chunk-{ep['data_chunk']:03d}" / f"file-{ep['data_file']:03d}.parquet" def get_states(self, ep_idx, columns=("observation.state",)): """(58, N) float64 joint positions + (N,) nominal timestamps (seconds, k/FPS) of one episode.""" ep = self.episode(ep_idx) path = self._data_path(ep) t = pq.read_table(path, columns=["episode_index", "frame_index", "timestamp", *columns], filters=[("episode_index", "=", int(ep_idx))]) fi = np.asarray(t.column("frame_index").to_numpy()) order = np.argsort(fi) fi = fi[order] ts = np.asarray(t.column("timestamp").to_numpy(), dtype=np.float64)[order] st = np.stack(t.column(columns[0]).to_numpy(zero_copy_only=False)[order]).astype(np.float64).T if st.shape != (STATE_DIM, ep["length"]) or not np.array_equal(fi, np.arange(ep["length"])): raise ValueError(f"episode {ep_idx}: states {st.shape}, frame_index range {fi.min()}..{fi.max()}, length {ep['length']}") return st, ts def get_actions(self, ep_idx): return self.get_states(ep_idx, columns=("action",)) class VideoReader: """cv2 (ffmpeg) decoder with sequential reads and frame-accurate random access. get(i) seeks only when needed (i != next sequential frame); seeking uses CAP_PROP_POS_FRAMES, which is frame-exact for these constant-rate H.264 files (verified by --check against sequential decode).""" def __init__(self, path): self.path = str(path) self.cap = cv2.VideoCapture(self.path) if not self.cap.isOpened(): raise IOError(f"cannot open {path}") self.n = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) self.wh = (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) self.pos = 0 # index of the next frame returned by next() def seek(self, i): if i != self.pos: self.cap.set(cv2.CAP_PROP_POS_FRAMES, int(i)) self.pos = int(i) def next(self): ok, fr = self.cap.read() if not ok: return None self.pos += 1 return fr def get(self, i): if not 0 <= i < self.n: raise IndexError(f"frame {i} outside {self.path} ({self.n} frames)") self.seek(i) fr = self.next() if fr is None: raise RuntimeError(f"decode failed at frame {i} of {self.path}") return fr def close(self): if self.cap is not None: self.cap.release() self.cap = None def __enter__(self): return self def __exit__(self, *a): self.close() # ---------------------------------------------------------------------- checks def _check(n_eps=5, decode_files=2, seed=0): ds = TrexDataset(use_cache=False) eps = ds.episodes() print(f"{len(eps)} episodes; total frames {sum(e['length'] for e in eps)}") avail = ds.available_episodes() print(f"episodes with head_left video present: {len(avail)}; with all 3 cameras: {len(ds.available_episodes(CAMS))}") for cam in CAMS: files = sorted(f for f in (ds.root / 'videos' / CAM_KEY[cam]).glob('chunk-*/file-*.mp4')) maxf = max(e["cams"][cam]["file"] for e in eps) print(f" {cam}: {len(files)} / {maxf + 1} video files present") # 1. per-file frame-count consistency (sum of lengths == frame count; from_ts contiguous) on a few files per cam rng = np.random.RandomState(seed) for cam in CAMS: by_file = {} for e in eps: by_file.setdefault(e["cams"][cam]["file"], []).append(e) present = [f for f in by_file if (ds.root / 'videos' / CAM_KEY[cam] / 'chunk-000' / f'file-{f:03d}.mp4').exists()] pick = sorted(rng.choice(present, size=min(3, len(present)), replace=False)) for f in pick: lst = sorted(by_file[f], key=lambda e: e["cams"][cam]["from_ts"]) cum, bad = 0, 0 for e in lst: c = e["cams"][cam] bad += int(c["first_frame"] != cum) + int(int(round(c["to_ts"] * FPS)) != cum + e["length"]) cum += e["length"] rd = VideoReader(ds.root / 'videos' / CAM_KEY[cam] / 'chunk-000' / f'file-{f:03d}.mp4') print(f" {cam} file-{f:03d}: {len(lst)} episodes, sum(length)={cum}, mp4 frames={rd.n} {rd.wh}, " f"pointer mismatches={bad} -> {'OK' if bad == 0 and rd.n == cum else 'MISMATCH'}") rd.close() # 2. states on n_eps episodes from different data files files = sorted({e["data_file"] for e in avail}) pick_files = [files[int(i)] for i in np.linspace(0, len(files) - 1, n_eps).round()] picked = [] for f in pick_files: cands = [e for e in avail if e["data_file"] == f] picked.append(cands[rng.randint(len(cands))]) for e in picked: t0 = time.time() st, ts = ds.get_states(e["episode_index"]) dt = np.abs(ts * FPS - np.arange(len(ts))).max() print(f" ep {e['episode_index']:5d} data file-{e['data_file']:03d} {e['motor_primitive']:>18s} len {e['length']:5d}: " f"states {st.shape}, max|ts*30-k|={dt:.1e}, state range [{st.min():.2f},{st.max():.2f}] ({time.time()-t0:.1f}s)") for cam in CAMS: if ds.video_path(e["episode_index"], cam).exists(): p, first = ds.frame_location(e["episode_index"], cam) print(f" {cam:11s} -> {p.name} first_frame {first}") else: print(f" {cam:11s} -> {ds.video_path(e['episode_index'], cam).name} MISSING (not downloaded)") # 3. indexed decode == sequential decode on decode_files files for e in picked[:decode_files]: cam = CAMS[0] path, first = ds.frame_location(e["episode_index"], cam) ks = sorted(set([0, 1, 7, e["length"] // 2, e["length"] - 1])) t0 = time.time() rd = VideoReader(path) rd.seek(first) seq = {} for k in range(e["length"]): fr = rd.next() if k in ks: seq[k] = fr t1 = time.time() rd2 = VideoReader(path) idx = {k: rd2.get(first + k) for k in ks[::-1]} # reverse order forces seeks t2 = time.time() diffs = {k: float(np.abs(seq[k].astype(int) - idx[k].astype(int)).mean()) for k in ks} # also compare against decoding from the very beginning of the file for frame first+ks[0] rd3 = VideoReader(path) fr0 = None for i in range(first + ks[1] + 1): fr0 = rd3.next() d0 = float(np.abs(fr0.astype(int) - seq[ks[1]].astype(int)).mean()) rd.close(); rd2.close(); rd3.close() print(f" decode ep {e['episode_index']} {cam} {path.name} first={first}: sequential {t1-t0:.1f}s, indexed {t2-t1:.1f}s; " f"mean|seq-idx| per frame {diffs}; from-file-start vs seeked (k={ks[1]}): {d0:.3f} -> " f"{'OK' if max(diffs.values()) == 0 and d0 == 0 else 'DIFF'}") def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("--check", action="store_true") ap.add_argument("--list", action="store_true") ap.add_argument("--available-only", action="store_true") ap.add_argument("--n", type=int, default=5) a = ap.parse_args(argv) if a.check: _check(a.n) if a.list: ds = TrexDataset() eps = ds.available_episodes() if a.available_only else ds.episodes() for e in eps: print(e["episode_index"], e["length"], e["motor_primitive"], e["object"], e["task"]) if __name__ == "__main__": main(sys.argv[1:])