#!/usr/bin/env python3 """Example reader for the BarMate LeRobot dataset. Purpose: show every kind of data this dataset contains, how to decode it, and where it lives on disk. Run from the dataset root: python reader.py Or point it at another episode: python reader.py --episode 5 --frame 100 Dependencies ------------ * required: ``duckdb`` and ``numpy`` * optional: ``av`` (or ``opencv-python``) to decode RGB frames from the mp4s The heavy nested-binary columns (depth / pointcloud) trip pyarrow 22.x's "Nested data conversions not implemented for chunked array outputs" check, so this reader uses ``duckdb`` throughout. It handles both the scalar columns and the nested struct columns transparently. Dataset layout -------------- :: / data/chunk-000/episode_XXXXXX.parquet # per-frame data + inline depth/pointcloud bytes videos/chunk-000/ observation.images.cam0_rgb/episode_XXXXXX.mp4 # RGB stored as video (yuv420p) observation.images.cam1_rgb/episode_XXXXXX.mp4 meta/ info.json # feature schema + dataset totals episodes.jsonl # per-episode length + task label episodes_stats.jsonl # per-episode stats over action / state / timestamp tasks.jsonl # task name lookup conversion_metadata.json # provenance: source bag, camera_info, TF, message counts README.md README.md """ from __future__ import annotations import argparse import json import sys from pathlib import Path from typing import Any import duckdb import numpy as np ROOT = Path(__file__).resolve().parent # --------------------------------------------------------------------------- # Column groups # --------------------------------------------------------------------------- # Per-frame scalar / list columns you always want in memory. SCALAR_COLS = [ "timestamp", # float32 (wall time within source rosbag, seconds) "frame_index", # int64 0..len-1 within episode "episode_index", # int64 constant per episode "index", # int64 globally sequential across the whole dataset "task_index", # int64 index into tasks.jsonl "next.done", # bool True on the last frame of the episode ] LIST_COLS = [ "observation.state", # list, shape (124,) "action", # list, shape (76,) ] # Struct columns that reference external mp4 files (RGB video). VIDEO_STRUCT_COLS = [ "observation.images.cam0_rgb", # {path: str, timestamp: float} "observation.images.cam1_rgb", ] # Struct columns with an inline raw16 depth image (H*W*2 bytes little-endian). DEPTH_STRUCT_COLS = [ "observation.depths.cam0", # {data, encoding=16UC1, format=raw16, h, w, step, ...} "observation.depths.cam1", ] # Struct columns with an inline serialized ROS 2 sensor_msgs/PointCloud2 (CDR). POINTCLOUD_STRUCT_COLS = [ "observation.pointclouds.cam0", # scene point cloud from RGB-D cam0 "observation.pointclouds.cam1", # scene point cloud from RGB-D cam1 "observation.pointclouds.left_hand_touch", # tactile "cloud" on left gripper "observation.pointclouds.right_hand_touch", ] ALL_STRUCT_COLS = VIDEO_STRUCT_COLS + DEPTH_STRUCT_COLS + POINTCLOUD_STRUCT_COLS # --------------------------------------------------------------------------- # Meta helpers # --------------------------------------------------------------------------- def load_info(root: Path) -> dict[str, Any]: return json.loads((root / "meta" / "info.json").read_text()) def load_episodes(root: Path) -> list[dict[str, Any]]: with (root / "meta" / "episodes.jsonl").open() as f: return [json.loads(line) for line in f] def load_tasks(root: Path) -> list[dict[str, Any]]: with (root / "meta" / "tasks.jsonl").open() as f: return [json.loads(line) for line in f] def episode_paths(root: Path, episode_index: int) -> dict[str, Path]: ep = f"episode_{episode_index:06d}" return { "parquet": root / "data" / "chunk-000" / f"{ep}.parquet", "cam0_mp4": root / "videos" / "chunk-000" / "observation.images.cam0_rgb" / f"{ep}.mp4", "cam1_mp4": root / "videos" / "chunk-000" / "observation.images.cam1_rgb" / f"{ep}.mp4", } # --------------------------------------------------------------------------- # Nested-payload decoders # --------------------------------------------------------------------------- def decode_depth(depth_struct: dict[str, Any]) -> np.ndarray: """Decode a raw16 depth struct into a ``(H, W)`` uint16 numpy array. Values are millimetres (RealSense convention). 0 means "no reading". """ if depth_struct["format"] != "raw16": raise NotImplementedError(f"unsupported depth format: {depth_struct['format']!r}") h = int(depth_struct["height"]) w = int(depth_struct["width"]) buf = depth_struct["data"] # duckdb returns bytes for BLOB dtype = np.dtype("u2") arr = np.frombuffer(buf, dtype=dtype) if arr.size != h * w: raise ValueError(f"depth size mismatch: {arr.size} != {h*w}") return arr.reshape(h, w) def summarize_pointcloud(pc_struct: dict[str, Any]) -> dict[str, Any]: """Summarize a PointCloud2 struct without a full CDR decode. The ``data`` blob is the serialized ROS 2 message body (``format='cdr'``). Full field parsing needs the sensor_msgs/PointCloud2 CDR schema — decoded via rclpy / rosidl_runtime_py at runtime. For a "just look at the shape" view we only need the metadata that already sits in the struct. """ return { "format": pc_struct["format"], "point_count": int(pc_struct["point_count"]), "point_step_bytes": int(pc_struct["point_step"]), "row_step_bytes": int(pc_struct["row_step"]), "grid_height": int(pc_struct["height"]), "grid_width": int(pc_struct["width"]), "is_dense": bool(pc_struct["is_dense"]), "cdr_payload_bytes": len(pc_struct["data"]) if pc_struct["data"] else 0, } def decode_rgb_frame(mp4_path: Path, ts_seconds: float) -> np.ndarray | None: """Decode a single RGB frame at ``ts_seconds`` from the mp4. Prefers PyAV; falls back to OpenCV. Returns ``None`` and prints a hint if neither is available. """ try: import av # type: ignore except ImportError: av = None if av is not None: with av.open(str(mp4_path)) as container: stream = container.streams.video[0] # seek to nearest keyframe at/before ts, then step forward container.seek(int(ts_seconds * av.time_base), any_frame=False, backward=True) best = None for frame in container.decode(stream): if frame.time is None: continue best = frame if frame.time >= ts_seconds: break return best.to_ndarray(format="rgb24") if best is not None else None try: import cv2 # type: ignore except ImportError: print( " [rgb] neither PyAV nor OpenCV installed; " "install one to decode RGB frames: pip install av (or) pip install opencv-python", file=sys.stderr, ) return None cap = cv2.VideoCapture(str(mp4_path)) try: cap.set(cv2.CAP_PROP_POS_MSEC, ts_seconds * 1000.0) ok, bgr = cap.read() if not ok: return None return bgr[:, :, ::-1].copy() # BGR -> RGB finally: cap.release() # --------------------------------------------------------------------------- # Loaders # --------------------------------------------------------------------------- def load_episode_lightweight(root: Path, episode_index: int) -> dict[str, np.ndarray]: """Load the low-cost columns for a whole episode into numpy arrays. Skips the heavy binary blobs (depth / pointcloud) — those are loaded per-frame by :func:`load_frame` when needed. """ con = duckdb.connect() p = episode_paths(root, episode_index)["parquet"] cols = SCALAR_COLS + LIST_COLS quoted = ", ".join(f'"{c}"' for c in cols) rel = con.execute( f"SELECT {quoted} FROM read_parquet('{p.as_posix()}') ORDER BY frame_index" ) tbl = rel.to_arrow_table() out: dict[str, np.ndarray] = {} for name in cols: col = tbl.column(name) if name in LIST_COLS: # list -> ragged numpy stacked into 2D since sizes are fixed values = col.to_pylist() out[name] = np.asarray(values, dtype=np.float32) else: out[name] = col.to_numpy(zero_copy_only=False) return out def load_frame(root: Path, episode_index: int, frame_index: int) -> dict[str, Any]: """Load one row (every column) for a specific frame.""" p = episode_paths(root, episode_index)["parquet"] con = duckdb.connect() row = con.execute( f"SELECT * FROM read_parquet('{p.as_posix()}') " f"WHERE frame_index = {int(frame_index)} LIMIT 1" ).fetchone() if row is None: raise IndexError(f"episode {episode_index} has no frame {frame_index}") col_names = [d[0] for d in con.description] return dict(zip(col_names, row)) # --------------------------------------------------------------------------- # Demo # --------------------------------------------------------------------------- def _print_header(title: str) -> None: print() print("=" * 72) print(title) print("=" * 72) def run_demo(root: Path, episode_index: int, frame_index: int) -> None: info = load_info(root) episodes = load_episodes(root) tasks = load_tasks(root) _print_header("Dataset overview (meta/info.json + meta/episodes.jsonl)") print(f" robot_type : {info['robot_type']}") print(f" codebase_version : {info['codebase_version']}") print(f" fps : {info['fps']} (control-loop rate the parquet is sampled at)") print(f" total_episodes : {info['total_episodes']}") print(f" total_frames : {info['total_frames']}") print(f" total_videos : {info['total_videos']} (2 per episode: cam0_rgb + cam1_rgb)") print(f" splits : {info['splits']}") print(f" tasks : {[t['task'] for t in tasks]}") lens = [e["length"] for e in episodes] print(f" episode lengths : min={min(lens)} max={max(lens)} mean={sum(lens)/len(lens):.1f}") _print_header("Feature schema (from meta/info.json)") for name, spec in info["features"].items(): shape = spec.get("shape") dtype = spec.get("dtype") extra = "" if spec.get("info"): extra = " " + " ".join(f"{k}={v}" for k, v in spec["info"].items()) print(f" {name:44s} dtype={dtype:11s} shape={shape}{extra}") _print_header(f"Load whole episode {episode_index} (lightweight columns)") ep = load_episode_lightweight(root, episode_index) for name in SCALAR_COLS: a = ep[name] print(f" {name:22s} {a.dtype} shape={a.shape} head={a[:3].tolist()} tail={a[-3:].tolist()}") for name in LIST_COLS: a = ep[name] n_nan = int(np.isnan(a).sum()) note = f" nan_count={n_nan}" if n_nan else "" print(f" {name:22s} {a.dtype} shape={a.shape} min={np.nanmin(a):.4f} max={np.nanmax(a):.4f}{note}") _print_header(f"Load one frame in full — episode {episode_index}, frame {frame_index}") row = load_frame(root, episode_index, frame_index) print(" scalar columns:") for c in SCALAR_COLS: print(f" {c:22s} {row[c]!r}") print(" list columns:") for c in LIST_COLS: v = np.asarray(row[c], dtype=np.float32) n_nan = int(np.isnan(v).sum()) note = f" nan_count={n_nan}" if n_nan else "" print( f" {c:22s} shape={v.shape} min={np.nanmin(v):.4f} max={np.nanmax(v):.4f} " f"first5={v[:5].tolist()}{note}" ) print(" video (RGB) columns — path + timestamp inside the mp4:") for c in VIDEO_STRUCT_COLS: s = row[c] print(f" {c:34s} path={s['path']!r} ts_in_mp4={s['timestamp']:.3f}s") print(" depth columns — raw16 inline blob:") for c in DEPTH_STRUCT_COLS: s = row[c] img = decode_depth(s) finite = img[img > 0] stat = f"min_mm={finite.min()} max_mm={finite.max()}" if finite.size else "all zeros" print( f" {c:34s} format={s['format']} encoding={s['encoding']} " f"H={s['height']} W={s['width']} step={s['step']} bytes={len(s['data'])} " f"decoded={img.dtype}{img.shape} {stat}" ) print(" pointcloud columns — serialized ROS2 PointCloud2 (CDR):") for c in POINTCLOUD_STRUCT_COLS: info_pc = summarize_pointcloud(row[c]) print(f" {c:44s} {info_pc}") _print_header(f"Optional: decode the RGB frame from cam0 at the recorded timestamp") cam0_path = ROOT / row["observation.images.cam0_rgb"]["path"] cam0_ts = float(row["observation.images.cam0_rgb"]["timestamp"]) frame = decode_rgb_frame(cam0_path, cam0_ts) if frame is None: print(f" (skipped — no video backend). Would decode {cam0_path.name} at t={cam0_ts:.3f}s") else: print(f" decoded RGB frame from {cam0_path.name} at t={cam0_ts:.3f}s -> {frame.dtype}{frame.shape}") def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Demo reader for the BarMate LeRobot dataset") p.add_argument("--root", type=Path, default=ROOT, help="Dataset root (default: dir containing this script)") p.add_argument("--episode", type=int, default=0, help="Episode index to load (default: 0)") p.add_argument("--frame", type=int, default=0, help="Frame index within the episode (default: 0)") return p.parse_args() if __name__ == "__main__": ns = parse_args() run_demo(ns.root, ns.episode, ns.frame)