File size: 20,639 Bytes
87816f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62b9622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87816f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62b9622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87816f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62b9622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87816f8
 
 
 
 
 
 
 
 
 
62b9622
87816f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
"""第6回演習 補助モジュール。

ノートブックと同じディレクトリに置いて `import utils` で使います。
データ取得・self-check(check_stepN)・可視化・キュレーション適用をまとめています。
self-check は ✅/❌+期待範囲+単位付き数値+ヒント1行を表示します(bare assert にしない)。
"""

from __future__ import annotations

import io
import json
import shutil
from pathlib import Path

import numpy as np

# ---------------------------------------------------------------- paths / data

HF_REPO = "Adwaver4157/pai2026-lecture6-data"  # 講座 org(アップロード時に upload_hf.py と一致させる)
DATA_DIR = Path("lecture6_data")

# 本編(Step 0〜4、CPU で全員が使う)だけを 0-3 で取得する。約 65 MB。
# 重い学習済みモデル(act_best 198MB / mini 197MB)と発展用データは、
# それを使うセルの中で必要時に fetch_data([...]) で追加取得する(遅延DL)。
CORE_PATTERNS = [
    "bags/*",
    "checkpoints/synced/*",
    "checkpoints/embeddings.npz",
    "checkpoints/step5_results.json",
    "checkpoints/step5_loss_curves.png",
    "checkpoints/step5_*.mp4",
    "lerobot/lecture6-bags16/*",
]

TOPIC_CAM_AGENT = "/cam_agentview/compressed"
TOPIC_CAM_WRIST = "/cam_wrist/compressed"
TOPIC_JOINTS = "/joint_states"
TOPIC_ACTION = "/leader/action"
ALL_TOPICS = [TOPIC_CAM_AGENT, TOPIC_CAM_WRIST, TOPIC_JOINTS, TOPIC_ACTION]

_INSTRUCTIONS = {
    "lift": "Pick up the red cube and lift it.",
    "can": "Pick up the can and place it into the bin.",
}


def ensure_lerobot_importable() -> None:
    """Colab の transformers 5.4+ が lerobot 0.5.1 の groot import を壊すのを無害化し、
    `lerobot.policies` を一度通します(Step 5 / Step 6 の前に必ず呼ぶ)。

    ローカル(Jupyter)は transformers 未導入で問題が出ませんが、Colab はプリインストール
    された新しい transformers が groot の config を dataclass 化の順序規則で壊します。
    ここで失敗すれば被害はこのセルに閉じ込められ、Step 6 での KeyError 連鎖を防げます。
    """
    import importlib.metadata as md
    import pathlib

    try:
        tv = md.version("transformers")
        print("transformers:", tv)
    except md.PackageNotFoundError:
        tv = None
        print("transformers 未導入(ローカル環境)。ガード不要です。")

    if tv and tuple(int(x) for x in tv.split(".")[:2]) >= (5, 4):
        import lerobot

        path = pathlib.Path(lerobot.__file__).parent / "policies/groot/groot_n1.py"
        lines = path.read_text().splitlines()
        for i, ln in enumerate(lines):
            if (
                "class GR00TN15Config(PretrainedConfig):" in ln
                and i > 0
                and lines[i - 1].strip() == "@dataclass"
            ):
                lines[i - 1] = lines[i - 1].replace("@dataclass", "@dataclass(kw_only=True)")
                print("groot_n1.py にパッチを適用しました")
        path.write_text("\n".join(lines))

    import lerobot.policies  # noqa: F401  ここで落ちたら: セッション再起動 → 0-2 からやり直し
    print("lerobot.policies import OK")


def fetch_data(patterns: list[str] | None = None) -> Path:
    """配布データを取得します(冪等・追加取得可)。

    - 講師環境(リポジトリ直下に data/ がある): ../data と ../out/checkpoints を
      symlink するだけ。patterns は無視(全部そろっている)。
    - Colab: HF Hub から patterns に一致するものだけを取得(リトライつき)。
      patterns 省略時は本編一式(CORE_PATTERNS, 約 65 MB)。追加で重い資産が
      要るセルは fetch_data(["checkpoints/act_best/*"]) のように呼び足す。
    """
    if patterns is None:
        patterns = CORE_PATTERNS
    local = Path("../data/bags")
    if local.exists():  # instructor repo layout
        root = DATA_DIR
        if not root.exists():
            root.mkdir(parents=True)
            (root / "bags").symlink_to(local.resolve())
            (root / "checkpoints").symlink_to(Path("../out/checkpoints").resolve())
            (root / "lerobot").symlink_to(Path("../data/lerobot").resolve())
        return root
    import time

    from huggingface_hub import snapshot_download

    for attempt in range(4):
        try:
            snapshot_download(
                HF_REPO,
                repo_type="dataset",
                local_dir=DATA_DIR,
                allow_patterns=patterns,
            )
            return DATA_DIR
        except Exception as e:  # 429 など。指数バックオフで粘る
            wait = 2**attempt * 5
            print(f"ダウンロード失敗({e})。{wait}秒後にリトライします…")
            time.sleep(wait)
    raise RuntimeError("データ取得に失敗しました。ネットワークを確認してください。")


