File size: 6,239 Bytes
3aa087b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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 ``<out>/samples.json`` and the camera frames as ``<out>/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 <libero_10_image 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 <pusht_image 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())