Download lingbot_test/script/segment_video_dataset.py from LllCCcc/Human-WAM: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/LllCCcc/Human-WAM/resolve/main/lingbot_test/script/segment_video_dataset.py
- Command line
-
hf download hf://datasets/LllCCcc/Human-WAM/lingbot_test/script/segment_video_dataset.py
-
curl -L -o segment_video_dataset.py https://huggingface.co/datasets/LllCCcc/Human-WAM/resolve/main/lingbot_test/script/segment_video_dataset.py
13.9 kB
| """ | |
| 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 | |