def list_bags(root: Path | None = None) -> list[Path]:
    root = root or DATA_DIR
    return sorted(p for p in (root / "bags").iterdir() if (p / "metadata.yaml").exists())


# ---------------------------------------------------------------- bag reading


def read_bag(bag_dir: Path, decode_images: bool = False) -> dict:
    """bag を読み、トピックごとに stamp[s]・受信時刻[s]・値を返します。

    値: JointState は position 配列、画像は decode_images=True のときだけ RGB 配列。
    """
    from PIL import Image
    from rosbags.highlevel import AnyReader

    out: dict[str, dict[str, list]] = {}
    with AnyReader([bag_dir]) as reader:
        for conn, t_recv_ns, raw in reader.messages():
            msg = reader.deserialize(raw, conn.msgtype)
            stamp = msg.header.stamp.sec + msg.header.stamp.nanosec * 1e-9
            d = out.setdefault(conn.topic, {"stamp": [], "recv": [], "val": []})
            d["stamp"].append(stamp)
            d["recv"].append(t_recv_ns * 1e-9)
            if conn.msgtype == "sensor_msgs/msg/JointState":
                d["val"].append(np.asarray(msg.position, dtype=np.float64))
            elif decode_images:
                d["val"].append(np.asarray(Image.open(io.BytesIO(msg.data.tobytes()))))
    res = {}
    for topic, d in out.items():
        order = np.argsort(d["stamp"])
        res[topic] = {
            "stamp": np.asarray(d["stamp"])[order],
            "recv": np.asarray(d["recv"])[order],
        }
        if d["val"]:
            res[topic]["val"] = np.stack([d["val"][i] for i in order])
    return res


def topic_table(root: Path | None = None):
    """全 bag のトピック・件数・実効 Hz の一覧表(DataFrame)。"""
    import pandas as pd

    rows = []
    for bag in list_bags(root):
        topics = read_bag(bag)
        for topic in ALL_TOPICS:
            d = topics[topic]
            dt = np.diff(np.sort(d["stamp"]))
            rows.append(
                {
                    "bag": bag.name,
                    "topic": topic,
                    "count": len(d["stamp"]),
                    "rate_hz": round(1.0 / np.median(dt), 1),
                    "max_gap_ms": round(float(dt.max() * 1e3), 1),
                }
            )
    return pd.DataFrame(rows)


def latency_table(root: Path | None = None):
    """bag別・トピック別の median(stamp − 受信時刻) [ms] 一覧(D1 の正式検出経路)。"""
    import pandas as pd

    rows = []
    for bag in list_bags(root):
        topics = read_bag(bag)
        row = {"bag": bag.name}
        for topic in ALL_TOPICS:
            d = topics[topic]
            row[topic] = round(float(np.median(d["stamp"] - d["recv"])) * 1e3, 1)
        rows.append(row)
    return pd.DataFrame(rows).set_index("bag")


