File size: 14,595 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert LeRobot v3.0 datasets (several episodes per parquet and per video file) into training shards, for
fine-tuning on the target robot. Same output format, episode filters, resampling, image size and normalization as
step 2 (scripts/preprocess.py), so pretraining and fine-tuning read data the same way.

    python scripts/convert_v3.py --raw ~/pop/realworld/raw --out ~/pop/realworld/shards \
        --datasets tmhoanggg/so101-fold-towel,tmhoanggg/so101-drawer-v3 --agent front --wrist wrist

<raw>/<name>/ is a local copy of the dataset (hf download --local-dir), <name> the part after the "/". Cameras are
chosen by name (observation.images.<agent>, observation.images.<wrist>): on one's own rig the names are known.
Joint names may carry LeRobot's ".pos" suffix.

Output: <out>/train/<id>/ and <out>/val/<id>/ (shard format of scripts/preprocess.py; --val episodes per dataset,
spread evenly over the recording order, go to val), each with index.json. Normalization statistics come from the
train episodes and are copied into val. <out>/report.json lists frames, episodes and drops per dataset.
"""
import argparse
import glob
import json
import math
import multiprocessing as mp
import os
import shutil
import sys
import time

import av
import numpy as np
import pyarrow.parquet as pq

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from popt.common import ARM, JOINTS, read_json, write_json  # noqa: E402

A = None


class VideoError(Exception):
    pass


def joints_ok(names) -> bool:
    if isinstance(names, dict):
        names = names.get("motors")
    return isinstance(names, list) and len(names) == 6 and all(
        str(n).removesuffix(".pos").split(".")[-1].endswith(j) for n, j in zip(names, JOINTS))


def decode_window(path: str, t0: float, idx: np.ndarray, size: int, fps: float) -> np.ndarray:
    """Frames idx (episode-relative native indices, sorted) of the episode that starts at t0 seconds in a video file
    holding several episodes, resized to size x size RGB. Frame j is the frame whose time is t0 + j / fps."""
    want = set(int(j) for j in idx)
    out = {}
    try:
        with av.open(path) as c:
            s = c.streams.video[0]
            s.thread_type = "AUTO"
            s.codec_context.thread_count = A.decode_threads
            c.seek(int(max(t0 - 1.0, 0.0) / s.time_base), stream=s, backward=True, any_frame=False)
            for fr in c.decode(s):
                if fr.time is None:
                    continue
                x = (fr.time - t0) * fps
                j = int(round(x))
                if j < 0:
                    continue
                if j > idx[-1]:
                    break
                if abs(x - j) > 0.25:
                    raise VideoError("video_time_mismatch")
                if j in want and j not in out:
                    out[j] = fr.to_ndarray(width=size, height=size, format="rgb24", interpolation="AREA")
    except VideoError:
        raise
    except Exception as e:  # noqa: BLE001
        raise VideoError("video_error") from e
    if len(out) != len(want):
        raise VideoError("video_missing_frames")
    return np.stack([out[int(j)] for j in idx])


def frames_of(job):
    """Worker: decode one episode's agent and wrist frames."""
    raw_d, info, ep, idx, agent, wrist = job
    fps = float(info["fps"])

    def path(key):
        return os.path.join(raw_d, info["video_path"].format(video_key=key, chunk_index=ep[f"videos/{key}/chunk_index"],
                                                            file_index=ep[f"videos/{key}/file_index"]))
    try:
        ia = decode_window(path(agent), ep[f"videos/{agent}/from_timestamp"], idx, A.res, fps)
        iw = decode_window(path(wrist), ep[f"videos/{wrist}/from_timestamp"], idx, A.res, fps) if wrist else None
        return ep["episode_index"], ia, iw, None
    except VideoError as err:
        return ep["episode_index"], None, None, str(err)


def episodes_meta(raw_d: str) -> list[dict]:
    rows = []
    for f in sorted(glob.glob(os.path.join(raw_d, "meta", "episodes", "chunk-*", "file-*.parquet"))):
        t = pq.read_table(f, columns=None)
        cols = [c for c in t.column_names if not c.startswith("stats/")]
        t = t.select(cols)
        rows += t.to_pylist()
    return sorted(rows, key=lambda r: r["episode_index"])


def load_data(raw_d: str, info: dict, eps: list[dict]) -> dict:
    """episode_index -> (state, action, timestamp) at the native rate."""
    files = sorted({(e["data/chunk_index"], e["data/file_index"]) for e in eps})
    out = {}
    for ci, fi in files:
        t = pq.read_table(os.path.join(raw_d, info["data_path"].format(chunk_index=ci, file_index=fi)),
                          columns=["episode_index", "frame_index", "timestamp", "observation.state", "action"])
        e_ix = t.column("episode_index").to_numpy()
        f_ix = t.column("frame_index").to_numpy()
        ts = t.column("timestamp").to_numpy().astype(np.float64)
        S = np.stack(t.column("observation.state").to_numpy(zero_copy_only=False)).astype(np.float64)
        Ac = np.stack(t.column("action").to_numpy(zero_copy_only=False)).astype(np.float64)
        for e in np.unique(e_ix):
            m = e_ix == e
            order = np.argsort(f_ix[m])
            out[int(e)] = (S[m][order], Ac[m][order], ts[m][order])
    return out


