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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert RealDatasets MP4 episodes into masked LeRobot v3 datasets.
|
| 3 |
+
|
| 4 |
+
The source tree is read-only. Camera 2 is stored as the wrist camera and
|
| 5 |
+
camera 4 as the front camera. Recorded frames are mapped to a strict 30 Hz
|
| 6 |
+
timeline. Missing timeline slots receive black images, NaN state/action values,
|
| 7 |
+
and false validity masks. Original videos and timestamp metadata are hard-linked
|
| 8 |
+
or copied into each task dataset's ``raw_video`` directory.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import shutil
|
| 19 |
+
import time
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
import av
|
| 25 |
+
import cv2
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pyarrow.dataset as pa_dataset
|
| 28 |
+
from lerobot.configs.video import RGBEncoderConfig
|
| 29 |
+
from lerobot.datasets import LeRobotDataset
|
| 30 |
+
from lerobot.datasets.compute_stats import compute_episode_stats as lerobot_compute_episode_stats
|
| 31 |
+
import lerobot.datasets.dataset_writer as dataset_writer_module
|
| 32 |
+
from tqdm import tqdm
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
TARGET_FPS = 30
|
| 36 |
+
OUTPUT_WIDTH = 848
|
| 37 |
+
OUTPUT_HEIGHT = 480
|
| 38 |
+
SOURCE_WIDTH = 1920
|
| 39 |
+
SOURCE_HEIGHT = 1080
|
| 40 |
+
SOURCE_CROP_WIDTH = 1908
|
| 41 |
+
SOURCE_CROP_LEFT = (SOURCE_WIDTH - SOURCE_CROP_WIDTH) // 2
|
| 42 |
+
|
| 43 |
+
WRIST_KEY = "observation.images.wrist"
|
| 44 |
+
FRONT_KEY = "observation.images.front"
|
| 45 |
+
WRIST_VALID_KEY = "observation.images.wrist_valid"
|
| 46 |
+
FRONT_VALID_KEY = "observation.images.front_valid"
|
| 47 |
+
STATE_KEY = "observation.state"
|
| 48 |
+
STATE_VALID_KEY = "observation.state_valid"
|
| 49 |
+
ACTION_KEY = "action"
|
| 50 |
+
ACTION_VALID_KEY = "action_valid"
|
| 51 |
+
SOURCE_TIMESTAMP_KEY = "source.timestamp"
|
| 52 |
+
SOURCE_RELATIVE_TIMESTAMP_KEY = "source.timestamp_relative"
|
| 53 |
+
SOURCE_ORIGINAL_TIMESTAMP_KEY = "source.original_timestamp"
|
| 54 |
+
SOURCE_ORIGINAL_RELATIVE_TIMESTAMP_KEY = "source.original_timestamp_relative"
|
| 55 |
+
SOURCE_FRAME_INDEX_KEY = "source.frame_index"
|
| 56 |
+
|
| 57 |
+
TASK_NAME_TO_SLUG = {
|
| 58 |
+
"抓娃娃": "pack_sloth",
|
| 59 |
+
"对折毛巾": "fold_cloth",
|
| 60 |
+
"放置绳子": "insert_rope",
|
| 61 |
+
}
|
| 62 |
+
SLUG_TO_TASK_NAME = {slug: name for name, slug in TASK_NAME_TO_SLUG.items()}
|
| 63 |
+
|
| 64 |
+
STATE_NAMES = ["x", "y", "z", "qx", "qy", "qz", "qw", "gripper"]
|
| 65 |
+
ACTION_NAMES = [
|
| 66 |
+
"delta_x",
|
| 67 |
+
"delta_y",
|
| 68 |
+
"delta_z",
|
| 69 |
+
"delta_rx",
|
| 70 |
+
"delta_ry",
|
| 71 |
+
"delta_rz",
|
| 72 |
+
"gripper",
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass(frozen=True)
|
| 77 |
+
class PoseStep:
|
| 78 |
+
position: np.ndarray
|
| 79 |
+
quaternion: np.ndarray
|
| 80 |
+
gripper: float
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@dataclass(frozen=True)
|
| 84 |
+
class Timeline:
|
| 85 |
+
source_to_target: list[int]
|
| 86 |
+
target_to_source: list[int]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass(frozen=True)
|
| 90 |
+
class EpisodeResult:
|
| 91 |
+
source_frames: int
|
| 92 |
+
target_frames: int
|
| 93 |
+
inserted_frames: int
|
| 94 |
+
valid_actions: int
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def parse_args() -> argparse.Namespace:
|
| 98 |
+
parser = argparse.ArgumentParser()
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--data-root",
|
| 101 |
+
type=Path,
|
| 102 |
+
default=Path.home() / "real-datasets-transfer" / "google-drive",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--output-root",
|
| 106 |
+
type=Path,
|
| 107 |
+
default=Path.home() / "real-datasets-transfer" / "lerobot-output",
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument("--repo-id", default="Zili2002/RealDatasets")
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--tasks",
|
| 112 |
+
nargs="+",
|
| 113 |
+
choices=sorted(SLUG_TO_TASK_NAME),
|
| 114 |
+
default=sorted(SLUG_TO_TASK_NAME),
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument("--max-episodes", type=int)
|
| 117 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 118 |
+
parser.add_argument("--skip-raw-video", action="store_true")
|
| 119 |
+
parser.add_argument("--skip-validation", action="store_true")
|
| 120 |
+
parser.add_argument("--image-writer-threads", type=int, default=8)
|
| 121 |
+
parser.add_argument("--encoder-threads", type=int, default=4)
|
| 122 |
+
parser.add_argument("--video-files-size-mb", type=int, default=500)
|
| 123 |
+
parser.add_argument("--data-files-size-mb", type=int, default=100)
|
| 124 |
+
parser.add_argument("--crf", type=int, default=23)
|
| 125 |
+
parser.add_argument("--preset", default="fast")
|
| 126 |
+
return parser.parse_args()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def require_positive(name: str, value: int | None) -> None:
|
| 130 |
+
if value is not None and (isinstance(value, bool) or value <= 0):
|
| 131 |
+
raise ValueError(f"{name} must be positive, got {value!r}")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def install_masked_statistics_hook() -> None:
|
| 135 |
+
"""Exclude invalid rows and black placeholders from LeRobot statistics."""
|
| 136 |
+
|
| 137 |
+
mask_by_feature = {
|
| 138 |
+
WRIST_KEY: WRIST_VALID_KEY,
|
| 139 |
+
FRONT_KEY: FRONT_VALID_KEY,
|
| 140 |
+
STATE_KEY: STATE_VALID_KEY,
|
| 141 |
+
ACTION_KEY: ACTION_VALID_KEY,
|
| 142 |
+
SOURCE_TIMESTAMP_KEY: WRIST_VALID_KEY,
|
| 143 |
+
SOURCE_RELATIVE_TIMESTAMP_KEY: WRIST_VALID_KEY,
|
| 144 |
+
SOURCE_ORIGINAL_TIMESTAMP_KEY: WRIST_VALID_KEY,
|
| 145 |
+
SOURCE_ORIGINAL_RELATIVE_TIMESTAMP_KEY: WRIST_VALID_KEY,
|
| 146 |
+
SOURCE_FRAME_INDEX_KEY: WRIST_VALID_KEY,
|
| 147 |
+
}
|
| 148 |
+
excluded_statistics_features = {
|
| 149 |
+
WRIST_VALID_KEY,
|
| 150 |
+
FRONT_VALID_KEY,
|
| 151 |
+
STATE_VALID_KEY,
|
| 152 |
+
ACTION_VALID_KEY,
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
def masked_compute_episode_stats(
|
| 156 |
+
episode_data: dict[str, Any],
|
| 157 |
+
features: dict[str, dict],
|
| 158 |
+
quantile_list: list[float] | None = None,
|
| 159 |
+
) -> dict:
|
| 160 |
+
filtered_data = dict(episode_data)
|
| 161 |
+
|
| 162 |
+
for feature_key, mask_key in mask_by_feature.items():
|
| 163 |
+
if feature_key not in filtered_data or mask_key not in filtered_data:
|
| 164 |
+
continue
|
| 165 |
+
|
| 166 |
+
mask = np.asarray(filtered_data[mask_key], dtype=bool).reshape(-1)
|
| 167 |
+
values = filtered_data[feature_key]
|
| 168 |
+
if len(values) != len(mask):
|
| 169 |
+
raise ValueError(
|
| 170 |
+
f"Statistics mask mismatch for {feature_key}: "
|
| 171 |
+
f"values={len(values)}, mask={len(mask)}"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if isinstance(values, list):
|
| 175 |
+
filtered_values = [
|
| 176 |
+
value for value, is_valid in zip(values, mask, strict=True) if is_valid
|
| 177 |
+
]
|
| 178 |
+
else:
|
| 179 |
+
filtered_values = np.asarray(values)[mask]
|
| 180 |
+
|
| 181 |
+
if len(filtered_values) < 2:
|
| 182 |
+
raise ValueError(
|
| 183 |
+
f"Need at least two valid values for {feature_key} statistics"
|
| 184 |
+
)
|
| 185 |
+
filtered_data[feature_key] = filtered_values
|
| 186 |
+
|
| 187 |
+
statistics_features = {
|
| 188 |
+
key: value
|
| 189 |
+
for key, value in features.items()
|
| 190 |
+
if key not in excluded_statistics_features
|
| 191 |
+
}
|
| 192 |
+
statistics_data = {
|
| 193 |
+
key: value
|
| 194 |
+
for key, value in filtered_data.items()
|
| 195 |
+
if key in statistics_features
|
| 196 |
+
}
|
| 197 |
+
return lerobot_compute_episode_stats(
|
| 198 |
+
statistics_data,
|
| 199 |
+
statistics_features,
|
| 200 |
+
quantile_list=quantile_list,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
dataset_writer_module.compute_episode_stats = masked_compute_episode_stats
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def task_records(data_root: Path, source_task_name: str) -> list[Path]:
|
| 207 |
+
task_root = data_root / source_task_name
|
| 208 |
+
if not task_root.is_dir():
|
| 209 |
+
raise FileNotFoundError(f"Source task directory is missing: {task_root}")
|
| 210 |
+
|
| 211 |
+
records = []
|
| 212 |
+
for path in task_root.glob("record_*"):
|
| 213 |
+
match = re.fullmatch(r"record_(\d+)", path.name)
|
| 214 |
+
if path.is_dir() and match is not None:
|
| 215 |
+
records.append((int(match.group(1)), path))
|
| 216 |
+
records.sort(key=lambda item: item[0])
|
| 217 |
+
if not records:
|
| 218 |
+
raise ValueError(f"No record_NNN directories found in {task_root}")
|
| 219 |
+
return [path for _, path in records]
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def exactly_one(paths: list[Path], description: str) -> Path:
|
| 223 |
+
if len(paths) != 1:
|
| 224 |
+
raise ValueError(f"Expected one {description}, found {paths}")
|
| 225 |
+
return paths[0]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def source_files(record_dir: Path) -> tuple[Path, Path, Path, Path]:
|
| 229 |
+
action_json = exactly_one(
|
| 230 |
+
sorted((record_dir / "action").glob("action_data_*.json")),
|
| 231 |
+
f"action JSON in {record_dir}",
|
| 232 |
+
)
|
| 233 |
+
timestamps_json = record_dir / "video" / "frame_timestamps.json"
|
| 234 |
+
if not timestamps_json.is_file():
|
| 235 |
+
raise FileNotFoundError(timestamps_json)
|
| 236 |
+
camera_2 = exactly_one(
|
| 237 |
+
sorted((record_dir / "video").glob("camera_2_*.mp4")),
|
| 238 |
+
f"camera 2 MP4 in {record_dir}",
|
| 239 |
+
)
|
| 240 |
+
camera_4 = exactly_one(
|
| 241 |
+
sorted((record_dir / "video").glob("camera_4_*.mp4")),
|
| 242 |
+
f"camera 4 MP4 in {record_dir}",
|
| 243 |
+
)
|
| 244 |
+
return action_json, timestamps_json, camera_2, camera_4
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def load_pose_steps(action_json: Path) -> list[PoseStep]:
|
| 248 |
+
payload = json.loads(action_json.read_text(encoding="utf-8"))
|
| 249 |
+
rows = payload.get("data")
|
| 250 |
+
if not isinstance(rows, list) or len(rows) < 2:
|
| 251 |
+
raise ValueError(f"Invalid or too-short action data: {action_json}")
|
| 252 |
+
|
| 253 |
+
steps: list[PoseStep] = []
|
| 254 |
+
for index, row in enumerate(rows):
|
| 255 |
+
try:
|
| 256 |
+
pose = row["end_effector_pose"]
|
| 257 |
+
position = pose["position"]
|
| 258 |
+
orientation = pose["orientation"]
|
| 259 |
+
xyz = np.asarray(
|
| 260 |
+
[position["x"], position["y"], position["z"]],
|
| 261 |
+
dtype=np.float64,
|
| 262 |
+
)
|
| 263 |
+
quaternion = np.asarray(
|
| 264 |
+
[
|
| 265 |
+
orientation["x"],
|
| 266 |
+
orientation["y"],
|
| 267 |
+
orientation["z"],
|
| 268 |
+
orientation["w"],
|
| 269 |
+
],
|
| 270 |
+
dtype=np.float64,
|
| 271 |
+
)
|
| 272 |
+
gripper = float(row["gripper_command"])
|
| 273 |
+
except (KeyError, TypeError, ValueError) as error:
|
| 274 |
+
raise ValueError(f"Bad pose at {action_json} row {index}") from error
|
| 275 |
+
|
| 276 |
+
if (
|
| 277 |
+
not np.isfinite(xyz).all()
|
| 278 |
+
or not np.isfinite(quaternion).all()
|
| 279 |
+
or not math.isfinite(gripper)
|
| 280 |
+
):
|
| 281 |
+
raise ValueError(f"Non-finite pose at {action_json} row {index}")
|
| 282 |
+
|
| 283 |
+
norm = float(np.linalg.norm(quaternion))
|
| 284 |
+
if norm < 1e-8:
|
| 285 |
+
raise ValueError(f"Zero quaternion at {action_json} row {index}")
|
| 286 |
+
quaternion /= norm
|
| 287 |
+
if steps and float(np.dot(steps[-1].quaternion, quaternion)) < 0.0:
|
| 288 |
+
quaternion = -quaternion
|
| 289 |
+
steps.append(PoseStep(xyz, quaternion, gripper))
|
| 290 |
+
|
| 291 |
+
return steps
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def load_timestamps(timestamps_json: Path) -> tuple[dict[str, Any], list[float]]:
|
| 295 |
+
metadata = json.loads(timestamps_json.read_text(encoding="utf-8"))
|
| 296 |
+
timestamps = metadata.get("timestamps_unix")
|
| 297 |
+
if not isinstance(timestamps, list) or len(timestamps) < 2:
|
| 298 |
+
raise ValueError(f"Invalid timestamps: {timestamps_json}")
|
| 299 |
+
parsed = [float(value) for value in timestamps]
|
| 300 |
+
if not np.isfinite(np.asarray(parsed)).all():
|
| 301 |
+
raise ValueError(f"Non-finite timestamps: {timestamps_json}")
|
| 302 |
+
if any(current <= previous for previous, current in zip(parsed, parsed[1:])):
|
| 303 |
+
raise ValueError(f"Timestamps are not strictly increasing: {timestamps_json}")
|
| 304 |
+
return metadata, parsed
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def build_timeline(timestamps: list[float]) -> Timeline:
|
| 308 |
+
start = timestamps[0]
|
| 309 |
+
source_to_target: list[int] = []
|
| 310 |
+
previous_slot = -1
|
| 311 |
+
|
| 312 |
+
for timestamp in timestamps:
|
| 313 |
+
relative = (timestamp - start) * TARGET_FPS
|
| 314 |
+
ideal_slot = int(math.floor(relative + 0.5))
|
| 315 |
+
slot = max(ideal_slot, previous_slot + 1)
|
| 316 |
+
source_to_target.append(slot)
|
| 317 |
+
previous_slot = slot
|
| 318 |
+
|
| 319 |
+
target_to_source = [-1] * (source_to_target[-1] + 1)
|
| 320 |
+
for source_index, target_index in enumerate(source_to_target):
|
| 321 |
+
if target_to_source[target_index] != -1:
|
| 322 |
+
raise RuntimeError(f"Duplicate target timeline index: {target_index}")
|
| 323 |
+
target_to_source[target_index] = source_index
|
| 324 |
+
|
| 325 |
+
return Timeline(source_to_target, target_to_source)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def quaternion_inverse(quaternion: np.ndarray) -> np.ndarray:
|
| 329 |
+
result = quaternion.copy()
|
| 330 |
+
result[:3] *= -1.0
|
| 331 |
+
return result
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def quaternion_multiply(left: np.ndarray, right: np.ndarray) -> np.ndarray:
|
| 335 |
+
lx, ly, lz, lw = left
|
| 336 |
+
rx, ry, rz, rw = right
|
| 337 |
+
return np.asarray(
|
| 338 |
+
[
|
| 339 |
+
lw * rx + lx * rw + ly * rz - lz * ry,
|
| 340 |
+
lw * ry - lx * rz + ly * rw + lz * rx,
|
| 341 |
+
lw * rz + lx * ry - ly * rx + lz * rw,
|
| 342 |
+
lw * rw - lx * rx - ly * ry - lz * rz,
|
| 343 |
+
],
|
| 344 |
+
dtype=np.float64,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def quaternion_to_rotation_vector(quaternion: np.ndarray) -> np.ndarray:
|
| 349 |
+
quaternion = quaternion / np.linalg.norm(quaternion)
|
| 350 |
+
if quaternion[3] < 0.0:
|
| 351 |
+
quaternion = -quaternion
|
| 352 |
+
vector = quaternion[:3]
|
| 353 |
+
vector_norm = float(np.linalg.norm(vector))
|
| 354 |
+
if vector_norm < 1e-10:
|
| 355 |
+
return 2.0 * vector
|
| 356 |
+
angle = 2.0 * math.atan2(vector_norm, float(quaternion[3]))
|
| 357 |
+
return vector / vector_norm * angle
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def make_state(step: PoseStep) -> np.ndarray:
|
| 361 |
+
return np.asarray(
|
| 362 |
+
[*step.position, *step.quaternion, step.gripper],
|
| 363 |
+
dtype=np.float32,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def make_action(current: PoseStep, following: PoseStep) -> np.ndarray:
|
| 368 |
+
delta_position = following.position - current.position
|
| 369 |
+
delta_quaternion = quaternion_multiply(
|
| 370 |
+
quaternion_inverse(current.quaternion),
|
| 371 |
+
following.quaternion,
|
| 372 |
+
)
|
| 373 |
+
delta_rotation = quaternion_to_rotation_vector(delta_quaternion)
|
| 374 |
+
return np.asarray(
|
| 375 |
+
[*delta_position, *delta_rotation, following.gripper],
|
| 376 |
+
dtype=np.float32,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def make_terminal_action(step: PoseStep) -> np.ndarray:
|
| 381 |
+
return np.asarray(
|
| 382 |
+
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, step.gripper],
|
| 383 |
+
dtype=np.float32,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def process_video_frame(frame: av.VideoFrame, path: Path, frame_index: int) -> np.ndarray:
|
| 388 |
+
image = frame.to_ndarray(format="rgb24")
|
| 389 |
+
if image.shape != (SOURCE_HEIGHT, SOURCE_WIDTH, 3):
|
| 390 |
+
raise ValueError(
|
| 391 |
+
f"Unexpected frame shape in {path} at {frame_index}: {image.shape}"
|
| 392 |
+
)
|
| 393 |
+
cropped = image[
|
| 394 |
+
:,
|
| 395 |
+
SOURCE_CROP_LEFT : SOURCE_CROP_LEFT + SOURCE_CROP_WIDTH,
|
| 396 |
+
:,
|
| 397 |
+
]
|
| 398 |
+
resized = cv2.resize(
|
| 399 |
+
cropped,
|
| 400 |
+
(OUTPUT_WIDTH, OUTPUT_HEIGHT),
|
| 401 |
+
interpolation=cv2.INTER_AREA,
|
| 402 |
+
)
|
| 403 |
+
return np.ascontiguousarray(resized, dtype=np.uint8)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def link_or_copy(source: Path, destination: Path) -> None:
|
| 407 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 408 |
+
if destination.exists():
|
| 409 |
+
if destination.samefile(source):
|
| 410 |
+
return
|
| 411 |
+
raise FileExistsError(destination)
|
| 412 |
+
try:
|
| 413 |
+
os.link(source, destination)
|
| 414 |
+
except OSError:
|
| 415 |
+
shutil.copy2(source, destination)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def save_raw_video(
|
| 419 |
+
task_output_root: Path,
|
| 420 |
+
record_dir: Path,
|
| 421 |
+
timestamps_json: Path,
|
| 422 |
+
camera_2: Path,
|
| 423 |
+
camera_4: Path,
|
| 424 |
+
timeline: Timeline,
|
| 425 |
+
) -> None:
|
| 426 |
+
raw_record_root = task_output_root / "raw_video" / record_dir.name
|
| 427 |
+
raw_record_root.mkdir(parents=True, exist_ok=True)
|
| 428 |
+
for source in (timestamps_json, camera_2, camera_4):
|
| 429 |
+
link_or_copy(source, raw_record_root / source.name)
|
| 430 |
+
|
| 431 |
+
mapping = {
|
| 432 |
+
"target_fps": TARGET_FPS,
|
| 433 |
+
"source_frame_count": len(timeline.source_to_target),
|
| 434 |
+
"target_frame_count": len(timeline.target_to_source),
|
| 435 |
+
"inserted_frame_count": timeline.target_to_source.count(-1),
|
| 436 |
+
"source_frame_to_target_index": timeline.source_to_target,
|
| 437 |
+
"target_to_source_frame_index": timeline.target_to_source,
|
| 438 |
+
"image_valid": [index >= 0 for index in timeline.target_to_source],
|
| 439 |
+
}
|
| 440 |
+
mapping_path = raw_record_root / "timeline_30hz.json"
|
| 441 |
+
temporary = mapping_path.with_suffix(".json.tmp")
|
| 442 |
+
temporary.write_text(
|
| 443 |
+
json.dumps(mapping, ensure_ascii=False, separators=(",", ":")),
|
| 444 |
+
encoding="utf-8",
|
| 445 |
+
)
|
| 446 |
+
os.replace(temporary, mapping_path)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def features() -> dict[str, dict[str, Any]]:
|
| 450 |
+
vector_name = lambda values: {"axes": values}
|
| 451 |
+
scalar_name = lambda value: {"axes": [value]}
|
| 452 |
+
return {
|
| 453 |
+
WRIST_KEY: {
|
| 454 |
+
"dtype": "video",
|
| 455 |
+
"shape": (OUTPUT_HEIGHT, OUTPUT_WIDTH, 3),
|
| 456 |
+
"names": ["height", "width", "channels"],
|
| 457 |
+
},
|
| 458 |
+
FRONT_KEY: {
|
| 459 |
+
"dtype": "video",
|
| 460 |
+
"shape": (OUTPUT_HEIGHT, OUTPUT_WIDTH, 3),
|
| 461 |
+
"names": ["height", "width", "channels"],
|
| 462 |
+
},
|
| 463 |
+
STATE_KEY: {
|
| 464 |
+
"dtype": "float32",
|
| 465 |
+
"shape": (8,),
|
| 466 |
+
"names": vector_name(STATE_NAMES),
|
| 467 |
+
},
|
| 468 |
+
ACTION_KEY: {
|
| 469 |
+
"dtype": "float32",
|
| 470 |
+
"shape": (7,),
|
| 471 |
+
"names": vector_name(ACTION_NAMES),
|
| 472 |
+
},
|
| 473 |
+
SOURCE_TIMESTAMP_KEY: {
|
| 474 |
+
"dtype": "float64",
|
| 475 |
+
"shape": (1,),
|
| 476 |
+
"names": scalar_name("unix_seconds"),
|
| 477 |
+
},
|
| 478 |
+
SOURCE_RELATIVE_TIMESTAMP_KEY: {
|
| 479 |
+
"dtype": "float64",
|
| 480 |
+
"shape": (1,),
|
| 481 |
+
"names": scalar_name("seconds"),
|
| 482 |
+
},
|
| 483 |
+
SOURCE_ORIGINAL_TIMESTAMP_KEY: {
|
| 484 |
+
"dtype": "float64",
|
| 485 |
+
"shape": (1,),
|
| 486 |
+
"names": scalar_name("unix_seconds"),
|
| 487 |
+
},
|
| 488 |
+
SOURCE_ORIGINAL_RELATIVE_TIMESTAMP_KEY: {
|
| 489 |
+
"dtype": "float64",
|
| 490 |
+
"shape": (1,),
|
| 491 |
+
"names": scalar_name("seconds"),
|
| 492 |
+
},
|
| 493 |
+
SOURCE_FRAME_INDEX_KEY: {
|
| 494 |
+
"dtype": "int64",
|
| 495 |
+
"shape": (1,),
|
| 496 |
+
"names": scalar_name("index"),
|
| 497 |
+
},
|
| 498 |
+
WRIST_VALID_KEY: {
|
| 499 |
+
"dtype": "bool",
|
| 500 |
+
"shape": (1,),
|
| 501 |
+
"names": scalar_name("valid"),
|
| 502 |
+
},
|
| 503 |
+
FRONT_VALID_KEY: {
|
| 504 |
+
"dtype": "bool",
|
| 505 |
+
"shape": (1,),
|
| 506 |
+
"names": scalar_name("valid"),
|
| 507 |
+
},
|
| 508 |
+
STATE_VALID_KEY: {
|
| 509 |
+
"dtype": "bool",
|
| 510 |
+
"shape": (1,),
|
| 511 |
+
"names": scalar_name("valid"),
|
| 512 |
+
},
|
| 513 |
+
ACTION_VALID_KEY: {
|
| 514 |
+
"dtype": "bool",
|
| 515 |
+
"shape": (1,),
|
| 516 |
+
"names": scalar_name("valid"),
|
| 517 |
+
},
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def create_dataset(
|
| 522 |
+
root: Path,
|
| 523 |
+
repo_id: str,
|
| 524 |
+
args: argparse.Namespace,
|
| 525 |
+
) -> LeRobotDataset:
|
| 526 |
+
encoder = RGBEncoderConfig(
|
| 527 |
+
vcodec="h264",
|
| 528 |
+
pix_fmt="yuv420p",
|
| 529 |
+
g=2,
|
| 530 |
+
crf=args.crf,
|
| 531 |
+
preset=args.preset,
|
| 532 |
+
)
|
| 533 |
+
return LeRobotDataset.create(
|
| 534 |
+
repo_id=repo_id,
|
| 535 |
+
root=root,
|
| 536 |
+
robot_type="fr3",
|
| 537 |
+
fps=TARGET_FPS,
|
| 538 |
+
features=features(),
|
| 539 |
+
use_videos=True,
|
| 540 |
+
video_backend="pyav",
|
| 541 |
+
image_writer_threads=args.image_writer_threads,
|
| 542 |
+
streaming_encoding=False,
|
| 543 |
+
encoder_threads=args.encoder_threads,
|
| 544 |
+
rgb_encoder=encoder,
|
| 545 |
+
metadata_buffer_size=10,
|
| 546 |
+
video_files_size_in_mb=args.video_files_size_mb,
|
| 547 |
+
data_files_size_in_mb=args.data_files_size_mb,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def process_episode(
|
| 552 |
+
dataset: LeRobotDataset,
|
| 553 |
+
task_output_root: Path,
|
| 554 |
+
task_slug: str,
|
| 555 |
+
record_dir: Path,
|
| 556 |
+
copy_raw_video: bool,
|
| 557 |
+
) -> EpisodeResult:
|
| 558 |
+
action_json, timestamps_json, camera_2_path, camera_4_path = source_files(
|
| 559 |
+
record_dir
|
| 560 |
+
)
|
| 561 |
+
steps = load_pose_steps(action_json)
|
| 562 |
+
timestamp_metadata, timestamps = load_timestamps(timestamps_json)
|
| 563 |
+
timeline = build_timeline(timestamps)
|
| 564 |
+
|
| 565 |
+
expected_count = len(steps)
|
| 566 |
+
if len(timestamps) != expected_count:
|
| 567 |
+
raise ValueError(
|
| 568 |
+
f"Action/timestamp mismatch in {record_dir}: "
|
| 569 |
+
f"actions={expected_count}, timestamps={len(timestamps)}"
|
| 570 |
+
)
|
| 571 |
+
if int(timestamp_metadata.get("frame_count", -1)) != expected_count:
|
| 572 |
+
raise ValueError(
|
| 573 |
+
f"Timestamp metadata count mismatch in {record_dir}: "
|
| 574 |
+
f"metadata={timestamp_metadata.get('frame_count')}, expected={expected_count}"
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
source_actions = [
|
| 578 |
+
make_action(steps[index], steps[index + 1])
|
| 579 |
+
for index in range(expected_count - 1)
|
| 580 |
+
]
|
| 581 |
+
source_actions.append(make_terminal_action(steps[-1]))
|
| 582 |
+
|
| 583 |
+
black_image = np.zeros(
|
| 584 |
+
(OUTPUT_HEIGHT, OUTPUT_WIDTH, 3),
|
| 585 |
+
dtype=np.uint8,
|
| 586 |
+
)
|
| 587 |
+
nan_state = np.full(8, np.nan, dtype=np.float32)
|
| 588 |
+
nan_action = np.full(7, np.nan, dtype=np.float32)
|
| 589 |
+
start_timestamp = timestamps[0]
|
| 590 |
+
valid_actions = 0
|
| 591 |
+
|
| 592 |
+
with av.open(str(camera_2_path)) as camera_2_container, av.open(
|
| 593 |
+
str(camera_4_path)
|
| 594 |
+
) as camera_4_container:
|
| 595 |
+
camera_2_frames = iter(camera_2_container.decode(video=0))
|
| 596 |
+
camera_4_frames = iter(camera_4_container.decode(video=0))
|
| 597 |
+
|
| 598 |
+
for target_index, source_index in enumerate(timeline.target_to_source):
|
| 599 |
+
nominal_relative = target_index / TARGET_FPS
|
| 600 |
+
nominal_timestamp = start_timestamp + nominal_relative
|
| 601 |
+
|
| 602 |
+
if source_index < 0:
|
| 603 |
+
wrist_image = black_image
|
| 604 |
+
front_image = black_image
|
| 605 |
+
state = nan_state
|
| 606 |
+
action = nan_action
|
| 607 |
+
original_timestamp = math.nan
|
| 608 |
+
original_relative = math.nan
|
| 609 |
+
image_valid = False
|
| 610 |
+
state_valid = False
|
| 611 |
+
action_valid = False
|
| 612 |
+
else:
|
| 613 |
+
try:
|
| 614 |
+
camera_2_frame = next(camera_2_frames)
|
| 615 |
+
camera_4_frame = next(camera_4_frames)
|
| 616 |
+
except StopIteration as error:
|
| 617 |
+
raise ValueError(
|
| 618 |
+
f"Video ended before frame {source_index} in {record_dir}"
|
| 619 |
+
) from error
|
| 620 |
+
|
| 621 |
+
wrist_image = process_video_frame(
|
| 622 |
+
camera_2_frame,
|
| 623 |
+
camera_2_path,
|
| 624 |
+
source_index,
|
| 625 |
+
)
|
| 626 |
+
front_image = process_video_frame(
|
| 627 |
+
camera_4_frame,
|
| 628 |
+
camera_4_path,
|
| 629 |
+
source_index,
|
| 630 |
+
)
|
| 631 |
+
state = make_state(steps[source_index])
|
| 632 |
+
action = source_actions[source_index]
|
| 633 |
+
original_timestamp = timestamps[source_index]
|
| 634 |
+
original_relative = original_timestamp - start_timestamp
|
| 635 |
+
image_valid = True
|
| 636 |
+
state_valid = True
|
| 637 |
+
|
| 638 |
+
action_valid = True
|
| 639 |
+
valid_actions += 1
|
| 640 |
+
|
| 641 |
+
dataset.add_frame(
|
| 642 |
+
{
|
| 643 |
+
WRIST_KEY: wrist_image,
|
| 644 |
+
FRONT_KEY: front_image,
|
| 645 |
+
STATE_KEY: state,
|
| 646 |
+
ACTION_KEY: action,
|
| 647 |
+
SOURCE_TIMESTAMP_KEY: np.asarray(
|
| 648 |
+
[nominal_timestamp],
|
| 649 |
+
dtype=np.float64,
|
| 650 |
+
),
|
| 651 |
+
SOURCE_RELATIVE_TIMESTAMP_KEY: np.asarray(
|
| 652 |
+
[nominal_relative],
|
| 653 |
+
dtype=np.float64,
|
| 654 |
+
),
|
| 655 |
+
SOURCE_ORIGINAL_TIMESTAMP_KEY: np.asarray(
|
| 656 |
+
[original_timestamp],
|
| 657 |
+
dtype=np.float64,
|
| 658 |
+
),
|
| 659 |
+
SOURCE_ORIGINAL_RELATIVE_TIMESTAMP_KEY: np.asarray(
|
| 660 |
+
[original_relative],
|
| 661 |
+
dtype=np.float64,
|
| 662 |
+
),
|
| 663 |
+
SOURCE_FRAME_INDEX_KEY: np.asarray(
|
| 664 |
+
[source_index],
|
| 665 |
+
dtype=np.int64,
|
| 666 |
+
),
|
| 667 |
+
WRIST_VALID_KEY: np.asarray([image_valid], dtype=np.bool_),
|
| 668 |
+
FRONT_VALID_KEY: np.asarray([image_valid], dtype=np.bool_),
|
| 669 |
+
STATE_VALID_KEY: np.asarray([state_valid], dtype=np.bool_),
|
| 670 |
+
ACTION_VALID_KEY: np.asarray([action_valid], dtype=np.bool_),
|
| 671 |
+
"task": task_slug,
|
| 672 |
+
}
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
if next(camera_2_frames, None) is not None:
|
| 676 |
+
raise ValueError(f"Camera 2 has extra frames in {record_dir}")
|
| 677 |
+
if next(camera_4_frames, None) is not None:
|
| 678 |
+
raise ValueError(f"Camera 4 has extra frames in {record_dir}")
|
| 679 |
+
|
| 680 |
+
dataset.save_episode(parallel_encoding=True)
|
| 681 |
+
|
| 682 |
+
if copy_raw_video:
|
| 683 |
+
save_raw_video(
|
| 684 |
+
task_output_root,
|
| 685 |
+
record_dir,
|
| 686 |
+
timestamps_json,
|
| 687 |
+
camera_2_path,
|
| 688 |
+
camera_4_path,
|
| 689 |
+
timeline,
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
return EpisodeResult(
|
| 693 |
+
source_frames=expected_count,
|
| 694 |
+
target_frames=len(timeline.target_to_source),
|
| 695 |
+
inserted_frames=timeline.target_to_source.count(-1),
|
| 696 |
+
valid_actions=valid_actions,
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def assert_no_nan_stats(path: Path) -> None:
|
| 701 |
+
stats = json.loads(path.read_text(encoding="utf-8"))
|
| 702 |
+
|
| 703 |
+
def visit(value: Any, location: str) -> None:
|
| 704 |
+
if isinstance(value, dict):
|
| 705 |
+
for key, item in value.items():
|
| 706 |
+
visit(item, f"{location}.{key}")
|
| 707 |
+
elif isinstance(value, list):
|
| 708 |
+
for index, item in enumerate(value):
|
| 709 |
+
visit(item, f"{location}[{index}]")
|
| 710 |
+
elif isinstance(value, float) and not math.isfinite(value):
|
| 711 |
+
raise ValueError(f"Non-finite statistic at {location}: {value}")
|
| 712 |
+
|
| 713 |
+
visit(stats, "stats")
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def validate_task_output(
|
| 717 |
+
task_root: Path,
|
| 718 |
+
repo_id: str,
|
| 719 |
+
expected_episodes: int,
|
| 720 |
+
expected_source_frames: int,
|
| 721 |
+
expected_target_frames: int,
|
| 722 |
+
) -> None:
|
| 723 |
+
assert_no_nan_stats(task_root / "meta" / "stats.json")
|
| 724 |
+
|
| 725 |
+
table = pa_dataset.dataset(task_root / "data", format="parquet").to_table(
|
| 726 |
+
columns=[
|
| 727 |
+
"episode_index",
|
| 728 |
+
SOURCE_FRAME_INDEX_KEY,
|
| 729 |
+
WRIST_VALID_KEY,
|
| 730 |
+
FRONT_VALID_KEY,
|
| 731 |
+
STATE_KEY,
|
| 732 |
+
STATE_VALID_KEY,
|
| 733 |
+
ACTION_KEY,
|
| 734 |
+
ACTION_VALID_KEY,
|
| 735 |
+
]
|
| 736 |
+
)
|
| 737 |
+
if table.num_rows != expected_target_frames:
|
| 738 |
+
raise ValueError(
|
| 739 |
+
f"Parquet frame count mismatch: {table.num_rows} != "
|
| 740 |
+
f"{expected_target_frames}"
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
rows = table.to_pylist()
|
| 744 |
+
real_rows = 0
|
| 745 |
+
for row_index, row in enumerate(rows):
|
| 746 |
+
source_index = int(row[SOURCE_FRAME_INDEX_KEY])
|
| 747 |
+
wrist_valid = bool(row[WRIST_VALID_KEY])
|
| 748 |
+
front_valid = bool(row[FRONT_VALID_KEY])
|
| 749 |
+
state_valid = bool(row[STATE_VALID_KEY])
|
| 750 |
+
action_valid = bool(row[ACTION_VALID_KEY])
|
| 751 |
+
state = np.asarray(row[STATE_KEY], dtype=np.float32)
|
| 752 |
+
action = np.asarray(row[ACTION_KEY], dtype=np.float32)
|
| 753 |
+
|
| 754 |
+
if wrist_valid != front_valid:
|
| 755 |
+
raise ValueError(f"Camera validity mismatch at row {row_index}")
|
| 756 |
+
if source_index < 0:
|
| 757 |
+
if wrist_valid or state_valid or action_valid:
|
| 758 |
+
raise ValueError(f"Invalid inserted-row mask at row {row_index}")
|
| 759 |
+
if not np.isnan(state).all() or not np.isnan(action).all():
|
| 760 |
+
raise ValueError(f"Inserted row is not NaN-filled at row {row_index}")
|
| 761 |
+
else:
|
| 762 |
+
real_rows += 1
|
| 763 |
+
if not wrist_valid or not state_valid:
|
| 764 |
+
raise ValueError(f"Invalid real-row mask at row {row_index}")
|
| 765 |
+
if not np.isfinite(state).all() or not np.isfinite(action).all():
|
| 766 |
+
raise ValueError(f"Real row has non-finite data at row {row_index}")
|
| 767 |
+
|
| 768 |
+
if real_rows != expected_source_frames:
|
| 769 |
+
raise ValueError(
|
| 770 |
+
f"Real frame count mismatch: {real_rows} != {expected_source_frames}"
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
for video_key in (WRIST_KEY, FRONT_KEY):
|
| 774 |
+
video_root = task_root / "videos" / video_key
|
| 775 |
+
video_frames = 0
|
| 776 |
+
for video_path in sorted(video_root.rglob("*.mp4")):
|
| 777 |
+
with av.open(str(video_path)) as container:
|
| 778 |
+
stream = container.streams.video[0]
|
| 779 |
+
frame_count = int(stream.frames or 0)
|
| 780 |
+
if frame_count == 0:
|
| 781 |
+
frame_count = sum(1 for _ in container.decode(video=0))
|
| 782 |
+
video_frames += frame_count
|
| 783 |
+
if (stream.width, stream.height) != (OUTPUT_WIDTH, OUTPUT_HEIGHT):
|
| 784 |
+
raise ValueError(
|
| 785 |
+
f"Unexpected output dimensions in {video_path}: "
|
| 786 |
+
f"{stream.width}x{stream.height}"
|
| 787 |
+
)
|
| 788 |
+
if video_frames != expected_target_frames:
|
| 789 |
+
raise ValueError(
|
| 790 |
+
f"{video_key} frame count mismatch: {video_frames} != "
|
| 791 |
+
f"{expected_target_frames}"
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
loaded = LeRobotDataset(
|
| 795 |
+
repo_id=repo_id,
|
| 796 |
+
root=task_root,
|
| 797 |
+
video_backend="pyav",
|
| 798 |
+
return_uint8=True,
|
| 799 |
+
)
|
| 800 |
+
if loaded.meta.total_episodes != expected_episodes:
|
| 801 |
+
raise ValueError(
|
| 802 |
+
f"Loaded episode count mismatch: {loaded.meta.total_episodes} != "
|
| 803 |
+
f"{expected_episodes}"
|
| 804 |
+
)
|
| 805 |
+
if len(loaded) != expected_target_frames:
|
| 806 |
+
raise ValueError(
|
| 807 |
+
f"Loaded frame count mismatch: {len(loaded)} != "
|
| 808 |
+
f"{expected_target_frames}"
|
| 809 |
+
)
|
| 810 |
+
sample_indices = sorted({0, len(loaded) // 2, len(loaded) - 1})
|
| 811 |
+
for index in sample_indices:
|
| 812 |
+
sample = loaded[index]
|
| 813 |
+
for video_key in (WRIST_KEY, FRONT_KEY):
|
| 814 |
+
if tuple(sample[video_key].shape) != (3, OUTPUT_HEIGHT, OUTPUT_WIDTH):
|
| 815 |
+
raise ValueError(
|
| 816 |
+
f"Unexpected loaded image shape for {video_key} at {index}: "
|
| 817 |
+
f"{tuple(sample[video_key].shape)}"
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def convert_task(
|
| 822 |
+
args: argparse.Namespace,
|
| 823 |
+
task_slug: str,
|
| 824 |
+
) -> None:
|
| 825 |
+
source_task_name = SLUG_TO_TASK_NAME[task_slug]
|
| 826 |
+
records = task_records(args.data_root, source_task_name)
|
| 827 |
+
if args.max_episodes is not None:
|
| 828 |
+
records = records[: args.max_episodes]
|
| 829 |
+
|
| 830 |
+
task_output_root = args.output_root / task_slug
|
| 831 |
+
if task_output_root.exists():
|
| 832 |
+
if not args.overwrite:
|
| 833 |
+
raise FileExistsError(
|
| 834 |
+
f"Output exists; pass --overwrite to replace it: {task_output_root}"
|
| 835 |
+
)
|
| 836 |
+
shutil.rmtree(task_output_root)
|
| 837 |
+
task_output_root.parent.mkdir(parents=True, exist_ok=True)
|
| 838 |
+
|
| 839 |
+
dataset = create_dataset(task_output_root, args.repo_id, args)
|
| 840 |
+
source_frames = 0
|
| 841 |
+
target_frames = 0
|
| 842 |
+
inserted_frames = 0
|
| 843 |
+
valid_actions = 0
|
| 844 |
+
started = time.monotonic()
|
| 845 |
+
|
| 846 |
+
try:
|
| 847 |
+
for record_dir in tqdm(records, desc=task_slug):
|
| 848 |
+
result = process_episode(
|
| 849 |
+
dataset,
|
| 850 |
+
task_output_root,
|
| 851 |
+
task_slug,
|
| 852 |
+
record_dir,
|
| 853 |
+
copy_raw_video=not args.skip_raw_video,
|
| 854 |
+
)
|
| 855 |
+
source_frames += result.source_frames
|
| 856 |
+
target_frames += result.target_frames
|
| 857 |
+
inserted_frames += result.inserted_frames
|
| 858 |
+
valid_actions += result.valid_actions
|
| 859 |
+
print(
|
| 860 |
+
f"{task_slug}/{record_dir.name}: "
|
| 861 |
+
f"source={result.source_frames} target={result.target_frames} "
|
| 862 |
+
f"inserted={result.inserted_frames} "
|
| 863 |
+
f"valid_actions={result.valid_actions}",
|
| 864 |
+
flush=True,
|
| 865 |
+
)
|
| 866 |
+
finally:
|
| 867 |
+
dataset.finalize()
|
| 868 |
+
|
| 869 |
+
elapsed = time.monotonic() - started
|
| 870 |
+
summary = {
|
| 871 |
+
"task": task_slug,
|
| 872 |
+
"source_task": source_task_name,
|
| 873 |
+
"episodes": len(records),
|
| 874 |
+
"source_frames": source_frames,
|
| 875 |
+
"target_frames": target_frames,
|
| 876 |
+
"inserted_frames": inserted_frames,
|
| 877 |
+
"valid_actions": valid_actions,
|
| 878 |
+
"fps": TARGET_FPS,
|
| 879 |
+
"width": OUTPUT_WIDTH,
|
| 880 |
+
"height": OUTPUT_HEIGHT,
|
| 881 |
+
"elapsed_seconds": elapsed,
|
| 882 |
+
}
|
| 883 |
+
(task_output_root / "conversion_summary.json").write_text(
|
| 884 |
+
json.dumps(summary, ensure_ascii=False, indent=2),
|
| 885 |
+
encoding="utf-8",
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
if not args.skip_validation:
|
| 889 |
+
validate_task_output(
|
| 890 |
+
task_output_root,
|
| 891 |
+
args.repo_id,
|
| 892 |
+
expected_episodes=len(records),
|
| 893 |
+
expected_source_frames=source_frames,
|
| 894 |
+
expected_target_frames=target_frames,
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
print(json.dumps(summary, ensure_ascii=False), flush=True)
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
def main() -> None:
|
| 901 |
+
args = parse_args()
|
| 902 |
+
require_positive("--max-episodes", args.max_episodes)
|
| 903 |
+
require_positive("--image-writer-threads", args.image_writer_threads)
|
| 904 |
+
require_positive("--encoder-threads", args.encoder_threads)
|
| 905 |
+
require_positive("--video-files-size-mb", args.video_files_size_mb)
|
| 906 |
+
require_positive("--data-files-size-mb", args.data_files_size_mb)
|
| 907 |
+
|
| 908 |
+
args.data_root = args.data_root.expanduser().resolve()
|
| 909 |
+
args.output_root = args.output_root.expanduser().resolve()
|
| 910 |
+
if not args.data_root.is_dir():
|
| 911 |
+
raise FileNotFoundError(args.data_root)
|
| 912 |
+
if args.output_root == args.data_root or args.data_root in args.output_root.parents:
|
| 913 |
+
raise ValueError("Output root must not be inside the source data root")
|
| 914 |
+
|
| 915 |
+
av.logging.set_level(av.logging.ERROR)
|
| 916 |
+
cv2.setNumThreads(1)
|
| 917 |
+
cv2.ocl.setUseOpenCL(False)
|
| 918 |
+
install_masked_statistics_hook()
|
| 919 |
+
|
| 920 |
+
for task_slug in args.tasks:
|
| 921 |
+
convert_task(args, task_slug)
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
if __name__ == "__main__":
|
| 925 |
+
main()
|