Delete convert_to_lerobot.py
Browse files- convert_to_lerobot.py +0 -666
convert_to_lerobot.py
DELETED
|
@@ -1,666 +0,0 @@
|
|
| 1 |
-
"""Convert pick_apple raw data to LeRobot v3.0 dataset format.
|
| 2 |
-
|
| 3 |
-
This script converts raw robot demonstration data (robot_data.csv + camera images)
|
| 4 |
-
to the LeRobot v3.0 dataset format.
|
| 5 |
-
|
| 6 |
-
Language instructions are stored as raw text in the parquet under the `task`
|
| 7 |
-
column (and indexed via `meta/tasks.parquet`). Token IDs / attention masks are
|
| 8 |
-
generated dynamically at training time by the model's tokenizer/collator.
|
| 9 |
-
|
| 10 |
-
Usage:
|
| 11 |
-
conda activate lerobot_env
|
| 12 |
-
python examples/learning_il/convert_pick_apple.py --input pick_apple --output data/pick_apple_lerobot
|
| 13 |
-
|
| 14 |
-
Data structure expected:
|
| 15 |
-
pick_apple/
|
| 16 |
-
├── episode_002/
|
| 17 |
-
│ ├── metadata.json
|
| 18 |
-
│ ├── robot_data.csv
|
| 19 |
-
│ ├── cam_head/
|
| 20 |
-
│ │ ├── 0.jpg, 1.jpg, ...
|
| 21 |
-
│ └── cam_wrist/
|
| 22 |
-
│ ├── 0.jpg, 1.jpg, ...
|
| 23 |
-
...
|
| 24 |
-
|
| 25 |
-
LeRobot v3.0 output structure:
|
| 26 |
-
data/pick_apple_lerobot/
|
| 27 |
-
├── data/
|
| 28 |
-
│ └── chunk-000/
|
| 29 |
-
│ └── file-000.parquet
|
| 30 |
-
├── videos/
|
| 31 |
-
│ └── chunk-000/
|
| 32 |
-
│ ├── observation.images.cam_head/
|
| 33 |
-
│ │ └── file-000.mp4
|
| 34 |
-
│ └── observation.images.cam_wrist/
|
| 35 |
-
│ └── file-000.mp4
|
| 36 |
-
└── meta/
|
| 37 |
-
├── info.json
|
| 38 |
-
├── stats.json
|
| 39 |
-
├── tasks.parquet
|
| 40 |
-
└── episodes/
|
| 41 |
-
└── chunk-000/
|
| 42 |
-
└── file-000.parquet
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
import argparse
|
| 46 |
-
import json
|
| 47 |
-
import shutil
|
| 48 |
-
from pathlib import Path
|
| 49 |
-
|
| 50 |
-
import cv2
|
| 51 |
-
import numpy as np
|
| 52 |
-
import pandas as pd
|
| 53 |
-
from tqdm import tqdm
|
| 54 |
-
|
| 55 |
-
# Import LeRobot's official statistics computation tools
|
| 56 |
-
try:
|
| 57 |
-
from lerobot.datasets.compute_stats import DEFAULT_QUANTILES, get_feature_stats
|
| 58 |
-
LEROBOT_STATS_AVAILABLE = True
|
| 59 |
-
except ImportError:
|
| 60 |
-
print("Warning: LeRobot stats module not available, will compute basic stats only")
|
| 61 |
-
LEROBOT_STATS_AVAILABLE = False
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def detect_cameras(episode_dir: Path) -> list[str]:
|
| 65 |
-
"""Detect all cameras from an episode directory.
|
| 66 |
-
|
| 67 |
-
Prioritizes metadata.json if it contains a 'cameras' field,
|
| 68 |
-
otherwise scans for cam_* subdirectories.
|
| 69 |
-
|
| 70 |
-
Returns:
|
| 71 |
-
Sorted list of camera names (e.g., ['cam_head', 'cam_wrist'])
|
| 72 |
-
"""
|
| 73 |
-
metadata_path = episode_dir / "metadata.json"
|
| 74 |
-
|
| 75 |
-
# Try to read from metadata first
|
| 76 |
-
if metadata_path.exists():
|
| 77 |
-
with open(metadata_path, "r") as f:
|
| 78 |
-
metadata = json.load(f)
|
| 79 |
-
if "cameras" in metadata:
|
| 80 |
-
cameras = [f"cam_{cam}" if not cam.startswith("cam_") else cam
|
| 81 |
-
for cam in metadata["cameras"]]
|
| 82 |
-
return sorted(cameras)
|
| 83 |
-
|
| 84 |
-
# Fallback: scan directories
|
| 85 |
-
cameras = []
|
| 86 |
-
for subdir in episode_dir.iterdir():
|
| 87 |
-
if subdir.is_dir() and subdir.name.startswith("cam_"):
|
| 88 |
-
# Verify it contains images
|
| 89 |
-
if list(subdir.glob("*.jpg")) or list(subdir.glob("*.png")):
|
| 90 |
-
cameras.append(subdir.name)
|
| 91 |
-
|
| 92 |
-
return sorted(cameras)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def validate_cameras_consistency(episode_dirs: list[Path]) -> list[str]:
|
| 96 |
-
"""Validate that all episodes have the same cameras.
|
| 97 |
-
|
| 98 |
-
Args:
|
| 99 |
-
episode_dirs: List of episode directories
|
| 100 |
-
|
| 101 |
-
Returns:
|
| 102 |
-
List of camera names (sorted)
|
| 103 |
-
|
| 104 |
-
Raises:
|
| 105 |
-
ValueError: If cameras are inconsistent across episodes
|
| 106 |
-
"""
|
| 107 |
-
if not episode_dirs:
|
| 108 |
-
raise ValueError("No episode directories provided")
|
| 109 |
-
|
| 110 |
-
# Detect cameras from first episode
|
| 111 |
-
reference_cameras = detect_cameras(episode_dirs[0])
|
| 112 |
-
if not reference_cameras:
|
| 113 |
-
raise ValueError(f"No cameras found in {episode_dirs[0]}")
|
| 114 |
-
|
| 115 |
-
print(f"Detected cameras: {reference_cameras}")
|
| 116 |
-
|
| 117 |
-
# Validate all other episodes have the same cameras
|
| 118 |
-
for episode_dir in episode_dirs[1:]:
|
| 119 |
-
cameras = detect_cameras(episode_dir)
|
| 120 |
-
if cameras != reference_cameras:
|
| 121 |
-
raise ValueError(
|
| 122 |
-
f"Camera mismatch in {episode_dir.name}:\n"
|
| 123 |
-
f" Expected: {reference_cameras}\n"
|
| 124 |
-
f" Found: {cameras}\n"
|
| 125 |
-
f"All episodes must have the same cameras."
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
return reference_cameras
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def get_episode_dirs(input_dir: Path) -> list[Path]:
|
| 132 |
-
"""Get all episode directories sorted by episode number."""
|
| 133 |
-
episode_dirs = []
|
| 134 |
-
for d in input_dir.iterdir():
|
| 135 |
-
if d.is_dir() and d.name.startswith("episode_"):
|
| 136 |
-
episode_dirs.append(d)
|
| 137 |
-
episode_dirs.sort(key=lambda x: int(x.name.split("_")[1]))
|
| 138 |
-
return episode_dirs
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
def load_episode_data(episode_dir: Path, cameras: list[str]) -> tuple[dict, pd.DataFrame, int]:
|
| 142 |
-
"""Load metadata and robot data for an episode.
|
| 143 |
-
|
| 144 |
-
Args:
|
| 145 |
-
episode_dir: Path to episode directory
|
| 146 |
-
cameras: List of camera names to load
|
| 147 |
-
|
| 148 |
-
Returns:
|
| 149 |
-
Tuple of (metadata, robot_data, num_frames)
|
| 150 |
-
"""
|
| 151 |
-
metadata_path = episode_dir / "metadata.json"
|
| 152 |
-
robot_data_path = episode_dir / "robot_data.csv"
|
| 153 |
-
|
| 154 |
-
with open(metadata_path, "r") as f:
|
| 155 |
-
metadata = json.load(f)
|
| 156 |
-
|
| 157 |
-
robot_data = pd.read_csv(robot_data_path)
|
| 158 |
-
|
| 159 |
-
# Count images for each camera
|
| 160 |
-
image_counts = []
|
| 161 |
-
for cam in cameras:
|
| 162 |
-
cam_dir = episode_dir / cam
|
| 163 |
-
num_images = len(list(cam_dir.glob("*.jpg"))) + len(list(cam_dir.glob("*.png")))
|
| 164 |
-
image_counts.append(num_images)
|
| 165 |
-
|
| 166 |
-
# num_frames is minimum of robot_data and all camera frame counts
|
| 167 |
-
num_frames = min(len(robot_data), *image_counts)
|
| 168 |
-
|
| 169 |
-
return metadata, robot_data, num_frames
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
def compute_stats(all_states: np.ndarray, all_actions: np.ndarray, cameras: list[str]) -> dict:
|
| 173 |
-
"""Compute dataset statistics for normalization with quantiles.
|
| 174 |
-
|
| 175 |
-
This function computes comprehensive statistics including:
|
| 176 |
-
- Basic stats: min, max, mean, std
|
| 177 |
-
- Quantiles: q01, q10, q50, q90, q99 (required for VLA models like pi05, smolvla)
|
| 178 |
-
|
| 179 |
-
For images, we use placeholder stats. LeRobot's factory.py will override
|
| 180 |
-
these with ImageNet stats when use_imagenet_stats=True (the default).
|
| 181 |
-
|
| 182 |
-
Args:
|
| 183 |
-
all_states: All state observations (N, state_dim)
|
| 184 |
-
all_actions: All actions (N, action_dim)
|
| 185 |
-
cameras: List of camera names (e.g., ['cam_head', 'cam_wrist'])
|
| 186 |
-
|
| 187 |
-
Returns:
|
| 188 |
-
Dictionary with statistics for each feature, including quantiles
|
| 189 |
-
"""
|
| 190 |
-
print("Computing statistics (including quantiles for VLA models)...")
|
| 191 |
-
|
| 192 |
-
stats = {}
|
| 193 |
-
|
| 194 |
-
# Compute state statistics with quantiles
|
| 195 |
-
if LEROBOT_STATS_AVAILABLE:
|
| 196 |
-
state_stats = get_feature_stats(
|
| 197 |
-
all_states,
|
| 198 |
-
axis=0, # Compute per-feature statistics across all samples
|
| 199 |
-
keepdims=False,
|
| 200 |
-
quantile_list=DEFAULT_QUANTILES # [0.01, 0.10, 0.50, 0.90, 0.99]
|
| 201 |
-
)
|
| 202 |
-
# Convert numpy arrays to lists for JSON serialization
|
| 203 |
-
stats["observation.state"] = {k: v.tolist() for k, v in state_stats.items()}
|
| 204 |
-
|
| 205 |
-
# Compute action statistics with quantiles
|
| 206 |
-
action_stats = get_feature_stats(
|
| 207 |
-
all_actions,
|
| 208 |
-
axis=0,
|
| 209 |
-
keepdims=False,
|
| 210 |
-
quantile_list=DEFAULT_QUANTILES
|
| 211 |
-
)
|
| 212 |
-
stats["action"] = {k: v.tolist() for k, v in action_stats.items()}
|
| 213 |
-
else:
|
| 214 |
-
# Fallback to basic stats only (not recommended for VLA models)
|
| 215 |
-
print("Warning: Computing basic stats only. VLA models may fail without quantiles!")
|
| 216 |
-
stats = {
|
| 217 |
-
"observation.state": {
|
| 218 |
-
"min": all_states.min(axis=0).tolist(),
|
| 219 |
-
"max": all_states.max(axis=0).tolist(),
|
| 220 |
-
"mean": all_states.mean(axis=0).tolist(),
|
| 221 |
-
"std": all_states.std(axis=0).tolist(),
|
| 222 |
-
},
|
| 223 |
-
"action": {
|
| 224 |
-
"min": all_actions.min(axis=0).tolist(),
|
| 225 |
-
"max": all_actions.max(axis=0).tolist(),
|
| 226 |
-
"mean": all_actions.mean(axis=0).tolist(),
|
| 227 |
-
"std": all_actions.std(axis=0).tolist(),
|
| 228 |
-
},
|
| 229 |
-
}
|
| 230 |
-
|
| 231 |
-
# Add image stats for each camera (ImageNet stats format: (c, 1, 1))
|
| 232 |
-
# These are placeholders - LeRobot will use ImageNet stats by default
|
| 233 |
-
for cam in cameras:
|
| 234 |
-
cam_key = f"observation.images.{cam}"
|
| 235 |
-
stats[cam_key] = {
|
| 236 |
-
"mean": [[[0.485]], [[0.456]], [[0.406]]], # ImageNet mean (c, 1, 1)
|
| 237 |
-
"std": [[[0.229]], [[0.224]], [[0.225]]], # ImageNet std (c, 1, 1)
|
| 238 |
-
"min": [[[0.0]], [[0.0]], [[0.0]]],
|
| 239 |
-
"max": [[[1.0]], [[1.0]], [[1.0]]],
|
| 240 |
-
}
|
| 241 |
-
|
| 242 |
-
# Print summary of computed statistics
|
| 243 |
-
if LEROBOT_STATS_AVAILABLE:
|
| 244 |
-
print(f"✓ Computed statistics with {len(DEFAULT_QUANTILES)} quantiles")
|
| 245 |
-
print(f" - observation.state: {list(stats['observation.state'].keys())}")
|
| 246 |
-
print(f" - action: {list(stats['action'].keys())}")
|
| 247 |
-
else:
|
| 248 |
-
print("⚠ Computed basic statistics only (no quantiles)")
|
| 249 |
-
|
| 250 |
-
return stats
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
def convert_dataset(
|
| 254 |
-
input_dir: Path,
|
| 255 |
-
output_dir: Path,
|
| 256 |
-
fps: int = 30,
|
| 257 |
-
task_description: str = "pick apple",
|
| 258 |
-
robot_type: str = "so100",
|
| 259 |
-
state_mode: str = "current_action",
|
| 260 |
-
action_mode: str = "next_action",
|
| 261 |
-
drop_last_frame: bool = True,
|
| 262 |
-
) -> None:
|
| 263 |
-
"""Convert raw data to LeRobot v3.0 format with dynamic camera support.
|
| 264 |
-
|
| 265 |
-
Automatically detects cameras from episode data and validates consistency.
|
| 266 |
-
"""
|
| 267 |
-
|
| 268 |
-
print(f"Converting data from {input_dir} to {output_dir}")
|
| 269 |
-
|
| 270 |
-
if output_dir.exists():
|
| 271 |
-
print(f"Removing existing output directory: {output_dir}")
|
| 272 |
-
shutil.rmtree(output_dir)
|
| 273 |
-
|
| 274 |
-
# Get episode directories
|
| 275 |
-
episode_dirs = get_episode_dirs(input_dir)
|
| 276 |
-
print(f"Found {len(episode_dirs)} episodes")
|
| 277 |
-
|
| 278 |
-
# Detect and validate cameras across all episodes
|
| 279 |
-
cameras = validate_cameras_consistency(episode_dirs)
|
| 280 |
-
print(f"Using {len(cameras)} cameras: {cameras}")
|
| 281 |
-
|
| 282 |
-
# Create directory structure
|
| 283 |
-
data_dir = output_dir / "data" / "chunk-000"
|
| 284 |
-
videos_dir = output_dir / "videos" / "chunk-000"
|
| 285 |
-
meta_dir = output_dir / "meta"
|
| 286 |
-
episodes_meta_dir = meta_dir / "episodes" / "chunk-000"
|
| 287 |
-
|
| 288 |
-
for d in [data_dir, meta_dir, episodes_meta_dir]:
|
| 289 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 290 |
-
|
| 291 |
-
# Create video directories for each camera
|
| 292 |
-
cam_dirs = {}
|
| 293 |
-
video_paths = {}
|
| 294 |
-
for cam in cameras:
|
| 295 |
-
cam_video_dir = videos_dir / f"observation.images.{cam}"
|
| 296 |
-
cam_video_dir.mkdir(parents=True, exist_ok=True)
|
| 297 |
-
cam_dirs[cam] = cam_video_dir
|
| 298 |
-
video_paths[cam] = cam_video_dir / "file-000.mp4"
|
| 299 |
-
|
| 300 |
-
# Pass 1: Collect episode data
|
| 301 |
-
print("\nPass 1: Collecting episode data...")
|
| 302 |
-
episode_data_list = []
|
| 303 |
-
total_video_frames = 0
|
| 304 |
-
|
| 305 |
-
for ep_idx, episode_dir in enumerate(tqdm(episode_dirs, desc="Loading")):
|
| 306 |
-
metadata, robot_data, num_frames = load_episode_data(episode_dir, cameras)
|
| 307 |
-
if num_frames == 0:
|
| 308 |
-
print(f"Warning: Skipping {episode_dir.name} - no frames")
|
| 309 |
-
continue
|
| 310 |
-
|
| 311 |
-
# We optionally drop the last frame to enable (state=u_t, action=u_{t+1}) alignment.
|
| 312 |
-
# This requires at least 2 frames per episode.
|
| 313 |
-
effective_frames = num_frames - 1 if drop_last_frame else num_frames
|
| 314 |
-
if effective_frames <= 0:
|
| 315 |
-
print(
|
| 316 |
-
f"Warning: Skipping {episode_dir.name} - not enough frames for drop_last_frame={drop_last_frame} "
|
| 317 |
-
f"(num_frames={num_frames})"
|
| 318 |
-
)
|
| 319 |
-
continue
|
| 320 |
-
|
| 321 |
-
# Prefer per-episode metadata task if available; fall back to CLI task_description.
|
| 322 |
-
ep_task = metadata.get("task") if isinstance(metadata, dict) else None
|
| 323 |
-
if not isinstance(ep_task, str) or not ep_task.strip():
|
| 324 |
-
ep_task = task_description
|
| 325 |
-
# Canonicalize task text for dataset storage (closer to LeRobot standard: raw text).
|
| 326 |
-
ep_task = ep_task.replace("_", " ").strip()
|
| 327 |
-
|
| 328 |
-
episode_data_list.append({
|
| 329 |
-
"ep_idx": len(episode_data_list), # New sequential index
|
| 330 |
-
"episode_dir": episode_dir,
|
| 331 |
-
"metadata": metadata,
|
| 332 |
-
"task": ep_task,
|
| 333 |
-
"robot_data": robot_data,
|
| 334 |
-
"num_frames": num_frames,
|
| 335 |
-
"effective_frames": effective_frames,
|
| 336 |
-
"video_from_frame": total_video_frames,
|
| 337 |
-
})
|
| 338 |
-
total_video_frames += effective_frames
|
| 339 |
-
|
| 340 |
-
if len(episode_data_list) == 0:
|
| 341 |
-
raise ValueError(f"No valid episodes found in {input_dir} (all have 0 frames?)")
|
| 342 |
-
|
| 343 |
-
# Get image dimensions from first camera's first frame
|
| 344 |
-
first_ep = episode_data_list[0]
|
| 345 |
-
# Validate that all cameras share the same resolution (required by a single mp4 per camera)
|
| 346 |
-
height = width = None
|
| 347 |
-
for cam in cameras:
|
| 348 |
-
first_img_path = first_ep["episode_dir"] / cam / "0.jpg"
|
| 349 |
-
if not first_img_path.exists():
|
| 350 |
-
first_img_path = first_ep["episode_dir"] / cam / "0.png"
|
| 351 |
-
first_img = cv2.imread(str(first_img_path))
|
| 352 |
-
if first_img is None:
|
| 353 |
-
raise FileNotFoundError(f"Missing first frame for camera '{cam}' at {first_img_path}")
|
| 354 |
-
h, w = first_img.shape[:2]
|
| 355 |
-
if height is None:
|
| 356 |
-
height, width = h, w
|
| 357 |
-
elif (h, w) != (height, width):
|
| 358 |
-
raise ValueError(
|
| 359 |
-
f"Camera resolution mismatch. Expected {(height, width)} but '{cam}' has {(h, w)}. "
|
| 360 |
-
"Please resize/crop during conversion or ensure all cameras match."
|
| 361 |
-
)
|
| 362 |
-
image_shape = (height, width, 3)
|
| 363 |
-
print(f"Image shape: {image_shape}")
|
| 364 |
-
|
| 365 |
-
# Build task index mapping (supports multi-task datasets).
|
| 366 |
-
unique_tasks = []
|
| 367 |
-
seen_tasks = set()
|
| 368 |
-
for ep_data in episode_data_list:
|
| 369 |
-
t = ep_data.get("task", task_description)
|
| 370 |
-
if t not in seen_tasks:
|
| 371 |
-
seen_tasks.add(t)
|
| 372 |
-
unique_tasks.append(t)
|
| 373 |
-
task_to_index = {t: i for i, t in enumerate(unique_tasks)}
|
| 374 |
-
|
| 375 |
-
# NOTE: We intentionally do NOT pre-tokenize language here.
|
| 376 |
-
# Store raw task text in parquet under `task`, and let training-time
|
| 377 |
-
# tokenizer/collator generate tokens + attention masks dynamically.
|
| 378 |
-
|
| 379 |
-
# Pass 2: Create videos and collect data
|
| 380 |
-
print("\nPass 2: Creating videos and processing frames...")
|
| 381 |
-
|
| 382 |
-
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 383 |
-
writers = {}
|
| 384 |
-
for cam in cameras:
|
| 385 |
-
writers[cam] = cv2.VideoWriter(str(video_paths[cam]), fourcc, fps, (width, height))
|
| 386 |
-
|
| 387 |
-
all_data_records = []
|
| 388 |
-
episode_records = []
|
| 389 |
-
all_states = []
|
| 390 |
-
all_actions = []
|
| 391 |
-
global_frame_index = 0
|
| 392 |
-
|
| 393 |
-
for ep_data in tqdm(episode_data_list, desc="Processing"):
|
| 394 |
-
ep_idx = ep_data["ep_idx"]
|
| 395 |
-
episode_dir = ep_data["episode_dir"]
|
| 396 |
-
robot_data = ep_data["robot_data"]
|
| 397 |
-
num_frames = ep_data["num_frames"]
|
| 398 |
-
effective_frames = ep_data["effective_frames"]
|
| 399 |
-
video_from_frame = ep_data["video_from_frame"]
|
| 400 |
-
ep_task = ep_data.get("task", task_description)
|
| 401 |
-
ep_task_index = task_to_index.get(ep_task, 0)
|
| 402 |
-
|
| 403 |
-
# Write video frames for all cameras
|
| 404 |
-
for frame_idx in range(effective_frames):
|
| 405 |
-
for cam in cameras:
|
| 406 |
-
# Support both jpg and png; enforce 1 frame written per index to keep timestamps aligned.
|
| 407 |
-
img_path = episode_dir / cam / f"{frame_idx}.jpg"
|
| 408 |
-
if not img_path.exists():
|
| 409 |
-
img_path = episode_dir / cam / f"{frame_idx}.png"
|
| 410 |
-
img = cv2.imread(str(img_path))
|
| 411 |
-
if img is None:
|
| 412 |
-
raise FileNotFoundError(
|
| 413 |
-
f"Missing/corrupted image for {episode_dir.name} cam={cam} frame={frame_idx}: {img_path}"
|
| 414 |
-
)
|
| 415 |
-
writers[cam].write(img)
|
| 416 |
-
|
| 417 |
-
# Extract raw targets u_t.
|
| 418 |
-
state_columns = ["j0", "j1", "j2", "j3", "j4", "j5", "gripper"]
|
| 419 |
-
episode_u = robot_data[state_columns].values[:num_frames].astype(np.float32)
|
| 420 |
-
episode_u[:, -1] = episode_u[:, -1] / 1000.0 # Normalize gripper
|
| 421 |
-
|
| 422 |
-
# Align sequences for training.
|
| 423 |
-
# We always build per-frame records of length `effective_frames`.
|
| 424 |
-
if drop_last_frame:
|
| 425 |
-
# Default recommended alignment when images and proprio are synchronous at time t:
|
| 426 |
-
# observation.state[t] = u_t
|
| 427 |
-
# action[t] = u_{t+1}
|
| 428 |
-
# by dropping the last frame.
|
| 429 |
-
base_u = episode_u[:-1] # u_0 .. u_{T-2}
|
| 430 |
-
next_u = episode_u[1:] # u_1 .. u_{T-1}
|
| 431 |
-
else:
|
| 432 |
-
base_u = episode_u
|
| 433 |
-
next_u = episode_u
|
| 434 |
-
|
| 435 |
-
if state_mode == "current_action":
|
| 436 |
-
episode_states = base_u.copy()
|
| 437 |
-
elif state_mode == "prev_action":
|
| 438 |
-
# observation.state[t] = u_{t-1}, with boundary state[0] = u_0.
|
| 439 |
-
if len(base_u) == 1:
|
| 440 |
-
episode_states = base_u.copy()
|
| 441 |
-
else:
|
| 442 |
-
episode_states = np.vstack([base_u[0:1], base_u[:-1]])
|
| 443 |
-
else:
|
| 444 |
-
raise ValueError(f"Unsupported state_mode: {state_mode}")
|
| 445 |
-
|
| 446 |
-
if action_mode == "current_action":
|
| 447 |
-
episode_actions = base_u.copy()
|
| 448 |
-
elif action_mode == "next_action":
|
| 449 |
-
episode_actions = next_u.copy()
|
| 450 |
-
else:
|
| 451 |
-
raise ValueError(f"Unsupported action_mode: {action_mode}")
|
| 452 |
-
|
| 453 |
-
# IMPORTANT: timestamp should be relative to episode start, in seconds
|
| 454 |
-
# LeRobot uses this for video frame lookup: from_timestamp + timestamp
|
| 455 |
-
# So timestamp should be 0, 1/fps, 2/fps, ... for frame 0, 1, 2, ...
|
| 456 |
-
|
| 457 |
-
dataset_from_index = global_frame_index
|
| 458 |
-
|
| 459 |
-
# Create frame records (NO video columns - loaded separately)
|
| 460 |
-
for frame_idx in range(effective_frames):
|
| 461 |
-
# timestamp in seconds from episode start
|
| 462 |
-
frame_timestamp = frame_idx / fps
|
| 463 |
-
record = {
|
| 464 |
-
"observation.state": episode_states[frame_idx].tolist(),
|
| 465 |
-
"action": episode_actions[frame_idx].tolist(),
|
| 466 |
-
"timestamp": frame_timestamp, # seconds from episode start
|
| 467 |
-
"episode_index": ep_idx,
|
| 468 |
-
"frame_index": frame_idx,
|
| 469 |
-
"index": global_frame_index,
|
| 470 |
-
"task": ep_task,
|
| 471 |
-
"task_index": ep_task_index,
|
| 472 |
-
"next.done": frame_idx == effective_frames - 1,
|
| 473 |
-
}
|
| 474 |
-
|
| 475 |
-
all_data_records.append(record)
|
| 476 |
-
all_states.append(episode_states[frame_idx])
|
| 477 |
-
all_actions.append(episode_actions[frame_idx])
|
| 478 |
-
global_frame_index += 1
|
| 479 |
-
|
| 480 |
-
# LeRobot v3 expects dataset_to_index to be EXCLUSIVE (right-open interval):
|
| 481 |
-
# frames for this episode are in [dataset_from_index, dataset_to_index)
|
| 482 |
-
dataset_to_index = global_frame_index
|
| 483 |
-
|
| 484 |
-
# Episode metadata with video references
|
| 485 |
-
episode_record = {
|
| 486 |
-
"episode_index": ep_idx,
|
| 487 |
-
"tasks": [ep_task],
|
| 488 |
-
"length": effective_frames,
|
| 489 |
-
"task_index": ep_task_index,
|
| 490 |
-
# Data file location
|
| 491 |
-
"data/chunk_index": 0,
|
| 492 |
-
"data/file_index": 0,
|
| 493 |
-
"dataset_from_index": dataset_from_index,
|
| 494 |
-
"dataset_to_index": dataset_to_index,
|
| 495 |
-
}
|
| 496 |
-
|
| 497 |
-
# Add video metadata for each camera dynamically
|
| 498 |
-
for cam in cameras:
|
| 499 |
-
video_key = f"observation.images.{cam}"
|
| 500 |
-
episode_record.update({
|
| 501 |
-
f"videos/{video_key}/chunk_index": 0,
|
| 502 |
-
f"videos/{video_key}/file_index": 0,
|
| 503 |
-
f"videos/{video_key}/from_timestamp": video_from_frame / fps,
|
| 504 |
-
# LeRobot expects to_timestamp to be the episode END time (exclusive), not last-frame time.
|
| 505 |
-
f"videos/{video_key}/to_timestamp": (video_from_frame + effective_frames) / fps,
|
| 506 |
-
})
|
| 507 |
-
|
| 508 |
-
episode_records.append(episode_record)
|
| 509 |
-
|
| 510 |
-
# Close video writers
|
| 511 |
-
for writer in writers.values():
|
| 512 |
-
writer.release()
|
| 513 |
-
|
| 514 |
-
print(f"Total frames: {global_frame_index}")
|
| 515 |
-
print(f"Total episodes: {len(episode_records)}")
|
| 516 |
-
|
| 517 |
-
# Compute statistics
|
| 518 |
-
all_states = np.array(all_states)
|
| 519 |
-
all_actions = np.array(all_actions)
|
| 520 |
-
stats = compute_stats(all_states, all_actions, cameras)
|
| 521 |
-
|
| 522 |
-
# Save data parquet
|
| 523 |
-
print("Saving data parquet...")
|
| 524 |
-
df = pd.DataFrame(all_data_records)
|
| 525 |
-
df.to_parquet(data_dir / "file-000.parquet", index=False)
|
| 526 |
-
|
| 527 |
-
# Save episodes parquet
|
| 528 |
-
print("Saving episodes metadata...")
|
| 529 |
-
episodes_df = pd.DataFrame(episode_records)
|
| 530 |
-
episodes_df.to_parquet(episodes_meta_dir / "file-000.parquet", index=False)
|
| 531 |
-
|
| 532 |
-
# Save tasks.parquet
|
| 533 |
-
# LeRobot v3 convention: task strings are stored in the dataframe index; task_index is a column.
|
| 534 |
-
tasks_items = sorted(task_to_index.items(), key=lambda kv: kv[1])
|
| 535 |
-
tasks_df = pd.DataFrame({"task_index": [idx for _, idx in tasks_items]}, index=[t for t, _ in tasks_items])
|
| 536 |
-
tasks_df.to_parquet(meta_dir / "tasks.parquet", index=True)
|
| 537 |
-
|
| 538 |
-
# Save stats.json
|
| 539 |
-
with open(meta_dir / "stats.json", "w") as f:
|
| 540 |
-
json.dump(stats, f, indent=2)
|
| 541 |
-
|
| 542 |
-
# Video info
|
| 543 |
-
video_info = {
|
| 544 |
-
"video.fps": fps,
|
| 545 |
-
"video.codec": "mp4v",
|
| 546 |
-
"video.pix_fmt": "yuv420p",
|
| 547 |
-
"video.is_depth_map": False,
|
| 548 |
-
"has_audio": False,
|
| 549 |
-
}
|
| 550 |
-
|
| 551 |
-
# Save info.json
|
| 552 |
-
features = {
|
| 553 |
-
"observation.state": {
|
| 554 |
-
"dtype": "float32",
|
| 555 |
-
"shape": [7],
|
| 556 |
-
"names": ["j0", "j1", "j2", "j3", "j4", "j5", "gripper"],
|
| 557 |
-
},
|
| 558 |
-
"action": {
|
| 559 |
-
"dtype": "float32",
|
| 560 |
-
"shape": [7],
|
| 561 |
-
"names": ["j0", "j1", "j2", "j3", "j4", "j5", "gripper"],
|
| 562 |
-
},
|
| 563 |
-
}
|
| 564 |
-
|
| 565 |
-
# Add camera features dynamically
|
| 566 |
-
for cam in cameras:
|
| 567 |
-
video_key = f"observation.images.{cam}"
|
| 568 |
-
features[video_key] = {
|
| 569 |
-
"dtype": "video",
|
| 570 |
-
"shape": list(image_shape),
|
| 571 |
-
"names": ["height", "width", "channel"],
|
| 572 |
-
"info": video_info,
|
| 573 |
-
}
|
| 574 |
-
|
| 575 |
-
# Add metadata features
|
| 576 |
-
features.update({
|
| 577 |
-
"timestamp": {"dtype": "float64", "shape": [1], "names": None},
|
| 578 |
-
"episode_index": {"dtype": "int64", "shape": [1], "names": None},
|
| 579 |
-
"frame_index": {"dtype": "int64", "shape": [1], "names": None},
|
| 580 |
-
"index": {"dtype": "int64", "shape": [1], "names": None},
|
| 581 |
-
"task": {"dtype": "string", "shape": [1], "names": None},
|
| 582 |
-
"task_index": {"dtype": "int64", "shape": [1], "names": None},
|
| 583 |
-
"next.done": {"dtype": "bool", "shape": [1], "names": None},
|
| 584 |
-
})
|
| 585 |
-
|
| 586 |
-
info = {
|
| 587 |
-
"codebase_version": "v3.0",
|
| 588 |
-
"robot_type": robot_type,
|
| 589 |
-
"fps": fps,
|
| 590 |
-
"total_episodes": len(episode_records),
|
| 591 |
-
"total_frames": global_frame_index,
|
| 592 |
-
"total_tasks": len(unique_tasks),
|
| 593 |
-
"total_videos": len(cameras),
|
| 594 |
-
"total_chunks": 1,
|
| 595 |
-
"chunks_size": global_frame_index,
|
| 596 |
-
"data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet",
|
| 597 |
-
"video_path": "videos/chunk-{chunk_index:03d}/{video_key}/file-{file_index:03d}.mp4",
|
| 598 |
-
"splits": {"train": f"0:{len(episode_records)}"},
|
| 599 |
-
"features": features,
|
| 600 |
-
}
|
| 601 |
-
|
| 602 |
-
with open(meta_dir / "info.json", "w") as f:
|
| 603 |
-
json.dump(info, f, indent=2)
|
| 604 |
-
|
| 605 |
-
print(f"\nDataset conversion complete!")
|
| 606 |
-
print(f"Output directory: {output_dir}")
|
| 607 |
-
print(f"Cameras: {cameras}")
|
| 608 |
-
print(f"Total episodes: {len(episode_records)}")
|
| 609 |
-
print(f"Total frames: {global_frame_index}")
|
| 610 |
-
print(f"Total videos: {len(cameras)}")
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
def main():
|
| 614 |
-
parser = argparse.ArgumentParser(description="Convert pick_apple data to LeRobot format")
|
| 615 |
-
parser.add_argument("--input", type=str, default="pick_apple")
|
| 616 |
-
parser.add_argument("--output", type=str, default="data/pick_apple_lerobot")
|
| 617 |
-
parser.add_argument("--fps", type=int, default=30)
|
| 618 |
-
parser.add_argument("--task", type=str, default="pick apple")
|
| 619 |
-
parser.add_argument("--robot-type", type=str, default="so100")
|
| 620 |
-
parser.add_argument(
|
| 621 |
-
"--state-mode",
|
| 622 |
-
type=str,
|
| 623 |
-
default="current_action",
|
| 624 |
-
choices=["prev_action", "current_action"],
|
| 625 |
-
help="How to construct observation.state from target commands u_t.",
|
| 626 |
-
)
|
| 627 |
-
|
| 628 |
-
parser.add_argument(
|
| 629 |
-
"--action-mode",
|
| 630 |
-
type=str,
|
| 631 |
-
default="next_action",
|
| 632 |
-
choices=["current_action", "next_action"],
|
| 633 |
-
help=(
|
| 634 |
-
"How to construct action targets from target commands u_t. "
|
| 635 |
-
"next_action uses u_{t+1} (recommended when dropping last frame)."
|
| 636 |
-
),
|
| 637 |
-
)
|
| 638 |
-
|
| 639 |
-
parser.add_argument(
|
| 640 |
-
"--keep-last-frame",
|
| 641 |
-
action="store_true",
|
| 642 |
-
help="Keep the last frame (disables dropping). When enabled, action_mode=next_action becomes current_action.",
|
| 643 |
-
)
|
| 644 |
-
|
| 645 |
-
args = parser.parse_args()
|
| 646 |
-
|
| 647 |
-
input_dir = Path(args.input)
|
| 648 |
-
output_dir = Path(args.output)
|
| 649 |
-
|
| 650 |
-
if not input_dir.exists():
|
| 651 |
-
raise ValueError(f"Input directory does not exist: {input_dir}")
|
| 652 |
-
|
| 653 |
-
convert_dataset(
|
| 654 |
-
input_dir,
|
| 655 |
-
output_dir,
|
| 656 |
-
fps=args.fps,
|
| 657 |
-
task_description=args.task,
|
| 658 |
-
robot_type=args.robot_type,
|
| 659 |
-
state_mode=args.state_mode,
|
| 660 |
-
action_mode=args.action_mode,
|
| 661 |
-
drop_last_frame=not args.keep_last_frame,
|
| 662 |
-
)
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
if __name__ == "__main__":
|
| 666 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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