def filter_episodes(eps, data, fps, tf):
    """Pass 1 of scripts/preprocess.py, same rules and thresholds."""
    min_frames = max(A.chunk, math.ceil(A.min_seconds * tf))
    dropped, cand = {}, []
    for ep in eps:
        e = ep["episode_index"]
        if e not in data:
            dropped[e] = "bad_parquet"
            continue
        S, Ac, ts = data[e]
        n = len(S)
        if n != ep["length"]:
            dropped[e] = "length_mismatch"
            continue
        if n < 2 or not (np.isfinite(S).all() and np.isfinite(Ac).all() and np.isfinite(ts).all()):
            dropped[e] = "non_finite" if n >= 2 else "too_short"
            continue
        dt = np.diff(ts)
        if (dt <= 0).any() or dt.max() > 2.5 / fps:
            dropped[e] = "timestamps"
            continue
        if (n - 1) / fps > A.max_seconds:
            dropped[e] = "too_long"
            continue
        m = int(math.floor((n - 1) * tf / fps + 1e-9)) + 1
        idx = np.minimum(np.round(np.arange(m) * fps / tf).astype(np.int64), n - 1)
        if m < min_frames:
            dropped[e] = "too_short"
            continue
        cand.append({"ep": ep, "e": e, "idx": idx, "S": S, "A": Ac,
                     "arm_range": float((S[:, ARM].max(0) - S[:, ARM].min(0)).max()),
                     "step_s": np.abs(np.diff(S[:, ARM], axis=0)).max(0),
                     "step_a": np.abs(np.diff(Ac[:, ARM], axis=0)).max(0)})
    if cand:
        allS = np.concatenate([c["S"][:, ARM] for c in cand])
        p1, p99 = np.percentile(allS, [1, 99], axis=0)
        jrange = np.maximum(np.maximum(p99 - p1, 0.25 * (p99 - p1).max()), 1e-6)
        med = float(np.median([c["arm_range"] for c in cand]))
        keep = []
        for c in cand:
            if c["arm_range"] < A.static_frac * med:
                dropped[c["e"]] = "static"
            elif (c["step_s"] > A.jump_frac * jrange).any() or (c["step_a"] > A.jump_frac * jrange).any():
                dropped[c["e"]] = "jump"
            else:
                keep.append(c)
        cand = keep
    return cand, dropped


def write_shard(d: str, cands: list, frames: dict, stats: dict, meta: dict):
    tmp = d + ".tmp"
    shutil.rmtree(tmp, ignore_errors=True)
    os.makedirs(tmp)
    eps, S_out, A_out, E_out, start = [], [], [], [], 0
    with open(os.path.join(tmp, "agent.u8"), "wb") as fa, open(os.path.join(tmp, "wrist.u8"), "wb") as fw:
        for c in cands:
            ia, iw = frames[c["e"]]
            fa.write(ia.tobytes())
            fw.write(iw.tobytes())
            L = len(c["idx"])
            eps.append({"source_episode": c["e"], "start": start, "length": L, "task": "; ".join(map(str, c["ep"].get("tasks") or [])) or None})
            S_out.append(c["S"][c["idx"]]); A_out.append(c["A"][c["idx"]]); E_out.append(np.full(L, len(eps) - 1, np.int32))
            start += L
    S, Ac = np.concatenate(S_out), np.concatenate(A_out)
    np.savez(os.path.join(tmp, "arrays.npz"), state=S.astype(np.float32), action=Ac.astype(np.float32), ep=np.concatenate(E_out))
    write_json(os.path.join(tmp, "episodes.json"), eps)
    write_json(os.path.join(tmp, "stats.json"), stats if stats is not None else PRE.norm_stats(S, Ac, eps))
    meta = meta | {"frames": int(len(S)), "episodes": len(eps), "source_episodes": [c["e"] for c in cands],
                   "hours_resampled": round(len(S) / A.target_fps / 3600, 3)}
    write_json(os.path.join(tmp, "meta.json"), meta)
    open(os.path.join(tmp, "DONE"), "w").close()
    shutil.rmtree(d, ignore_errors=True)
    os.replace(tmp, d)
    return read_json(os.path.join(d, "stats.json")), meta


