#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2026 Tenstorrent USA, Inc. # SPDX-License-Identifier: Apache-2.0 """Pick evaluation frames from a local LeRobot v3 dataset (parquet with embedded images). Writes ``/samples.json`` and the camera frames as ``/frames/*.png|jpg`` (the bytes stored in the dataset, unchanged), for ``scripts/eval_agreement.py``. Reads only data files that are present locally (download them first, e.g. with ``huggingface_hub.hf_hub_download``); needs only ``pyarrow``. Run it with ``python -I`` on downloaded data. # LIBERO-10: the third-person camera in the two third-person slots, the wrist camera in slot 3 python -I scripts/extract_samples.py --dataset-dir --out samples_libero \\ --views observation.images.image,observation.images.image,observation.images.wrist_image \\ --per-episode 10 # Push-T: its single camera in all three slots; ground-truth actions kept for an MAE metric python -I scripts/extract_samples.py --dataset-dir --out samples_pusht \\ --views observation.image,observation.image,observation.image --per-episode 5 --max-episodes 10 Frames are chosen evenly over each episode among the frames that have a full action chunk (``--horizon`` future actions, 30 by default) inside the same episode. """ from __future__ import annotations import argparse import hashlib import json from pathlib import Path import pyarrow.parquet as pq def _ext(b: bytes) -> str: if b[:8] == b"\x89PNG\r\n\x1a\n": return "png" if b[:3] == b"\xff\xd8\xff": return "jpg" raise ValueError("frame is neither PNG nor JPEG") def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--dataset-dir", required=True, type=Path, help="local LeRobot v3 dataset root (meta/, data/)") ap.add_argument("--out", required=True, type=Path) ap.add_argument("--views", required=True, help="3 comma-separated image columns for slots image,image2,image3") ap.add_argument("--state-key", default="observation.state") ap.add_argument("--action-key", default="action") ap.add_argument("--per-episode", type=int, default=10, help="frames per episode") ap.add_argument("--max-episodes", type=int, default=0, help="0 = every episode in the local data files") ap.add_argument("--horizon", type=int, default=30, help="future actions kept per frame (the chunk size)") ap.add_argument("--source", default="", help="free-text provenance stored in samples.json (repo@revision)") args = ap.parse_args() views = [v.strip() for v in args.views.split(",")] if len(views) != 3: ap.error("--views needs exactly 3 columns") root = args.dataset_dir # meta/tasks.parquet: the task string is the "task" column, or the pandas index (older exports) tasks = {} for r in pq.read_table(root / "meta" / "tasks.parquet").to_pylist(): text = r.get("task", r.get("__index_level_0__")) if not isinstance(text, str): raise SystemExit(f"cannot read the task string from meta/tasks.parquet row {r}") tasks[r["task_index"]] = text files = sorted((root / "data").glob("chunk-*/file-*.parquet")) if not files: raise SystemExit(f"no data files under {root / 'data'}") out = args.out (out / "frames").mkdir(parents=True, exist_ok=True) samples = [] episodes_used = 0 cols = sorted(set(views)) + [args.state_key, args.action_key, "episode_index", "frame_index", "index", "task_index"] for f in files: t = pq.read_table(f, columns=cols) meta = t.select(["episode_index", "frame_index", "index", "task_index"]).to_pylist() by_ep: dict[int, list[int]] = {} for row_i, r in enumerate(meta): by_ep.setdefault(r["episode_index"], []).append(row_i) for ep in sorted(by_ep): if args.max_episodes and episodes_used >= args.max_episodes: break rows = sorted(by_ep[ep], key=lambda i: meta[i]["frame_index"]) n_ok = len(rows) - args.horizon + 1 # frames with a full chunk of future actions if n_ok <= 0: continue k = min(args.per_episode, n_ok) picks = [rows[round(j * (n_ok - 1) / max(1, k - 1))] for j in range(k)] if k > 1 else [rows[0]] actions_ep = t.column(args.action_key).to_pylist() for row_i in picks: pos = rows.index(row_i) chunk = [actions_ep[rows[pos + h]] for h in range(args.horizon)] files_for_views = [] for col in views: b = t.column(col)[row_i].as_py()["bytes"] name = f"{meta[row_i]['index']:08d}_{col.replace('.', '_')}.{_ext(b)}" p = out / "frames" / name if not p.exists(): p.write_bytes(b) files_for_views.append(f"frames/{name}") samples.append( dict( id=len(samples), episode_index=meta[row_i]["episode_index"], frame_index=meta[row_i]["frame_index"], index=meta[row_i]["index"], task=tasks[meta[row_i]["task_index"]], state=[float(x) for x in t.column(args.state_key)[row_i].as_py()], gt_actions=[[float(x) for x in a] for a in chunk], images=files_for_views, ) ) episodes_used += 1 digest = hashlib.sha256(json.dumps(samples, sort_keys=True).encode()).hexdigest() doc = dict(source=args.source, dataset_dir_name=root.name, views=views, horizon=args.horizon, per_episode=args.per_episode, episodes=episodes_used, n=len(samples), sha256=digest, samples=samples) (out / "samples.json").write_text(json.dumps(doc, indent=1)) print(f"{len(samples)} samples from {episodes_used} episodes -> {out}/samples.json (sha256 {digest[:16]})") return 0 if __name__ == "__main__": raise SystemExit(main())