def xcorr_lag_ms(topics: dict, fs: float = 100.0) -> float:
    """指令(/leader/action)に対する関節応答の遅れ [ms]。

    頑健化 2 点(生成時に実測してこの形に決定):
    - 関節速度は「位置を一様グリッドに補間 → 微分」で作る
      (メッセージ毎の Δpos/Δt は stamp jitter 5ms@50Hz で壊れる)
    - 両信号を 100ms 移動平均 → 一階差分してから相関を取る
      (生の速度波形はピークが平坦で argmax が ±300ms 迷走する)
    """
    act, jnt = topics[TOPIC_ACTION], topics[TOPIC_JOINTS]
    t_a, sig_a = act["stamp"], np.linalg.norm(act["val"][:, :3], axis=1)
    t_j, pos_j = jnt["stamp"], jnt["val"]
    grid = np.arange(max(t_a[0], t_j[0]), min(t_a[-1], t_j[-1]), 1.0 / fs)
    pos = np.stack([np.interp(grid, t_j, pos_j[:, j]) for j in range(pos_j.shape[1])], axis=1)
    joint_speed = np.zeros(len(grid))
    joint_speed[1:] = np.linalg.norm(np.diff(pos, axis=0), axis=1) * fs
    cmd = np.interp(grid, t_a, sig_a)
    kernel = np.ones(10) / 10
    a = np.diff(np.convolve(cmd, kernel, mode="same"))
    b = np.diff(np.convolve(joint_speed, kernel, mode="same"))
    a = (a - a.mean()) / (a.std() + 1e-9)
    b = (b - b.mean()) / (b.std() + 1e-9)
    corr = np.correlate(b, a, mode="full")
    lags = (np.arange(len(corr)) - (len(a) - 1)) / fs
    keep = np.abs(lags) <= 1.0
    return float(lags[keep][np.argmax(corr[keep])] * 1e3)


# ---------------------------------------------------------------- checkpoints


def load_synced(bag_name: str, root: Path | None = None) -> dict[str, np.ndarray]:
    """Step 2 の checkpoint をロードします(画像は bag から復元)。"""
    root = root or DATA_DIR
    d = dict(np.load(root / "checkpoints" / "synced" / f"{bag_name}.npz"))
    topics = read_bag(root / "bags" / bag_name, decode_images=True)
    d["agentview"] = topics[TOPIC_CAM_AGENT]["val"][d["cam_idx"]]
    d["wrist"] = topics[TOPIC_CAM_WRIST]["val"][d["wrist_idx"]]
    return d


# ---------------------------------------------------------------- self-checks


def _report(name: str, ok: bool, detail: str, hint: str = "") -> bool:
    mark = "✅" if ok else "❌"
    print(f"{mark} {name}: {detail}")
    if not ok and hint:
        print(f"   ヒント: {hint}")
    return ok


def check_step0(root: Path | None = None) -> None:
    root = root or DATA_DIR
    bags = list_bags(root)
    ok = _report(
        "bag 件数", len(bags) == 16, f"{len(bags)} 件(期待: 16 件)",
        "fetch_data() を再実行してください",
    )
    size = sum(f.stat().st_size for b in bags for f in b.rglob("*")) / 1e6
    ok &= _report(
        "合計サイズ", 30 <= size <= 70, f"{size:.1f} MB(期待: 30〜70 MB)",
        "ダウンロードが途中で失敗している可能性があります",
    )
    import importlib.metadata

    ver_str = importlib.metadata.version("rosbags")
    ver = tuple(int(x) for x in ver_str.split(".")[:2])
    ok &= _report(
        "rosbags", ver >= (0, 10), f"version {ver_str}(期待: >= 0.10)",
        "セル 0-2 の install を実行して、ランタイムを再起動してください",
    )
    # 環境診断(当日の質問対応がスクリーンショット1枚で済むように)
    import os

    def _v(pkg):
        try:
            return importlib.metadata.version(pkg)
        except importlib.metadata.PackageNotFoundError:
            return "(未導入)"

    vers = " / ".join(f"{k} {_v(k)}" for k in ("lerobot", "transformers", "torch", "robosuite"))
    print(f"環境: {vers} / MUJOCO_GL={os.environ.get('MUJOCO_GL', '(未設定)')}")
    # transformers が 5.4+ だと Step 6 で groot が壊れる(0-2b で対策済みか確認用)
    tv = _v("transformers")
    if tv not in ("(未導入)",) and tuple(int(x) for x in tv.split(".")[:2]) >= (5, 4):
        print("  ※ transformers 5.4+ 検出。Step 6 前にセル 0-2b を必ず実行してください。")
    print("\nStep 0 完了です。" if ok else "\n上の ❌ を直してから先に進んでください。")


