File size: 13,887 Bytes
465d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
PyTorch Dataset for loading raw video segments for VAE preprocessing.

Fully self-contained — all data-side operations (segment filtering, frame
sampling, video decoding, batch padding) are implemented here without
importing from other preprocessing scripts.
"""

from __future__ import annotations

from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from tqdm import tqdm

from lerobot.datasets.video_utils import decode_video_frames


# ---- helpers ----------------------------------------------------------------

def _get_latent_output_path(
    dataset_root: Path,
    camera_key: str,
    episode_index: int,
    start_frame: int,
    end_frame: int,
) -> Path:
    chunk_id = episode_index // 1000
    return (
        dataset_root
        / "latents"
        / f"chunk-{chunk_id:03d}"
        / camera_key
        / f"episode_{episode_index:06d}_{start_frame}_{end_frame}.pth"
    )


def _resolve_episode_data_source(
    dataset_root: Path, episode_row: dict, data_path_template: str,
) -> Path:
    chunk_key = "data/chunk_index"
    file_key = "data/file_index"
    if chunk_key not in episode_row or file_key not in episode_row:
        raise KeyError(
            "Can not find v3.0 data parquet metadata for "
            f"episode_index={int(episode_row['episode_index'])}"
        )
    data_path = dataset_root / data_path_template.format(
        chunk_index=int(episode_row[chunk_key]),
        file_index=int(episode_row[file_key]),
    )
    if not data_path.exists():
        raise FileNotFoundError(f"Data parquet not found: {data_path}")
    return data_path


def _batch_load_episode_frame_timestamps(
    dataset_root: Path,
    episode_indices: set[int],
    episode_lookup: dict[int, dict],
    data_path_template: str,
) -> dict[int, dict[int, float]]:
    """Load timestamps for many episodes at once, reading each parquet file only once."""
    if not episode_indices:
        return {}

    import pandas as pd
    from collections import defaultdict

    # Group episodes by their data parquet file
    file_to_episodes: dict[Path, list[int]] = defaultdict(list)
    for ep_idx in episode_indices:
        episode_row = episode_lookup.get(ep_idx)
        if episode_row is None:
            raise KeyError(f"episode_index not found in metadata: {ep_idx}")
        data_path = _resolve_episode_data_source(dataset_root, episode_row, data_path_template)
        file_to_episodes[data_path].append(ep_idx)

    result: dict[int, dict[int, float]] = {}

    for data_path, ep_list in tqdm(
        file_to_episodes.items(),
        desc="Loading timestamps",
        unit="file",
    ):
        frame_table = pd.read_parquet(
            data_path,
            columns=["episode_index", "frame_index", "timestamp"],
            filters=[("episode_index", "in", ep_list)],
        )
        if frame_table.empty:
            raise ValueError(f"No frame timestamps found in {data_path} for episodes {ep_list}")

        for ep_idx in ep_list:
            ep_rows = frame_table[frame_table["episode_index"] == ep_idx]
            if ep_rows.empty:
                raise ValueError(
                    f"No frame timestamps found in {data_path} for episode_index={ep_idx}"
                )
            ep_rows = ep_rows.sort_values("frame_index", kind="stable").reset_index(drop=True)
            frame_ids = [int(v) for v in ep_rows["frame_index"].tolist()]
            timestamps = [float(v) for v in ep_rows["timestamp"].tolist()]

            if len(frame_ids) != len(set(frame_ids)):
                raise ValueError(
                    f"Duplicated frame_index in {data_path} for episode_index={ep_idx}"
                )

            episode_row = episode_lookup[ep_idx]
            expected_num_frames = None
            if "dataset_from_index" in episode_row and "dataset_to_index" in episode_row:
                expected_num_frames = int(episode_row["dataset_to_index"]) - int(episode_row["dataset_from_index"])
            elif "length" in episode_row:
                expected_num_frames = int(episode_row["length"])

            if expected_num_frames is not None and len(frame_ids) != expected_num_frames:
                raise ValueError(
                    f"Frame count mismatch for episode_index={ep_idx}: "
                    f"metadata says {expected_num_frames}, parquet has {len(frame_ids)} ({data_path})"
                )

            expected_frame_ids = list(range(len(frame_ids)))
            if frame_ids != expected_frame_ids:
                raise ValueError(
                    f"frame_index is not contiguous 0..N-1 for episode_index={ep_idx} in {data_path}"
                )

            if any(b <= a for a, b in zip(timestamps, timestamps[1:])):
                raise ValueError(
                    f"timestamp is not strictly increasing for episode_index={ep_idx} in {data_path}"
                )

            result[ep_idx] = dict(zip(frame_ids, timestamps))

    return result


def _resolve_episode_video_source(
    dataset_root: Path,
    camera_key: str,
    episode_index: int,
    episode_lookup: dict[int, dict],
    legacy: bool = False,
) -> tuple[Path, float]:
    """Return ``(video_path, start_timestamp)``.

    Args:
        legacy: True for v2.1 layout (one mp4 per episode),
                False for v3.0 layout (chunk/file based).
    """
    if legacy:
        chunk_id = episode_index // 1000
        video_path = (
            dataset_root
            / "videos"
            / f"chunk-{chunk_id:03d}"
            / camera_key
            / f"episode_{episode_index:06d}.mp4"
        )
        if not video_path.exists():
            raise FileNotFoundError(f"Video not found: {video_path}")
        return video_path, 0.0

    episode_row = episode_lookup.get(int(episode_index))
    if episode_row is None:
        raise KeyError(f"episode_index not found in metadata: {episode_index}")

    chunk_key = f"videos/{camera_key}/chunk_index"
    file_key = f"videos/{camera_key}/file_index"
    from_ts_key = f"videos/{camera_key}/from_timestamp"
    if chunk_key not in episode_row or file_key not in episode_row:
        raise KeyError(
            f"Can not find v3.0 video metadata for camera={camera_key}, "
            f"episode_index={episode_index}"
        )

    video_path = (
        dataset_root
        / "videos"
        / camera_key
        / f"chunk-{int(episode_row[chunk_key]):03d}"
        / f"file-{int(episode_row[file_key]):03d}.mp4"
    )
    if not video_path.exists():
        raise FileNotFoundError(f"Video not found: {video_path}")

    return video_path, float(episode_row.get(from_ts_key, 0.0))


def _sample_frame_ids(
    start_frame: int, end_frame: int, ori_fps: float, target_fps: int,
) -> list[int]:
    if target_fps <= 0 or ori_fps <= 0:
        raise ValueError(f"FPS must be positive: target_fps={target_fps}, ori_fps={ori_fps}")
    if target_fps > ori_fps:
        target_fps = ori_fps
    if end_frame <= start_frame:
        raise ValueError(f"Invalid frame range: {start_frame} -> {end_frame}")

    ori_fps = max(float(ori_fps), 1.0)
    stride = max(int(round(ori_fps / target_fps)), 1)
    frame_ids = list(range(start_frame, end_frame, stride))
    if not frame_ids:
        frame_ids = [start_frame]
    if frame_ids[-1] != end_frame - 1:
        frame_ids.append(end_frame - 1)
    return sorted(set(frame_ids))


def _read_video_frames(
    video_path: Path,
    timestamps: list[float],
    height: int,
    width: int,
    tolerance_s: float,
) -> torch.Tensor:
    """Decode, resize and normalise to [-1, 1]. Returns ``(1, 3, F, H, W)``."""
    if not video_path.exists():
        raise FileNotFoundError(f"Video not found: {video_path}")

    frames = decode_video_frames(
        video_path, timestamps=timestamps, tolerance_s=tolerance_s, backend="pyav",
    )  # (F, C, H, W) in [0, 1]

    if frames.shape[-2:] != (height, width):
        frames = F.interpolate(frames, size=(height, width), mode="bilinear", align_corners=False)

    return frames.unsqueeze(0).permute(0, 2, 1, 3, 4) * 2.0 - 1.0


def _compute_valid_frame_count(num_sampled):
    """Frames kept after dropping incomplete tail chunk (temporal downsample = 4)."""
    n = np.maximum(num_sampled, 1)
    return np.where(n <= 1, n, 1 + ((n - 1) // 4) * 4)


def _compute_latent_frame_count(num_valid):
    """Latent temporal frames from valid input frames (temporal downsample = 4)."""
    n = np.maximum(num_valid, 1)
    return np.where(n <= 1, n, 1 + (n - 1) // 4)


# ---- dataset ----------------------------------------------------------------

class SegmentVideoDataset(Dataset):
    """Dataset that loads and preprocesses video segments for VAE encoding.

    * **init** — segment filtering (skip existing / invalid), frame sampling,
      valid-frame & latent-frame count, timestamp resolution.
    * **getitem** — video frame loading, decoding, resize, normalisation.
    * **collate** — batch-level temporal padding (see ``collate_segment_videos``).

    Parameters
    ----------
    segments : list[dict]
        Raw action segments (from ``ensure_action_config_store``).
    camera_key, dataset_root, episode_lookup, data_path_template :
        Passed through to video / timestamp resolution helpers.
    dataset_fps : float
        Original dataset FPS.
    target_fps : int
        Target FPS for frame sampling.
    height, width : int
        Target frame resolution.
    skip_existing : bool
        Skip segments whose latent files already exist.
    legacy_video : bool
        True for v2.1 video layout, False for v3.0.
    """

    def __init__(
        self,
        segments: list[dict],
        camera_key: str,
        dataset_root: Path,
        episode_lookup: dict,
        data_path_template: str,
        dataset_fps: float,
        target_fps: int,
        height: int,
        width: int,
        skip_existing: bool = False,
        legacy_video: bool = False,
    ):
        self.camera_key = camera_key
        self.dataset_root = dataset_root
        self.episode_lookup = episode_lookup
        self.height = height
        self.width = width
        self.legacy_video = legacy_video

        self.metas: list[dict] = []
        self.skipped_keys: dict[tuple[int, int, int], int] = {}

        # Pass 1: filter segments, compute frame sampling, collect needed episodes
        pending: list[dict] = []
        needed_episodes: set[int] = set()

        for seg in tqdm(segments, desc=f"Filtering [{camera_key}]", unit="seg"):
            ep_idx = int(seg["episode_index"])
            sf = int(seg["start_frame"])
            ef = int(seg["end_frame"])
            key = (ep_idx, sf, ef)

            all_sampled = _sample_frame_ids(sf, ef, dataset_fps, target_fps)
            valid_count = int(_compute_valid_frame_count(len(all_sampled)))
            sampled_ids = all_sampled[:valid_count]
            if not sampled_ids:
                continue

            latent_count = int(_compute_latent_frame_count(valid_count))
            if skip_existing:
                out_path = _get_latent_output_path(dataset_root, camera_key, ep_idx, sf, ef)
                if out_path.exists():
                    self.skipped_keys[key] = latent_count
                    continue

            needed_episodes.add(ep_idx)
            pending.append({
                "episode_index": ep_idx,
                "start_frame": sf,
                "end_frame": ef,
                "action_text": seg["action_text"],
                "sampled_ids": sampled_ids,
                "valid_frame_count": valid_count,
                "latent_frame_count": latent_count,
            })

        # Batch load timestamps: each parquet file is read only once
        ts_map = _batch_load_episode_frame_timestamps(
            dataset_root, needed_episodes, episode_lookup, data_path_template,
        )

        # Pass 2: resolve timestamps and build final metas
        for item in pending:
            exact_ts = ts_map[item["episode_index"]]
            item["relative_timestamps"] = [float(exact_ts[fid]) for fid in item["sampled_ids"]]
            self.metas.append(item)

        # Sort by frame count so similarly-sized segments land in the same batch
        self.metas.sort(key=lambda m: m["valid_frame_count"],reverse=True)

        # Trim episode_lookup to only needed episodes (reduces pickle size for workers)
        used_episodes = {m["episode_index"] for m in self.metas}
        self.episode_lookup = {k: v for k, v in episode_lookup.items() if k in used_episodes}

    def __len__(self):
        return len(self.metas)

    def __getitem__(self, idx):
        meta = self.metas[idx]
        video_path, start_ts = _resolve_episode_video_source(
            self.dataset_root, self.camera_key,
            meta["episode_index"], self.episode_lookup,
            legacy=self.legacy_video,
        )
        query_ts = [ts + start_ts for ts in meta["relative_timestamps"]]
        video = _read_video_frames(
            video_path, query_ts, self.height, self.width, tolerance_s=1e-4,
        )  # (1, 3, F, H, W)
        return meta, video


# ---- collate ----------------------------------------------------------------

def collate_segment_videos(batch: list) -> tuple[list[dict], torch.Tensor]:
    """Pad videos to the longest temporal dim in the batch and stack.

    Returns ``(metas, batch_tensor)`` where *batch_tensor* is
    ``(B, 3, max_T, H, W)``.
    """
    metas = [item[0] for item in batch]
    videos = [item[1] for item in batch]
    max_t = max(v.shape[2] for v in videos)
    padded = []
    for v in videos:
        pad_t = max_t - v.shape[2]
        if pad_t > 0:
            v = F.pad(v, (0, 0, 0, 0, 0, pad_t), value=0)
        padded.append(v)
    batch_tensor = torch.cat(padded, dim=0)
    return metas, batch_tensor