Upload folder using huggingface_hub
Browse files- convert_to_hdf5.py +165 -0
- convert_to_lerobot.py +666 -0
- patch_lerobot_for_smolvla.py +298 -0
- test_camera_fps.py +85 -0
- test_camera_manager_fps.py +67 -0
- test_dual_cameras_fps.py +88 -0
convert_to_hdf5.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import h5py
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
|
| 10 |
+
def load_robot_data(csv_path):
|
| 11 |
+
"""
|
| 12 |
+
Returns: master_ts, robot_ts, qpos, gripper
|
| 13 |
+
"""
|
| 14 |
+
master_timestamps = []
|
| 15 |
+
robot_timestamps = []
|
| 16 |
+
qpos = []
|
| 17 |
+
gripper = []
|
| 18 |
+
|
| 19 |
+
with open(csv_path, 'r') as f:
|
| 20 |
+
reader = csv.reader(f)
|
| 21 |
+
try:
|
| 22 |
+
header = next(reader)
|
| 23 |
+
|
| 24 |
+
# Check format
|
| 25 |
+
# Format 1: master_timestamp, robot_timestamp, j0..j5, gripper
|
| 26 |
+
# Format 2: cam_timestamp, robot_timestamp, j0..j5, gripper (Previous version)
|
| 27 |
+
# Format 3: timestamp, j0..j5, gripper (Legacy)
|
| 28 |
+
|
| 29 |
+
if header[0] == 'master_timestamp' or header[0] == 'cam_timestamp':
|
| 30 |
+
# New formats
|
| 31 |
+
for row in reader:
|
| 32 |
+
master_timestamps.append(float(row[0]))
|
| 33 |
+
robot_timestamps.append(float(row[1]))
|
| 34 |
+
qpos.append([float(x) for x in row[2:8]])
|
| 35 |
+
gripper.append(float(row[8]))
|
| 36 |
+
else:
|
| 37 |
+
# Legacy format
|
| 38 |
+
for row in reader:
|
| 39 |
+
t = float(row[0])
|
| 40 |
+
master_timestamps.append(t)
|
| 41 |
+
robot_timestamps.append(t)
|
| 42 |
+
qpos.append([float(x) for x in row[1:7]])
|
| 43 |
+
gripper.append(float(row[7]))
|
| 44 |
+
|
| 45 |
+
except StopIteration:
|
| 46 |
+
return np.array([]), np.array([]), np.array([]), np.array([])
|
| 47 |
+
|
| 48 |
+
return np.array(master_timestamps), np.array(robot_timestamps), np.array(qpos), np.array(gripper)
|
| 49 |
+
|
| 50 |
+
def process_episode(episode_path, output_path):
|
| 51 |
+
print(f"Processing {episode_path}...")
|
| 52 |
+
|
| 53 |
+
csv_path = episode_path / "robot_data.csv"
|
| 54 |
+
|
| 55 |
+
if not csv_path.exists():
|
| 56 |
+
print(f"Skipping {episode_path}: Missing CSV")
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
# Load Robot Data
|
| 60 |
+
master_ts, robot_ts, qpos, gripper = load_robot_data(csv_path)
|
| 61 |
+
|
| 62 |
+
if len(master_ts) == 0:
|
| 63 |
+
print(f"Skipping {episode_path}: Empty CSV")
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
num_frames = len(master_ts)
|
| 67 |
+
|
| 68 |
+
# Find all camera directories
|
| 69 |
+
cam_dirs = sorted(list(episode_path.glob("cam_*")))
|
| 70 |
+
|
| 71 |
+
if not cam_dirs:
|
| 72 |
+
print(f"Skipping {episode_path}: No camera directories found")
|
| 73 |
+
return
|
| 74 |
+
|
| 75 |
+
# Prepare HDF5 file
|
| 76 |
+
with h5py.File(output_path, 'w') as root:
|
| 77 |
+
root.attrs['sim'] = False
|
| 78 |
+
|
| 79 |
+
obs = root.create_group('observations')
|
| 80 |
+
|
| 81 |
+
# Robot State
|
| 82 |
+
obs.create_dataset('qpos', data=qpos)
|
| 83 |
+
obs.create_dataset('qvel', data=np.zeros_like(qpos)) # Placeholder, see below
|
| 84 |
+
|
| 85 |
+
# Process Images
|
| 86 |
+
min_frames = num_frames
|
| 87 |
+
|
| 88 |
+
for cam_dir in cam_dirs:
|
| 89 |
+
cam_name = cam_dir.name # e.g. cam_head
|
| 90 |
+
image_files = sorted(list(cam_dir.glob("*.jpg")), key=lambda x: int(x.stem))
|
| 91 |
+
|
| 92 |
+
# Check count
|
| 93 |
+
if len(image_files) != num_frames:
|
| 94 |
+
print(f"Warning: {cam_name} frames ({len(image_files)}) != CSV rows ({num_frames}). Truncating.")
|
| 95 |
+
min_frames = min(min_frames, len(image_files))
|
| 96 |
+
|
| 97 |
+
# Load images
|
| 98 |
+
# Note: Loading all to memory might be heavy for many cameras/long episodes
|
| 99 |
+
# Consider chunking if needed. For now, simple load.
|
| 100 |
+
images = []
|
| 101 |
+
for img_path in image_files[:min_frames]:
|
| 102 |
+
img = cv2.imread(str(img_path))
|
| 103 |
+
images.append(img)
|
| 104 |
+
|
| 105 |
+
images = np.array(images)
|
| 106 |
+
obs.create_dataset(f'images/{cam_name}', data=images)
|
| 107 |
+
|
| 108 |
+
# Truncate robot data if images were shorter
|
| 109 |
+
if min_frames < num_frames:
|
| 110 |
+
qpos = qpos[:min_frames]
|
| 111 |
+
gripper = gripper[:min_frames]
|
| 112 |
+
robot_ts = robot_ts[:min_frames]
|
| 113 |
+
master_ts = master_ts[:min_frames]
|
| 114 |
+
|
| 115 |
+
# Re-save truncated qpos
|
| 116 |
+
del obs['qpos']
|
| 117 |
+
obs.create_dataset('qpos', data=qpos)
|
| 118 |
+
|
| 119 |
+
# Compute qvel
|
| 120 |
+
qvel = np.zeros_like(qpos)
|
| 121 |
+
if len(qpos) > 1:
|
| 122 |
+
dt = np.diff(robot_ts)
|
| 123 |
+
dt = np.where(dt == 0, 1e-3, dt)[:, None]
|
| 124 |
+
qvel[:-1] = (qpos[1:] - qpos[:-1]) / dt
|
| 125 |
+
qvel[-1] = qvel[-2]
|
| 126 |
+
|
| 127 |
+
del obs['qvel']
|
| 128 |
+
obs.create_dataset('qvel', data=qvel)
|
| 129 |
+
|
| 130 |
+
# Action
|
| 131 |
+
action = np.zeros_like(qpos)
|
| 132 |
+
action[:-1] = qpos[1:]
|
| 133 |
+
action[-1] = qpos[-1]
|
| 134 |
+
|
| 135 |
+
root.create_dataset('action', data=action)
|
| 136 |
+
|
| 137 |
+
# Store timestamps
|
| 138 |
+
# obs.create_dataset('timestamp', data=master_ts)
|
| 139 |
+
|
| 140 |
+
print(f"Saved to {output_path}")
|
| 141 |
+
|
| 142 |
+
def main():
|
| 143 |
+
parser = argparse.ArgumentParser(description="Convert raw data to HDF5 for ACT")
|
| 144 |
+
parser.add_argument('--task', required=True, help="Task name")
|
| 145 |
+
parser.add_argument('--out', default="dataset.hdf5", help="Output HDF5 filename (or dir)")
|
| 146 |
+
args = parser.parse_args()
|
| 147 |
+
|
| 148 |
+
data_root = Path("data")
|
| 149 |
+
task_dir = data_root / args.task
|
| 150 |
+
|
| 151 |
+
if not task_dir.exists():
|
| 152 |
+
print(f"Task {args.task} not found in {data_root}")
|
| 153 |
+
return
|
| 154 |
+
|
| 155 |
+
episodes = sorted(list(task_dir.glob("episode_*")))
|
| 156 |
+
|
| 157 |
+
output_dir = Path(args.out)
|
| 158 |
+
output_dir.mkdir(exist_ok=True, parents=True)
|
| 159 |
+
|
| 160 |
+
for ep_dir in episodes:
|
| 161 |
+
out_name = f"{ep_dir.name}.hdf5"
|
| 162 |
+
process_episode(ep_dir, output_dir / out_name)
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
main()
|
convert_to_lerobot.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
patch_lerobot_for_smolvla.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Patch an existing LeRobot v3 dataset to be usable for SmolVLA.
|
| 2 |
+
|
| 3 |
+
This script is intended for the common situation where a dataset was converted for ACT
|
| 4 |
+
but is missing SmolVLA-required language fields and/or uses an incompatible definition
|
| 5 |
+
for observation.state.
|
| 6 |
+
|
| 7 |
+
What it does:
|
| 8 |
+
- Creates a patched copy of the dataset (optionally symlinking videos to avoid duplication)
|
| 9 |
+
- Sets observation.state to the previous target (scheme-2): state[t] = action[t-1] within each episode
|
| 10 |
+
(state[0] is set to action[0] as a boundary condition)
|
| 11 |
+
- Adds SmolVLA language inputs:
|
| 12 |
+
- observation.language.tokens
|
| 13 |
+
- observation.language.attention_mask
|
| 14 |
+
computed from each episode's metadata.json "task" string using a Transformers tokenizer.
|
| 15 |
+
- Updates meta/info.json features and meta/stats.json.
|
| 16 |
+
- Updates meta/tasks.parquet (task strings live in the dataframe index) and meta/episodes parquet "tasks".
|
| 17 |
+
|
| 18 |
+
Usage example:
|
| 19 |
+
python backend/scripts/patch_lerobot_for_smolvla.py \
|
| 20 |
+
--dataset-dir backend/datasets/pick_up_objects \
|
| 21 |
+
--raw-dir backend/data/pick_up_objects \
|
| 22 |
+
--output-dir backend/datasets/pick_up_objects_smolvla \
|
| 23 |
+
--vlm-model-name HuggingFaceTB/SmolVLM2-500M-Video-Instruct \
|
| 24 |
+
--tokenizer-max-length 48
|
| 25 |
+
|
| 26 |
+
Notes:
|
| 27 |
+
- This does NOT re-encode videos.
|
| 28 |
+
- Requires "transformers" to be installed in the current environment.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import argparse
|
| 34 |
+
import json
|
| 35 |
+
import shutil
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
import numpy as np
|
| 39 |
+
import pandas as pd
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
from transformers import AutoTokenizer
|
| 43 |
+
|
| 44 |
+
_TRANSFORMERS_AVAILABLE = True
|
| 45 |
+
except Exception:
|
| 46 |
+
_TRANSFORMERS_AVAILABLE = False
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from lerobot.datasets.compute_stats import DEFAULT_QUANTILES, get_feature_stats
|
| 50 |
+
|
| 51 |
+
_LEROBOT_STATS_AVAILABLE = True
|
| 52 |
+
except Exception:
|
| 53 |
+
_LEROBOT_STATS_AVAILABLE = False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
STATE_KEY = "observation.state"
|
| 57 |
+
ACTION_KEY = "action"
|
| 58 |
+
LANG_TOKENS_KEY = "observation.language.tokens"
|
| 59 |
+
LANG_MASK_KEY = "observation.language.attention_mask"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _iter_episode_dirs(raw_dir: Path) -> list[Path]:
|
| 63 |
+
eps = [p for p in raw_dir.iterdir() if p.is_dir() and p.name.startswith("episode_")]
|
| 64 |
+
eps.sort(key=lambda p: int(p.name.split("_")[1]))
|
| 65 |
+
return eps
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _collect_tasks_from_raw(raw_dir: Path) -> list[str]:
|
| 69 |
+
tasks: list[str] = []
|
| 70 |
+
for ep_dir in _iter_episode_dirs(raw_dir):
|
| 71 |
+
meta_path = ep_dir / "metadata.json"
|
| 72 |
+
if not meta_path.exists():
|
| 73 |
+
continue
|
| 74 |
+
meta = json.loads(meta_path.read_text())
|
| 75 |
+
task = meta.get("task")
|
| 76 |
+
if isinstance(task, str) and task.strip():
|
| 77 |
+
tasks.append(task.strip())
|
| 78 |
+
# preserve order but unique
|
| 79 |
+
seen = set()
|
| 80 |
+
uniq: list[str] = []
|
| 81 |
+
for t in tasks:
|
| 82 |
+
if t not in seen:
|
| 83 |
+
seen.add(t)
|
| 84 |
+
uniq.append(t)
|
| 85 |
+
return uniq
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _normalize_task_text(task: str) -> str:
|
| 89 |
+
# Keep it minimal and stable: convert snake_case to words.
|
| 90 |
+
return task.replace("_", " ").strip()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _encode_tasks(tasks: list[str], vlm_model_name: str, tokenizer_max_length: int) -> dict[str, tuple[list[int], list[int]]]:
|
| 94 |
+
if not _TRANSFORMERS_AVAILABLE:
|
| 95 |
+
raise RuntimeError(
|
| 96 |
+
"transformers is required to generate language tokens. Install it with `pip install transformers`."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
tokenizer = AutoTokenizer.from_pretrained(vlm_model_name, use_fast=True)
|
| 100 |
+
encoded: dict[str, tuple[list[int], list[int]]] = {}
|
| 101 |
+
for task in tasks:
|
| 102 |
+
text = _normalize_task_text(task)
|
| 103 |
+
out = tokenizer(
|
| 104 |
+
text,
|
| 105 |
+
padding="max_length",
|
| 106 |
+
truncation=True,
|
| 107 |
+
max_length=tokenizer_max_length,
|
| 108 |
+
return_attention_mask=True,
|
| 109 |
+
return_tensors=None,
|
| 110 |
+
)
|
| 111 |
+
input_ids = list(map(int, out["input_ids"]))
|
| 112 |
+
attn = list(map(int, out["attention_mask"]))
|
| 113 |
+
if len(input_ids) != tokenizer_max_length or len(attn) != tokenizer_max_length:
|
| 114 |
+
raise ValueError("Tokenizer output length mismatch; expected fixed max_length")
|
| 115 |
+
encoded[task] = (input_ids, attn)
|
| 116 |
+
|
| 117 |
+
return encoded
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _compute_stats(states: np.ndarray, actions: np.ndarray, existing_stats: dict) -> dict:
|
| 121 |
+
# Recompute state/action stats; preserve image stats unchanged.
|
| 122 |
+
stats = dict(existing_stats) if isinstance(existing_stats, dict) else {}
|
| 123 |
+
|
| 124 |
+
if _LEROBOT_STATS_AVAILABLE:
|
| 125 |
+
state_stats = get_feature_stats(states, axis=0, keepdims=False, quantile_list=DEFAULT_QUANTILES)
|
| 126 |
+
action_stats = get_feature_stats(actions, axis=0, keepdims=False, quantile_list=DEFAULT_QUANTILES)
|
| 127 |
+
stats[STATE_KEY] = {k: v.tolist() for k, v in state_stats.items()}
|
| 128 |
+
stats[ACTION_KEY] = {k: v.tolist() for k, v in action_stats.items()}
|
| 129 |
+
else:
|
| 130 |
+
stats[STATE_KEY] = {
|
| 131 |
+
"min": states.min(axis=0).tolist(),
|
| 132 |
+
"max": states.max(axis=0).tolist(),
|
| 133 |
+
"mean": states.mean(axis=0).tolist(),
|
| 134 |
+
"std": states.std(axis=0).tolist(),
|
| 135 |
+
}
|
| 136 |
+
stats[ACTION_KEY] = {
|
| 137 |
+
"min": actions.min(axis=0).tolist(),
|
| 138 |
+
"max": actions.max(axis=0).tolist(),
|
| 139 |
+
"mean": actions.mean(axis=0).tolist(),
|
| 140 |
+
"std": actions.std(axis=0).tolist(),
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
return stats
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def patch_dataset(
|
| 147 |
+
dataset_dir: Path,
|
| 148 |
+
raw_dir: Path,
|
| 149 |
+
output_dir: Path,
|
| 150 |
+
vlm_model_name: str,
|
| 151 |
+
tokenizer_max_length: int,
|
| 152 |
+
symlink_videos: bool,
|
| 153 |
+
) -> None:
|
| 154 |
+
if not dataset_dir.exists():
|
| 155 |
+
raise FileNotFoundError(f"dataset_dir not found: {dataset_dir}")
|
| 156 |
+
if not raw_dir.exists():
|
| 157 |
+
raise FileNotFoundError(f"raw_dir not found: {raw_dir}")
|
| 158 |
+
|
| 159 |
+
tasks = _collect_tasks_from_raw(raw_dir)
|
| 160 |
+
if not tasks:
|
| 161 |
+
raise ValueError(f"No tasks found in raw metadata under {raw_dir}")
|
| 162 |
+
if len(tasks) != 1:
|
| 163 |
+
# The existing converter currently writes a single task_index=0 for all frames.
|
| 164 |
+
# If you truly have multiple tasks, you should re-convert with a corrected mapping.
|
| 165 |
+
raise ValueError(
|
| 166 |
+
f"Found {len(tasks)} unique tasks in raw data ({tasks}), but this dataset appears single-task. "
|
| 167 |
+
"Re-run conversion with multi-task support if needed."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
task = tasks[0]
|
| 171 |
+
encoded = _encode_tasks([task], vlm_model_name, tokenizer_max_length)
|
| 172 |
+
tok, mask = encoded[task]
|
| 173 |
+
|
| 174 |
+
if output_dir.exists():
|
| 175 |
+
shutil.rmtree(output_dir)
|
| 176 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 177 |
+
|
| 178 |
+
# Copy data/meta; reuse videos via symlink if requested.
|
| 179 |
+
shutil.copytree(dataset_dir / "data", output_dir / "data")
|
| 180 |
+
shutil.copytree(dataset_dir / "meta", output_dir / "meta")
|
| 181 |
+
|
| 182 |
+
src_videos = dataset_dir / "videos"
|
| 183 |
+
if src_videos.exists():
|
| 184 |
+
if symlink_videos:
|
| 185 |
+
(output_dir / "videos").symlink_to(src_videos, target_is_directory=True)
|
| 186 |
+
else:
|
| 187 |
+
shutil.copytree(src_videos, output_dir / "videos")
|
| 188 |
+
|
| 189 |
+
# Patch tasks.parquet (task string is the index).
|
| 190 |
+
tasks_df = pd.DataFrame({"task_index": [0]}, index=[task])
|
| 191 |
+
tasks_df.to_parquet(output_dir / "meta" / "tasks.parquet", index=True)
|
| 192 |
+
|
| 193 |
+
# Patch episodes parquet (update tasks list entry).
|
| 194 |
+
episodes_paths = sorted((output_dir / "meta" / "episodes").glob("chunk-*/*.parquet"))
|
| 195 |
+
if not episodes_paths:
|
| 196 |
+
raise FileNotFoundError("No episodes parquet found under meta/episodes")
|
| 197 |
+
for ep_path in episodes_paths:
|
| 198 |
+
edf = pd.read_parquet(ep_path)
|
| 199 |
+
if "tasks" in edf.columns:
|
| 200 |
+
edf["tasks"] = [[task] for _ in range(len(edf))]
|
| 201 |
+
if "task_index" in edf.columns:
|
| 202 |
+
edf["task_index"] = 0
|
| 203 |
+
edf.to_parquet(ep_path, index=False)
|
| 204 |
+
|
| 205 |
+
# Patch data parquet(s).
|
| 206 |
+
data_paths = sorted((output_dir / "data").glob("chunk-*/*.parquet"))
|
| 207 |
+
if not data_paths:
|
| 208 |
+
raise FileNotFoundError("No data parquet found under data/")
|
| 209 |
+
|
| 210 |
+
all_states = []
|
| 211 |
+
all_actions = []
|
| 212 |
+
|
| 213 |
+
for dp in data_paths:
|
| 214 |
+
df = pd.read_parquet(dp)
|
| 215 |
+
required = {STATE_KEY, ACTION_KEY, "episode_index", "frame_index", "task_index"}
|
| 216 |
+
missing = required - set(df.columns)
|
| 217 |
+
if missing:
|
| 218 |
+
raise ValueError(f"Missing required columns in {dp}: {sorted(missing)}")
|
| 219 |
+
|
| 220 |
+
df = df.sort_values(["episode_index", "frame_index"]).reset_index(drop=False)
|
| 221 |
+
# Shift state within each episode: state[t] = action[t-1]
|
| 222 |
+
action_arr = np.stack(df[ACTION_KEY].to_numpy())
|
| 223 |
+
ep_idx = df["episode_index"].to_numpy()
|
| 224 |
+
|
| 225 |
+
state_arr = np.empty_like(action_arr)
|
| 226 |
+
# process per episode
|
| 227 |
+
start = 0
|
| 228 |
+
while start < len(df):
|
| 229 |
+
curr_ep = ep_idx[start]
|
| 230 |
+
end = start
|
| 231 |
+
while end < len(df) and ep_idx[end] == curr_ep:
|
| 232 |
+
end += 1
|
| 233 |
+
a = action_arr[start:end]
|
| 234 |
+
s = np.vstack([a[0:1], a[:-1]])
|
| 235 |
+
state_arr[start:end] = s
|
| 236 |
+
start = end
|
| 237 |
+
|
| 238 |
+
# Add language columns (same for all rows; single-task)
|
| 239 |
+
df[STATE_KEY] = [row.tolist() for row in state_arr]
|
| 240 |
+
df[LANG_TOKENS_KEY] = [tok for _ in range(len(df))]
|
| 241 |
+
df[LANG_MASK_KEY] = [mask for _ in range(len(df))]
|
| 242 |
+
|
| 243 |
+
# Restore original row order (by the previous dataframe index).
|
| 244 |
+
df = df.sort_values("index").drop(columns=["index"]).reset_index(drop=True)
|
| 245 |
+
|
| 246 |
+
dp.parent.mkdir(parents=True, exist_ok=True)
|
| 247 |
+
df.to_parquet(dp, index=False)
|
| 248 |
+
|
| 249 |
+
all_states.append(state_arr)
|
| 250 |
+
all_actions.append(action_arr)
|
| 251 |
+
|
| 252 |
+
# Update info.json features.
|
| 253 |
+
info_path = output_dir / "meta" / "info.json"
|
| 254 |
+
info = json.loads(info_path.read_text())
|
| 255 |
+
features = info.get("features", {})
|
| 256 |
+
features[LANG_TOKENS_KEY] = {"dtype": "int64", "shape": [tokenizer_max_length], "names": None}
|
| 257 |
+
features[LANG_MASK_KEY] = {"dtype": "int64", "shape": [tokenizer_max_length], "names": None}
|
| 258 |
+
info["features"] = features
|
| 259 |
+
info["total_tasks"] = 1
|
| 260 |
+
info_path.write_text(json.dumps(info, indent=2))
|
| 261 |
+
|
| 262 |
+
# Update stats.json.
|
| 263 |
+
stats_path = output_dir / "meta" / "stats.json"
|
| 264 |
+
existing_stats = json.loads(stats_path.read_text()) if stats_path.exists() else {}
|
| 265 |
+
|
| 266 |
+
states = np.concatenate(all_states, axis=0)
|
| 267 |
+
actions = np.concatenate(all_actions, axis=0)
|
| 268 |
+
stats = _compute_stats(states, actions, existing_stats)
|
| 269 |
+
stats_path.write_text(json.dumps(stats, indent=2))
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def main() -> None:
|
| 273 |
+
parser = argparse.ArgumentParser(description="Patch a LeRobot dataset for SmolVLA")
|
| 274 |
+
parser.add_argument("--dataset-dir", type=str, required=True)
|
| 275 |
+
parser.add_argument("--raw-dir", type=str, required=True)
|
| 276 |
+
parser.add_argument("--output-dir", type=str, required=True)
|
| 277 |
+
parser.add_argument(
|
| 278 |
+
"--vlm-model-name",
|
| 279 |
+
type=str,
|
| 280 |
+
default="HuggingFaceTB/SmolVLM2-500M-Video-Instruct",
|
| 281 |
+
)
|
| 282 |
+
parser.add_argument("--tokenizer-max-length", type=int, default=48)
|
| 283 |
+
parser.add_argument("--no-symlink-videos", action="store_true")
|
| 284 |
+
|
| 285 |
+
args = parser.parse_args()
|
| 286 |
+
|
| 287 |
+
patch_dataset(
|
| 288 |
+
dataset_dir=Path(args.dataset_dir),
|
| 289 |
+
raw_dir=Path(args.raw_dir),
|
| 290 |
+
output_dir=Path(args.output_dir),
|
| 291 |
+
vlm_model_name=args.vlm_model_name,
|
| 292 |
+
tokenizer_max_length=args.tokenizer_max_length,
|
| 293 |
+
symlink_videos=not args.no_symlink_videos,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
if __name__ == "__main__":
|
| 298 |
+
main()
|
test_camera_fps.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import time
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
def test_camera(device_id, width=640, height=480, fps=30):
|
| 6 |
+
print(f"\n=== Testing Camera Index {device_id} ===")
|
| 7 |
+
|
| 8 |
+
# 优先使用 V4L2 后端
|
| 9 |
+
backend = cv2.CAP_V4L2 if hasattr(cv2, 'CAP_V4L2') else cv2.CAP_ANY
|
| 10 |
+
backend_name = "V4L2" if backend == cv2.CAP_V4L2 else "ANY"
|
| 11 |
+
print(f"Opening with backend: {backend_name}")
|
| 12 |
+
|
| 13 |
+
cap = cv2.VideoCapture(device_id, backend)
|
| 14 |
+
|
| 15 |
+
if not cap.isOpened():
|
| 16 |
+
print(f"Error: Could not open camera {device_id}")
|
| 17 |
+
return
|
| 18 |
+
|
| 19 |
+
# 1. 强制 MJPG
|
| 20 |
+
print("Attempting to set MJPG format...")
|
| 21 |
+
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
|
| 22 |
+
|
| 23 |
+
# 2. 设置 FPS 和 分辨率
|
| 24 |
+
cap.set(cv2.CAP_PROP_FPS, fps)
|
| 25 |
+
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
|
| 26 |
+
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
|
| 27 |
+
|
| 28 |
+
# 3. 关闭自动曝光 (Linux V4L2 特有,尝试通过 OpenCV 属性设置)
|
| 29 |
+
# 0.25 通常对应 'Manual',但在不同驱动下可能不同,这里仅作为尝试
|
| 30 |
+
# cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)
|
| 31 |
+
|
| 32 |
+
# 4. 读取实际生效的设置
|
| 33 |
+
actual_w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
|
| 34 |
+
actual_h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
|
| 35 |
+
actual_fps = cap.get(cv2.CAP_PROP_FPS)
|
| 36 |
+
fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
|
| 37 |
+
codec = "".join([chr((fourcc >> 8 * i) & 0xFF) for i in range(4)])
|
| 38 |
+
|
| 39 |
+
print(f"----------------------------------------")
|
| 40 |
+
print(f"Requested: {width}x{height} @ {fps} FPS, MJPG")
|
| 41 |
+
print(f"Actual : {actual_w}x{actual_h} @ {actual_fps} FPS, Codec: {codec}")
|
| 42 |
+
print(f"----------------------------------------")
|
| 43 |
+
|
| 44 |
+
if codec.upper() != "MJPG":
|
| 45 |
+
print("WARNING: Codec is NOT MJPG! This is likely the cause of low FPS.")
|
| 46 |
+
|
| 47 |
+
print("Warming up camera (skip 10 frames)...")
|
| 48 |
+
for _ in range(10):
|
| 49 |
+
cap.read()
|
| 50 |
+
|
| 51 |
+
print(f"Starting capture loop for 100 frames...")
|
| 52 |
+
count = 0
|
| 53 |
+
start_time = time.time()
|
| 54 |
+
|
| 55 |
+
while count < 100:
|
| 56 |
+
ret, frame = cap.read()
|
| 57 |
+
if not ret:
|
| 58 |
+
print("Error: Failed to read frame during loop")
|
| 59 |
+
break
|
| 60 |
+
count += 1
|
| 61 |
+
# 显示简略进度
|
| 62 |
+
if count % 10 == 0:
|
| 63 |
+
sys.stdout.write(f"{count}..")
|
| 64 |
+
sys.stdout.flush()
|
| 65 |
+
|
| 66 |
+
end_time = time.time()
|
| 67 |
+
duration = end_time - start_time
|
| 68 |
+
avg_fps = count / duration
|
| 69 |
+
|
| 70 |
+
print(f"\n\nRESULT: Captured {count} frames in {duration:.2f} seconds.")
|
| 71 |
+
print(f"AVERAGE FPS: {avg_fps:.2f}")
|
| 72 |
+
|
| 73 |
+
cap.release()
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
if len(sys.argv) < 2:
|
| 77 |
+
print("Usage: python test_camera_fps.py <device_id> [width] [height] [fps]")
|
| 78 |
+
print("Example: python backend/scripts/test_camera_fps.py 0 640 480 30")
|
| 79 |
+
else:
|
| 80 |
+
dev_id = int(sys.argv[1])
|
| 81 |
+
w = int(sys.argv[2]) if len(sys.argv) > 2 else 640
|
| 82 |
+
h = int(sys.argv[3]) if len(sys.argv) > 3 else 480
|
| 83 |
+
f = int(sys.argv[4]) if len(sys.argv) > 4 else 30
|
| 84 |
+
test_camera(dev_id, w, h, f)
|
| 85 |
+
|
test_camera_manager_fps.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
from core.camera import CameraManager
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main(devices, duration: float = 10.0):
|
| 9 |
+
"""
|
| 10 |
+
使用项目里的 CameraManager / SingleCamera 逻辑,单独测试真实采集 FPS,
|
| 11 |
+
不经过 FastAPI / WebSocket / DataRecorder。
|
| 12 |
+
"""
|
| 13 |
+
# Enable INFO logs so我们能看到 SingleCamera 初始化实际的分辨率 / FPS / 编码
|
| 14 |
+
logging.basicConfig(
|
| 15 |
+
level=logging.INFO,
|
| 16 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
cam_manager = CameraManager()
|
| 20 |
+
|
| 21 |
+
# 构造角色映射:head / wrist / left / right 按顺序分配
|
| 22 |
+
roles = ["head", "wrist", "left", "right", "aux"]
|
| 23 |
+
mapping = {}
|
| 24 |
+
for i, dev in enumerate(devices):
|
| 25 |
+
if i < len(roles):
|
| 26 |
+
mapping[roles[i]] = dev
|
| 27 |
+
|
| 28 |
+
print("Config mapping:", mapping)
|
| 29 |
+
cam_manager.configure(mapping, mock_all=False)
|
| 30 |
+
cam_manager.start_all()
|
| 31 |
+
|
| 32 |
+
t0 = time.time()
|
| 33 |
+
last_print = t0
|
| 34 |
+
print_interval = 1.0
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
while time.time() - t0 < duration:
|
| 38 |
+
status = cam_manager.get_status()
|
| 39 |
+
now = time.time()
|
| 40 |
+
if now - last_print >= print_interval:
|
| 41 |
+
print(f"[{now - t0:5.2f}s] Camera status:")
|
| 42 |
+
for role, info in status.items():
|
| 43 |
+
print(f" - {role}: dev={info['device_id']}, fps={info['fps']:.2f}, mock={info['is_mock']}")
|
| 44 |
+
last_print = now
|
| 45 |
+
time.sleep(0.05)
|
| 46 |
+
finally:
|
| 47 |
+
cam_manager.stop_all()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
parser = argparse.ArgumentParser()
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"devices",
|
| 54 |
+
nargs="+",
|
| 55 |
+
type=int,
|
| 56 |
+
help="Camera device indices, e.g. 0 2",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--duration",
|
| 60 |
+
type=float,
|
| 61 |
+
default=10.0,
|
| 62 |
+
help="Test duration in seconds (default 10)",
|
| 63 |
+
)
|
| 64 |
+
args = parser.parse_args()
|
| 65 |
+
main(args.devices, args.duration)
|
| 66 |
+
|
| 67 |
+
|
test_dual_cameras_fps.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
def capture_loop(device_id, width, height, fps, results, index):
|
| 7 |
+
print(f"[Cam {device_id}] Starting initialization...")
|
| 8 |
+
|
| 9 |
+
backend = cv2.CAP_V4L2 if hasattr(cv2, 'CAP_V4L2') else cv2.CAP_ANY
|
| 10 |
+
cap = cv2.VideoCapture(device_id, backend)
|
| 11 |
+
|
| 12 |
+
if not cap.isOpened():
|
| 13 |
+
print(f"[Cam {device_id}] FAILED to open.")
|
| 14 |
+
results[index] = 0.0
|
| 15 |
+
return
|
| 16 |
+
|
| 17 |
+
# 强制 MJPG
|
| 18 |
+
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
|
| 19 |
+
cap.set(cv2.CAP_PROP_FPS, fps)
|
| 20 |
+
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
|
| 21 |
+
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
|
| 22 |
+
|
| 23 |
+
# 检查实际 Codec
|
| 24 |
+
fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
|
| 25 |
+
codec = "".join([chr((fourcc >> 8 * i) & 0xFF) for i in range(4)])
|
| 26 |
+
actual_fps = cap.get(cv2.CAP_PROP_FPS)
|
| 27 |
+
print(f"[Cam {device_id}] Initialized. Codec: {codec}, Target: {fps}, Actual Report: {actual_fps}")
|
| 28 |
+
|
| 29 |
+
# 热身
|
| 30 |
+
for _ in range(10):
|
| 31 |
+
cap.read()
|
| 32 |
+
|
| 33 |
+
print(f"[Cam {device_id}] Start capturing 100 frames...")
|
| 34 |
+
|
| 35 |
+
count = 0
|
| 36 |
+
start_time = time.time()
|
| 37 |
+
|
| 38 |
+
while count < 100:
|
| 39 |
+
ret, _ = cap.read()
|
| 40 |
+
if ret:
|
| 41 |
+
count += 1
|
| 42 |
+
else:
|
| 43 |
+
time.sleep(0.001)
|
| 44 |
+
|
| 45 |
+
end_time = time.time()
|
| 46 |
+
cap.release()
|
| 47 |
+
|
| 48 |
+
duration = end_time - start_time
|
| 49 |
+
avg_fps = count / duration
|
| 50 |
+
results[index] = avg_fps
|
| 51 |
+
print(f"[Cam {device_id}] FINISHED. Avg FPS: {avg_fps:.2f}")
|
| 52 |
+
|
| 53 |
+
def test_dual_cameras(dev1, dev2):
|
| 54 |
+
print(f"=== Testing Dual Cameras Concurrent: {dev1} & {dev2} ===")
|
| 55 |
+
print("NOTE: If total bandwidth exceeds USB limit, FPS will drop.\n")
|
| 56 |
+
|
| 57 |
+
results = [0.0, 0.0]
|
| 58 |
+
|
| 59 |
+
t1 = threading.Thread(target=capture_loop, args=(dev1, 640, 480, 30, results, 0))
|
| 60 |
+
t2 = threading.Thread(target=capture_loop, args=(dev2, 640, 480, 30, results, 1))
|
| 61 |
+
|
| 62 |
+
# 同时启动
|
| 63 |
+
t1.start()
|
| 64 |
+
t2.start()
|
| 65 |
+
|
| 66 |
+
t1.join()
|
| 67 |
+
t2.join()
|
| 68 |
+
|
| 69 |
+
print("\n=== FINAL RESULTS ===")
|
| 70 |
+
print(f"Camera {dev1}: {results[0]:.2f} FPS")
|
| 71 |
+
print(f"Camera {dev2}: {results[1]:.2f} FPS")
|
| 72 |
+
|
| 73 |
+
if results[0] < 20 or results[1] < 20:
|
| 74 |
+
print("\n[!] LOW FPS DETECTED.")
|
| 75 |
+
print("Possible causes:")
|
| 76 |
+
print("1. USB Bandwidth saturation (Try plugging into different USB ports/hubs).")
|
| 77 |
+
print("2. Low light condition triggering auto-exposure lag.")
|
| 78 |
+
print("3. One camera fell back to YUYV instead of MJPG.")
|
| 79 |
+
else:
|
| 80 |
+
print("\n[OK] Both cameras running smoothly.")
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
if len(sys.argv) < 3:
|
| 84 |
+
print("Usage: python backend/scripts/test_dual_cameras_fps.py <id1> <id2>")
|
| 85 |
+
print("Example: python backend/scripts/test_dual_cameras_fps.py 0 2")
|
| 86 |
+
else:
|
| 87 |
+
test_dual_cameras(int(sys.argv[1]), int(sys.argv[2]))
|
| 88 |
+
|