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
 
 
 
 
 
 
 
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
500
501
502
503
504
505
506
507
508
509
510
511
512
"""
Extract a small subset from a full lingbot-va dataset for quick model testing.

Supports both single-dataset and multi-dataset (recursive) layouts.
Copies metadata, latent files, action parquets, and trims videos (via ffmpeg)
for a specified number of episodes.

Usage:
    python subset_dataset.py \
        --src /path/to/full_dataset \
        --dst /path/to/subset_dataset \
        --num-episodes 5 \
        --copy-videos
"""

from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
from pathlib import Path

import pandas as pd


def find_dataset_roots(base: Path) -> list[Path]:
    """Recursively find all dataset roots (dirs containing meta/info.json)."""
    roots = []
    for dirpath, _, filenames in os.walk(base):
        if "info.json" in filenames and Path(dirpath).name == "meta":
            roots.append(Path(dirpath).parent)
    if not roots:
        raise FileNotFoundError(
            f"No dataset found under {base} (looking for meta/info.json)"
        )
    return sorted(roots)


def load_jsonl(path: Path) -> list[dict]:
    rows = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def save_jsonl(rows: list[dict], path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")


def resolve_action_config_path(root: Path) -> Path | None:
    candidates = [
        root / "meta/lingbot_action_config.jsonl",
        root / "meta/action_config.jsonl",
        root / "meta/episodes.jsonl",
    ]
    for c in candidates:
        if c.exists():
            return c
    return None


def get_segments(config_path: Path) -> list[dict]:
    """Load action segments from config file, handling legacy format."""
    rows = load_jsonl(config_path)

    if config_path.name == "episodes.jsonl":
        segments = []
        for row in rows:
            if "action_config" in row:
                for ac in row["action_config"]:
                    seg = {"episode_index": int(row["episode_index"])}
                    seg.update(ac)
                    if "tasks" in row:
                        seg.setdefault("tasks", row["tasks"])
                    segments.append(seg)
            else:
                tasks = row.get("tasks", [])
                action_text = tasks[0] if tasks else "robot manipulation"
                segments.append({
                    "episode_index": int(row["episode_index"]),
                    "tasks": tasks,
                    "start_frame": 0,
                    "end_frame": int(row["length"]),
                    "action_text": action_text,
                })
        return segments

    # lingbot_action_config.jsonl / action_config.jsonl: flat format
    return rows


def copy_latents_for_episodes(
    src_root: Path, dst_root: Path, episode_indices: set[int], segments: list[dict],
):
    """Copy latent .pth files for selected episodes."""
    latent_src = src_root / "latents"
    if not latent_src.exists():
        print(f"  [skip] no latents/ dir in {src_root}")
        return 0

    copied = 0
    for seg in segments:
        ep = int(seg["episode_index"])
        if ep not in episode_indices:
            continue
        sf = int(seg["start_frame"])
        ef = int(seg["end_frame"])
        chunk_id = ep // 1000

        chunk_dir = latent_src / f"chunk-{chunk_id:03d}"
        if not chunk_dir.exists():
            continue

        for cam_dir in chunk_dir.iterdir():
            if not cam_dir.is_dir():
                continue
            fname = f"episode_{ep:06d}_{sf}_{ef}.pth"
            src_file = cam_dir / fname
            if src_file.exists():
                dst_file = dst_root / "latents" / f"chunk-{chunk_id:03d}" / cam_dir.name / fname
                dst_file.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(src_file, dst_file)
                copied += 1
    return copied


def _load_episode_metadata(src_root: Path) -> dict[int, dict]:
    """Load episode metadata from jsonl or parquet and return {episode_index: row_dict}."""
    # v3.0: meta/episodes/ is a parquet directory
    ep_parquet_dir = src_root / "meta/episodes"
    if ep_parquet_dir.is_dir():
        df = pd.read_parquet(ep_parquet_dir)
        rows = df.to_dict("records")
        return {int(r["episode_index"]): r for r in rows}

    # single parquet file
    ep_parquet = src_root / "meta/episodes.parquet"
    if ep_parquet.exists():
        df = pd.read_parquet(ep_parquet)
        rows = df.to_dict("records")
        return {int(r["episode_index"]): r for r in rows}

    # legacy jsonl
    ep_jsonl = src_root / "meta/episodes.jsonl"
    if ep_jsonl.exists():
        rows = load_jsonl(ep_jsonl)
        return {int(r["episode_index"]): r for r in rows}

    return {}


def _discover_cam_keys(ep_meta: dict[int, dict]) -> set[str]:
    """Find all camera keys from episode metadata."""
    cams = set()
    for row in ep_meta.values():
        for k in row:
            if k.startswith("videos/") and k.endswith("/chunk_index"):
                cams.add(k.split("/")[1])
    return cams


def _ffmpeg_trim(src_mp4: Path, dst_mp4: Path, start: float, end: float | None):
    """Trim a video clip with ffmpeg (stream copy, no re-encoding)."""
    dst_mp4.parent.mkdir(parents=True, exist_ok=True)
    cmd = [
        "ffmpeg", "-y",
        "-i", str(src_mp4),
        "-ss", f"{start:.6f}",
    ]
    if end is not None:
        cmd += ["-to", f"{end:.6f}"]
    cmd += [
        "-c", "copy",
        "-avoid_negative_ts", "make_zero",
        str(dst_mp4),
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"  [warn] ffmpeg failed for {src_mp4}: {result.stderr[-200:]}")
        return False
    return True


def _ffmpeg_concat(clip_paths: list[Path], dst_mp4: Path):
    """Concatenate multiple clips into one file using ffmpeg concat demuxer."""
    dst_mp4.parent.mkdir(parents=True, exist_ok=True)
    # Write concat list file
    list_file = dst_mp4.parent / ".concat_list.txt"
    with open(list_file, "w") as f:
        for p in clip_paths:
            f.write(f"file '{p}'\n")
    cmd = [
        "ffmpeg", "-y",
        "-f", "concat", "-safe", "0",
        "-i", str(list_file),
        "-c", "copy",
        str(dst_mp4),
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    list_file.unlink(missing_ok=True)
    if result.returncode != 0:
        print(f"  [warn] ffmpeg concat failed: {result.stderr[-300:]}")
        return False
    return True


def trim_videos_for_episodes(
    src_root: Path,
    dst_root: Path,
    episode_indices: set[int],
    ep_meta: dict[int, dict],
) -> dict[int, dict]:
    """Trim and concatenate video clips for selected episodes.

    For each camera, groups episodes by source video file, trims each
    group as a contiguous range [min(from_ts), max(to_ts)], then
    concatenates all groups into a single output file-000.mp4.
    Updates episode metadata with new timestamps.

    Returns metadata updates: {episode_index: {field: new_value, ...}}
    """
    from collections import defaultdict

    vid_src = src_root / "videos"
    meta_updates: dict[int, dict] = {}

    if not vid_src.exists() or not ep_meta:
        return meta_updates

    cam_keys = _discover_cam_keys(ep_meta)
    if not cam_keys:
        return meta_updates

    for cam in sorted(cam_keys):
        # Group selected episodes by source video file
        groups: dict[tuple[int, int], list[int]] = defaultdict(list)
        for ep in sorted(episode_indices):
            row = ep_meta.get(ep)
            if row is None:
                continue
            chunk_idx = row.get(f"videos/{cam}/chunk_index")
            file_idx = row.get(f"videos/{cam}/file_index")
            if chunk_idx is None or file_idx is None:
                continue
            groups[(int(chunk_idx), int(file_idx))].append(ep)

        if not groups:
            continue

        # Trim each source file to [min_from, max_to], track cumulative offset
        temp_clips: list[Path] = []
        cumulative_offset = 0.0

        for (chunk_idx, file_idx), eps in sorted(groups.items()):
            src_mp4 = (
                vid_src / cam
                / f"chunk-{chunk_idx:03d}"
                / f"file-{file_idx:03d}.mp4"
            )
            if not src_mp4.exists():
                print(f"  [warn] source video not found: {src_mp4}")
                continue

            # Find time range for this group
            from_ts_list = []
            to_ts_list = []
            for ep in eps:
                row = ep_meta[ep]
                from_ts_list.append(float(row[f"videos/{cam}/from_timestamp"]))
                to_ts_raw = row.get(f"videos/{cam}/to_timestamp")
                if to_ts_raw is not None:
                    to_ts_list.append(float(to_ts_raw))

            min_from = min(from_ts_list)
            max_to = max(to_ts_list) if to_ts_list else None

            # Trim source file to this range
            temp_clip = dst_root / f".tmp_{cam.replace('.', '_')}_{chunk_idx}_{file_idx}.mp4"
            ok = _ffmpeg_trim(src_mp4, temp_clip, min_from, max_to)
            if not ok:
                continue
            temp_clips.append(temp_clip)

            # Update each episode's metadata
            for ep in eps:
                row = ep_meta[ep]
                orig_from = float(row[f"videos/{cam}/from_timestamp"])
                orig_to_raw = row.get(f"videos/{cam}/to_timestamp")

                updates = meta_updates.setdefault(ep, {})
                updates[f"videos/{cam}/chunk_index"] = 0
                updates[f"videos/{cam}/file_index"] = 0
                updates[f"videos/{cam}/from_timestamp"] = cumulative_offset + (orig_from - min_from)
                if orig_to_raw is not None:
                    updates[f"videos/{cam}/to_timestamp"] = cumulative_offset + (float(orig_to_raw) - min_from)

            # Advance cumulative offset by the duration of this clip
            if max_to is not None:
                cumulative_offset += max_to - min_from

        # Concatenate all clips into one output file
        dst_mp4 = dst_root / "videos" / cam / "chunk-000" / "file-000.mp4"
        if len(temp_clips) == 1:
            dst_mp4.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(temp_clips[0]), str(dst_mp4))
        elif len(temp_clips) > 1:
            _ffmpeg_concat(temp_clips, dst_mp4)
            for tc in temp_clips:
                tc.unlink(missing_ok=True)

        print(f"  [{cam}] merged {len(temp_clips)} clip(s) into {dst_mp4.relative_to(dst_root)}")

    return meta_updates



def copy_data_parquets(
    src_root: Path, dst_root: Path, episode_indices: set[int],
):
    """Copy and filter data parquet files to only include selected episodes."""
    data_src = src_root / "data"
    if not data_src.exists():
        return 0

    copied = 0
    for pq_file in sorted(data_src.rglob("*.parquet")):
        try:
            df = pd.read_parquet(pq_file)
        except Exception as e:
            print(f"  [warn] cannot read {pq_file}: {e}")
            continue

        if "episode_index" in df.columns:
            df_sub = df[df["episode_index"].isin(episode_indices)]
        else:
            df_sub = df

        if len(df_sub) == 0:
            continue

        rel = pq_file.relative_to(src_root)
        dst_file = dst_root / rel
        dst_file.parent.mkdir(parents=True, exist_ok=True)
        df_sub.to_parquet(dst_file, index=False)
        copied += 1

    return copied


def _apply_meta_updates(rows: list[dict], updates: dict[int, dict]) -> list[dict]:
    """Apply video metadata updates to episode rows."""
    if not updates:
        return rows
    out = []
    for row in rows:
        ep = int(row["episode_index"])
        if ep in updates:
            row = dict(row)
            row.update(updates[ep])
        out.append(row)
    return out


def subset_single_dataset(
    src_root: Path,
    dst_root: Path,
    num_episodes: int,
    copy_videos: bool = False,
):
    """Create a subset of a single dataset."""
    print(f"\nProcessing: {src_root}")

    # 1. Load action config to find available episodes
    config_path = resolve_action_config_path(src_root)
    if config_path is None:
        print("  [skip] no action config found")
        return

    all_segments = get_segments(config_path)
    all_episodes = sorted({int(s["episode_index"]) for s in all_segments})
    selected = set(all_episodes[:num_episodes])
    selected_segments = [s for s in all_segments if int(s["episode_index"]) in selected]

    print(f"  Total episodes: {len(all_episodes)}, selecting: {len(selected)}")
    print(f"  Total segments: {len(all_segments)}, selecting: {len(selected_segments)}")

    dst_root.mkdir(parents=True, exist_ok=True)

    # 2. Copy meta/info.json
    info_src = src_root / "meta/info.json"
    if info_src.exists():
        (dst_root / "meta").mkdir(parents=True, exist_ok=True)
        shutil.copy2(info_src, dst_root / "meta/info.json")

    # 3. Trim videos (must happen before writing episodes.jsonl so we can
    #    apply metadata updates for the new video paths/timestamps)
    video_meta_updates: dict[int, dict] = {}
    if copy_videos:
        ep_meta = _load_episode_metadata(src_root)
        video_meta_updates = trim_videos_for_episodes(
            src_root, dst_root, selected, ep_meta,
        )

    # 4. Write filtered action config
    if config_path.name == "episodes.jsonl":
        orig_rows = load_jsonl(config_path)
        filtered_rows = [r for r in orig_rows if int(r["episode_index"]) in selected]
        filtered_rows = _apply_meta_updates(filtered_rows, video_meta_updates)
        save_jsonl(filtered_rows, dst_root / "meta/episodes.jsonl")
    else:
        save_jsonl(selected_segments, dst_root / config_path.relative_to(src_root))

    # 5. Copy & filter episode metadata (parquet dir, parquet file, or jsonl)
    ep_parquet_dir = src_root / "meta/episodes"
    ep_parquet_file = src_root / "meta/episodes.parquet"
    ep_jsonl_file = src_root / "meta/episodes.jsonl"

    if ep_parquet_dir.is_dir():
        df = pd.read_parquet(ep_parquet_dir)
        df_sub = df[df["episode_index"].isin(selected)].copy()
        for ep_idx in df_sub["episode_index"]:
            if int(ep_idx) in video_meta_updates:
                for k, v in video_meta_updates[int(ep_idx)].items():
                    df_sub.loc[df_sub["episode_index"] == ep_idx, k] = v
        dst_ep_file = dst_root / "meta/episodes/chunk-000/file-000.parquet"
        dst_ep_file.parent.mkdir(parents=True, exist_ok=True)
        df_sub.to_parquet(dst_ep_file, index=False)
        print(f"  Wrote {len(df_sub)} rows to meta/episodes/")
    elif ep_parquet_file.exists():
        df = pd.read_parquet(ep_parquet_file)
        df_sub = df[df["episode_index"].isin(selected)].copy()
        for ep_idx in df_sub["episode_index"]:
            if int(ep_idx) in video_meta_updates:
                for k, v in video_meta_updates[int(ep_idx)].items():
                    df_sub.loc[df_sub["episode_index"] == ep_idx, k] = v
        (dst_root / "meta").mkdir(parents=True, exist_ok=True)
        df_sub.to_parquet(dst_root / "meta/episodes.parquet", index=False)
    elif ep_jsonl_file.exists() and config_path.name != "episodes.jsonl":
        orig_rows = load_jsonl(ep_jsonl_file)
        filtered_rows = [r for r in orig_rows if int(r["episode_index"]) in selected]
        filtered_rows = _apply_meta_updates(filtered_rows, video_meta_updates)
        save_jsonl(filtered_rows, dst_root / "meta/episodes.jsonl")

    # 6. Copy empty_emb.pt
    emb_src = src_root / "empty_emb.pt"
    if emb_src.exists():
        shutil.copy2(emb_src, dst_root / "empty_emb.pt")

    # 7. Copy latent files
    n = copy_latents_for_episodes(src_root, dst_root, selected, selected_segments)
    print(f"  Copied {n} latent files")

    # 8. Copy & filter data parquets
    n = copy_data_parquets(src_root, dst_root, selected)
    print(f"  Copied {n} data parquet files")

    # 9. Copy other meta files (stats, tasks, etc.)
    meta_src = src_root / "meta"
    if meta_src.exists():
        for f in meta_src.iterdir():
            if f.name in ("info.json", "episodes.jsonl", "episodes.parquet",
                          "episodes", "lingbot_action_config.jsonl",
                          "action_config.jsonl"):
                continue  # already handled
            dst_f = dst_root / "meta" / f.name
            if f.is_file() and not dst_f.exists():
                dst_f.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(f, dst_f)


def main():
    parser = argparse.ArgumentParser(
        description="Extract a small subset from a lingbot-va dataset for testing."
    )
    parser.add_argument("--src", type=str, required=True,
                        help="Source dataset root (single dataset or multi-dataset parent)")
    parser.add_argument("--dst", type=str, required=True,
                        help="Destination path for the subset")
    parser.add_argument("--num-episodes", type=int, default=5,
                        help="Number of episodes to include per sub-dataset (default: 5)")
    parser.add_argument("--copy-videos", action="store_true",
                        help="Also copy raw video files (not needed for latent-based training)")
    args = parser.parse_args()

    src = Path(args.src).resolve()
    dst = Path(args.dst).resolve()

    if dst.exists():
        print(f"Warning: destination {dst} already exists, files may be overwritten.")

    dataset_roots = find_dataset_roots(src)
    print(f"Found {len(dataset_roots)} dataset(s) under {src}")

    for ds_root in dataset_roots:
        rel = ds_root.relative_to(src)
        ds_dst = dst / rel if str(rel) != "." else dst
        subset_single_dataset(ds_root, ds_dst, args.num_episodes, args.copy_videos)

    print(f"\nDone! Subset saved to: {dst}")


if __name__ == "__main__":
    main()