def check_step1(rate_df, latency_df) -> None:
    cam = rate_df[rate_df.topic == TOPIC_CAM_AGENT]
    jnt = rate_df[rate_df.topic == TOPIC_JOINTS]
    ok = _report(
        "カメラ実効レート",
        bool(((cam.rate_hz - 20).abs() / 20 < 0.1).all()),
        f"20Hz ±10% に {int(((cam.rate_hz - 20).abs() / 20 < 0.1).sum())}/16 本",
        "実効 Hz は median(Δt) から求めます(平均だと欠落に引っ張られます)",
    )
    ok &= _report(
        "関節実効レート",
        bool(((jnt.rate_hz - 50).abs() / 50 < 0.1).all()),
        f"50Hz ±10% に {int(((jnt.rate_hz - 50).abs() / 50 < 0.1).sum())}/16 本",
        "",
    )
    n_anom = int((latency_df[TOPIC_JOINTS].abs() > 300).sum())
    ok &= _report(
        "レイテンシ異常 bag",
        n_anom == 1,
        f"{n_anom} 本(期待: ちょうど 1 本、median(stamp−受信時刻) が +300ms 超)",
        "正常な bag では stamp−受信時刻 ≈ −数 ms(伝送遅延の分だけ負)です",
    )
    print("\nStep 1 完了です。" if ok else "\n上の ❌ を直してから先に進んでください。")


def check_step2(bag_name: str, n_adopted: int, root: Path | None = None) -> None:
    root = root or DATA_DIR
    expected = len(np.load(root / "checkpoints" / "synced" / f"{bag_name}.npz")["t"])
    ok = _report(
        f"{bag_name} の採用フレーム数",
        abs(n_adopted - expected) <= 3,
        f"{n_adopted} フレーム(期待: {expected} ±3 フレーム)",
        "slop の単位(秒)と、関節 np.interp の範囲外マスクを確認してください",
    )
    print("\nStep 2 完了です。" if ok else "")


def check_sync(lag_by_bag: dict[str, float]) -> None:
    lags = np.array(list(lag_by_bag.values()))
    n_big = int((lags > 300).sum())
    ok = _report(
        "相互相関ラグ > 300ms の bag",
        n_big == 1,
        f"{n_big} 本(期待: ちょうど 1 本 ≈ +430ms)",
        "utils.xcorr_lag_ms をそのまま使っていますか",
    )
    ok &= _report(
        "その他の bag のラグ",
        bool((np.abs(lags[lags <= 300]) <= 100).all()),
        f"max |lag| = {np.abs(lags[lags <= 300]).max():.0f} ms(期待: ≤100 ms)",
        "",
    )
    print("\n同期の検算は以上です。" if ok else "")


def check_step3(ds) -> None:
    ok = _report(
        "エピソード数", ds.num_episodes == 3, f"{ds.num_episodes}(期待: 授業内は 3 本)", ""
    )
    ok &= _report("fps", ds.fps == 20, f"{ds.fps}(期待: 20)", "features の fps を確認")
    need = {
        "observation.images.agentview",
        "observation.images.wrist",
        "observation.state",
        "action",
    }
    have = need & set(ds.features)
    ok &= _report(
        "features",
        have == need,
        f"{len(have)}/4 キー(期待: 画像2・state・action)",
        "キー名は observation.images.* / observation.state / action です",
    )
    item = ds[0]
    ok &= _report(
        "shape",
        tuple(item["observation.state"].shape) == (7,) and tuple(item["action"].shape) == (7,),
        f'state {tuple(item["observation.state"].shape)} / action {tuple(item["action"].shape)}(期待: (7,) / (7,))',
        "",
    )
    print("\nStep 3 完了です。" if ok else "")


def check_labels(suspects: list[str]) -> None:
    """Step 4b(ラベル監査)の self-check。"""
    ok = _report(
        "容疑者数",
        len(suspects) == 2,
        f"{len(suspects)} 本: {sorted(suspects)}(期待: ちょうど 2 本)",
        "filter 済みの bag を判断表で除外してから kNN を回していますか(LOO: 対角は inf)",
    )
    if ok:
        print("→ この 2 本を mp4 で目視して、指示文と本当に食い違うか確認しましょう。")


# ---------------------------------------------------------------- visualization


