File size: 14,096 Bytes
167b1c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/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
--------------
::

    <root>/
      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<float>, shape (124,)
    "action",              # list<float>, 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") if not depth_struct["is_bigendian"] else 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<float> -> 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)