def convert(name: str, pool) -> dict:
    raw_d = os.path.join(A.raw, name.split("/")[-1])
    info = read_json(os.path.join(raw_d, "meta", "info.json"))
    assert str(info.get("codebase_version", "")).startswith("v3"), info.get("codebase_version")
    feats = info["features"]
    assert joints_ok(feats["observation.state"].get("names")) and joints_ok(feats["action"].get("names")), \
        "state and action must be the 6 standard joints"
    agent, wrist = f"observation.images.{A.agent}", f"observation.images.{A.wrist}"
    for k in (agent, wrist):
        assert k in feats and feats[k]["dtype"] == "video", f"{name}: no video {k}"
    fps, tf = float(info["fps"]), A.target_fps
    assert fps >= tf, (fps, tf)
    eps = episodes_meta(raw_d)
    data = load_data(raw_d, info, eps)
    cands, dropped = filter_episodes(eps, data, fps, tf)
    t0 = time.time()
    frames = {}
    for e, ia, iw, err in pool.imap(frames_of, [(raw_d, info, c["ep"], c["idx"], agent, wrist) for c in cands], chunksize=1):
        if err:
            dropped[e] = err
        else:
            frames[e] = (ia, iw)
    cands = [c for c in cands if c["e"] in frames]
    # validation split: A.val episodes spread evenly over the recording order
    vi = set(np.unique(np.linspace(0, len(cands) - 1, A.val).round().astype(int)).tolist()) if A.val and len(cands) > A.val else set()
    tr = [c for k, c in enumerate(cands) if k not in vi]
    va = [c for k, c in enumerate(cands) if k in vi]
    sid = name.replace("/", "__")
    base = {"dataset": name, "status": "kept", "source_fps": fps, "target_fps": tf, "res": A.res, "chunk": A.chunk,
            "agent": agent, "wrist": wrist, "revision": A.revisions.get(name), "codebase_version": info["codebase_version"],
            "robot_type": info.get("robot_type"), "joint_names": feats["observation.state"].get("names"),
            "camera_names": {agent.split(".")[-1]: A.agent, wrist.split(".")[-1]: A.wrist},
            "episodes_dropped": PRE.by_reason(dropped), "dropped_episode_list": {str(k): v for k, v in sorted(dropped.items())}}
    stats, mt = write_shard(os.path.join(A.out, "train", sid), tr, frames, None, base | {"split": "train"})
    mv = write_shard(os.path.join(A.out, "val", sid), va, frames, stats, base | {"split": "val"})[1] if va else None
    r = {"dataset": name, "episodes_source": len(eps), "train_episodes": mt["episodes"], "train_frames": mt["frames"],
         "val_episodes": mv["episodes"] if mv else 0, "val_frames": mv["frames"] if mv else 0,
         "episodes_dropped": PRE.by_reason(dropped), "tasks": sorted({str(t) for e in eps for t in (e.get("tasks") or [])}),
         "decode_seconds": round(time.time() - t0, 1)}
    print(json.dumps(r), flush=True)
    return r


def index(split_dir: str):
    shards = []
    for done in sorted(glob.glob(os.path.join(split_dir, "*", "DONE"))):
        m = read_json(os.path.join(os.path.dirname(done), "meta.json"))
        shards.append({"dir": os.path.basename(os.path.dirname(done)), "dataset": m["dataset"], "frames": m["frames"],
                       "episodes": m["episodes"], "has_wrist": True})
    write_json(os.path.join(split_dir, "index.json"), {"revision": A.revisions, "target_fps": A.target_fps, "res": A.res,
                                                      "chunk": A.chunk, "frames": sum(s["frames"] for s in shards),
                                                      "shards": shards})


PRE = None


def main():
    global A, PRE
    p = argparse.ArgumentParser()
    p.add_argument("--raw", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--datasets", required=True, help="comma-separated <user>/<name>")
    p.add_argument("--revisions", default="", help="file with '<name> <sha>' lines, recorded in the output")
    p.add_argument("--agent", default="front")
    p.add_argument("--wrist", default="wrist")
    p.add_argument("--val", type=int, default=5, help="validation episodes per dataset")
    p.add_argument("--workers", type=int, default=16)
    p.add_argument("--decode-threads", type=int, default=1)
    p.add_argument("--target-fps", type=int, default=int(os.environ.get("TARGET_FPS", 10)))
    p.add_argument("--res", type=int, default=int(os.environ.get("RES", 256)))
    p.add_argument("--chunk", type=int, default=int(os.environ.get("CHUNK", 16)))
    p.add_argument("--min-seconds", type=float, default=2.0)
    p.add_argument("--max-seconds", type=float, default=600.0)
    p.add_argument("--static-frac", type=float, default=0.1)
    p.add_argument("--jump-frac", type=float, default=0.5)
    A = p.parse_args()
    import scripts.preprocess as pre  # norm_stats and by_reason, unchanged
    pre.A = A
    PRE = pre
    revs = {}
    if A.revisions:
        for line in open(A.revisions):
            if line.strip():
                n, sha = line.split()
                revs[n] = sha
    names = [s for s in A.datasets.split(",") if s]
    A.revisions = {n: revs.get(n.split("/")[-1], revs.get(n)) for n in names}
    for s in ("train", "val"):
        os.makedirs(os.path.join(A.out, s), exist_ok=True)
    with mp.get_context("fork").Pool(A.workers) as pool:
        rows = [convert(n, pool) for n in names]
    for s in ("train", "val"):
        index(os.path.join(A.out, s))
    write_json(os.path.join(A.out, "report.json"), {"revisions": A.revisions, "target_fps": A.target_fps, "res": A.res,
                                                    "chunk": A.chunk, "val_per_dataset": A.val, "datasets": rows})
    print("convert done", flush=True)


if __name__ == "__main__":
    main()