def save_mp4(frames, path: str, fps: int = 20, upscale: int = 1) -> str:
    """ブラウザ(Colab の Chrome)で確実に再生できる mp4 を書き出します。

    Colab 実機で「砂嵐動画」になる主因は、Colab の imageio-ffmpeg が既定で
    Chrome 非対応の pixel format を出すことでした(ローカルの新しい版は yuv420p 既定で
    問題が出ない)。ここで yuv420p / libx264 / 偶数寸法 / uint8 連続配列を強制します。
    """
    import imageio.v2 as imageio

    a = np.asarray(frames)
    if a.ndim == 4 and a.shape[1] == 3:                 # (T,3,H,W) -> (T,H,W,3)
        a = a.transpose(0, 2, 3, 1)
    if a.dtype != np.uint8:                             # 0..1 float も 0..255 も許容
        a = np.clip(a * (255 if float(a.max()) <= 1.0 else 1), 0, 255).astype(np.uint8)
    a = a[..., :3]
    if upscale > 1:
        a = a.repeat(upscale, 1).repeat(upscale, 2)
    a = a[:, : a.shape[1] // 2 * 2, : a.shape[2] // 2 * 2]   # H,W を偶数に
    a = np.ascontiguousarray(a)                          # flipud ビューのストライドずれ対策
    imageio.mimwrite(
        path, a, fps=fps, codec="libx264",
        output_params=["-pix_fmt", "yuv420p"], macro_block_size=16,
    )
    return path


def episode_video(ds, episode_index: int, camera: str = "agentview", path: str | None = None):
    """1 エピソードを mp4 にして IPython Video で返します(講座の実績方式)。"""
    from IPython.display import Video

    frames = []
    ep = ds.meta.episodes[episode_index]
    for i in range(ep["dataset_from_index"], ep["dataset_to_index"]):
        img = ds[i][f"observation.images.{camera}"]
        frames.append((img.permute(1, 2, 0).numpy() * 255).astype(np.uint8))
    path = path or f"ep_{episode_index:03d}_{camera}.mp4"
    save_mp4(frames, path, fps=ds.fps)
    return Video(path, embed=True, width=480)


def stats_report(ds) -> None:
    """エピソード長・行動分布・jerk・タスク別本数のダッシュボード(ラベルは英語)。"""
    import matplotlib.pyplot as plt

    n = ds.num_episodes
    lengths, jerks, tasks = [], [], []
    for e in range(n):
        ep = ds.meta.episodes[e]
        idx = np.arange(ep["dataset_from_index"], ep["dataset_to_index"])
        acts = np.stack([ds[int(i)]["action"].numpy() for i in idx])
        lengths.append(len(idx))
        jerks.append(float(np.abs(np.diff(acts[:, :3], n=2, axis=0)).mean()))
        tasks.append(ds.meta.episodes[e]["tasks"][0])
    fig, axes = plt.subplots(1, 3, figsize=(13, 3.2))
    axes[0].bar(range(n), lengths)
    axes[0].set_title("episode length [frames]")
    axes[0].set_xlabel("episode")
    axes[1].bar(range(n), jerks, color="tab:orange")
    axes[1].set_title("action jerk (smoothness, lower=better)")
    axes[1].set_xlabel("episode")
    labels, counts = np.unique(tasks, return_counts=True)
    axes[2].bar([l[:18] for l in labels], counts, color="tab:green")
    axes[2].set_title("episodes per task label")
    plt.tight_layout()
    plt.show()


# ---------------------------------------------------------------- curation


def apply_curation(ds_root: Path, df, out_root: Path):
    """判断表 df(episode_id / decision / new_task 列)を適用した新データセットを作ります。

    decision: keep / filter / relabel。relabel 行は new_task にタスク名(lift/can)。
    """
    from lerobot.datasets.dataset_tools import modify_tasks
    from lerobot.datasets.lerobot_dataset import LeRobotDataset

    out_root = Path(out_root)
    if out_root.exists():
        shutil.rmtree(out_root)
    shutil.copytree(ds_root, out_root)
    ds = LeRobotDataset(repo_id="local/curated", root=out_root)

    episode_tasks = {
        int(row.episode_id): _INSTRUCTIONS[row.new_task]
        for _, row in df[df.decision == "relabel"].iterrows()
    }
    if episode_tasks:
        modify_tasks(ds, episode_tasks=episode_tasks)

    drop = [int(r.episode_id) for _, r in df[df.decision == "filter"].iterrows()]
    keep = [e for e in range(ds.num_episodes) if e not in drop]
    print(f"filter: {len(drop)} 本除外, relabel: {len(episode_tasks)} 本, keep: {len(keep)} 本")
    return ds, keep


# ---------------------------------------------------------------- step 4b


def segment_pool(vis_frames: np.ndarray) -> np.ndarray:
    """(E,F,D) → (E,2D)。前半平均‖後半平均(順序を残すプーリング)。"""
    half = vis_frames.shape[1] // 2
    return np.concatenate(
        [vis_frames[:, :half].mean(1), vis_frames[:, half:].mean(1)], axis=1
    )


def zscore(x: np.ndarray) -> np.ndarray:
    return (x - x.mean(0)) / (x.std(0) + 1e-9)