mcap / scripts /convert_mcap_to_lerobot.py
CyberDJ's picture
Upload scripts/convert_mcap_to_lerobot.py with huggingface_hub
f83b064 verified
Raw
History Blame Contribute Delete
52.5 kB
"""
Convert mcap files to lerobot format within a single file.
Supports Human-in-the-Loop (HIL) data filtering by action_type.
Example Usage:
Notice:
if use multiprocessing, please make sure the repo id is a temperary repo (e.g., we_d900_temp/accessory-return)
to avoid multiple processes pushing to the same repo at the same time. After the conversion is done,
you can rename the repo to the final name (e.g., we_d900/accessory-return).
1. Normal teleoperation data processing
-> Without HIL filtering (keep all actions):
python posttraining/scripts/dataset/convert_mcap_to_lerobot.py \
--task 'accessory-return' \
--num_process 40 \
--robot_type arx \
--repo_id we_d900_temp/accessory-return \
--final_dataset_repo_root we_d900 \
--tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
--dataset_root /nas/volume1/scratch/datasets \
2. Generate human-in-the-loop (HIL) data with filtering:
python posttraining/scripts/dataset/convert_mcap_to_lerobot.py \
--task 'accessory-return' \
--num_process 40 \
--robot_type arx \
--repo_id we_d900_temp/accessory-return \
--final_dataset_repo_root we_d900 \
--tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
--dataset_root /nas/volume1/scratch/datasets \
--hil_filter
3. With custom action types, e.g. only keep "teleop":
python posttraining/scripts/dataset/convert_mcap_to_lerobot.py
--task 'accessory-return' \
--num_process 40 \
--robot_type arx \
--repo_id we_d900_temp/accessory-return \
--final_dataset_repo_root we_d900 \
--tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
--dataset_root /nas/volume1/scratch/datasets \
--action_types ["teleop"]
"""
from pathlib import Path
import gc
import os
import cv2
import tqdm
import json
import subprocess
import numpy as np
import logging
import shutil
import pandas as pd
from typing import Literal
from mcap.reader import make_reader
from lerobot.utils.constants import HF_LEROBOT_HOME
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from typing import Iterable
from foxglove_schemas_protobuf.CompressedImage_pb2 import CompressedImage
from foxglove_schemas_protobuf.FrameTransforms_pb2 import FrameTransforms
from packaging import version
from concurrent.futures import ProcessPoolExecutor
from lerobot.datasets.utils import load_tasks
import pyarrow as pa
import pyarrow.parquet as pq
import dataclasses
import argparse
logger = logging.getLogger()
DATASET_ROOT = "/nas/volume1/scratch/datasets"
TASKS_JSON_PATH = "/home/shiduozhang/projects/tasks_hil.json"
# Default commander_state values to keep for HIL data
DEFAULT_HIL_ACTION_TYPES = {"INFERENCE", "TELEOP"}
def load_task_folders(task_name: str, tasks_json_path: str = TASKS_JSON_PATH) -> list[str]:
"""
Load folder names for a specific task from tasks_merged.json.
Args:
task_name: The task name to look up
tasks_json_path: Path to the tasks_merged.json file
Returns:
List of folder names for the task
"""
import json
with open(tasks_json_path, "r", encoding="utf-8") as f:
tasks = json.load(f)
if task_name not in tasks:
available_tasks = list(tasks.keys())
raise ValueError(f"Task '{task_name}' not found. Available tasks: {available_tasks}")
return tasks[task_name]
def get_mcap_info_from_folder(folder_path: str) -> tuple[str | None, str]:
"""
Get mcap file path and version from a folder.
Args:
folder_path: Path to the folder containing mcap and metadata.json
Returns:
Tuple of (mcap_file_path, mcap_version)
"""
import json
from glob import glob
# Find mcap file (recursively)
mcap_files = glob(os.path.join(folder_path, "**/*.mcap"), recursive=True)
if not mcap_files:
# Fallback to non-recursive search
mcap_files = glob(os.path.join(folder_path, "*.mcap"))
if not mcap_files:
logger.warning(f"No mcap file found in {folder_path}")
return None, "1.12.7" # Default version
mcap_path = mcap_files[0]
# Read metadata.json for version
metadata_path = os.path.join(folder_path, "metadata.json")
mcap_version = "1.12.7" # Default version
if os.path.exists(metadata_path):
try:
with open(metadata_path, "r", encoding="utf-8") as f:
metadata = json.load(f)
mcap_version = metadata.get("version", metadata.get("mcap_version", "1.12.7"))
except Exception as e:
logger.warning(f"Error reading metadata from {metadata_path}: {e}")
return mcap_path, mcap_version
############################################# Protobuf Types #############################################
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: robotics.proto
# Protobuf Python Version: 5.29.4
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
b'\n\x0erobotics.proto\x12\x0cworld_engine\x1a\x1fgoogle/protobuf/timestamp.proto"\xc0\x01\n\x10RobotObservation\x12\x17\n\x0fjoint_positions\x18\x01 \x03(\x01\x12\x0e\n\x06\x65\x65_pos\x18\x02 \x03(\x01\x12-\n\ttimestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x18\n\x10joint_velocities\x18\x04 \x03(\x01\x12\x10\n\x08\x63urrents\x18\x05 \x03(\x01\x12\x0f\n\x07torques\x18\x06 \x03(\x01\x12\x17\n\x0f\x63ommander_state\x18\x07 \x01(\t"L\n\x0bRobotAction\x12\x0e\n\x06\x61\x63tion\x18\x01 \x03(\x01\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xbe\x02\n\x0eSyncTimestamps\x12:\n\x16robot_action_timestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12?\n\x1brobot_observation_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x38\n\x14top_camera_timestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x39\n\x15left_camera_timestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12:\n\x16right_camera_timestamp\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestampb\x06proto3'
)
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "robotics_pb2", _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals["_ROBOTOBSERVATION"]._serialized_start = 66
_globals["_ROBOTOBSERVATION"]._serialized_end = 258
_globals["_ROBOTACTION"]._serialized_start = 260
_globals["_ROBOTACTION"]._serialized_end = 336
_globals["_SYNCTIMESTAMPS"]._serialized_start = 339
_globals["_SYNCTIMESTAMPS"]._serialized_end = 657
# @@protoc_insertion_point(module_scope)
############################################# Dataset Config #############################################
@dataclasses.dataclass(frozen=True)
class DatasetConfig:
use_videos: bool = True
tolerance_s: float = 0.0001
image_writer_processes: int = 10
image_writer_threads: int = 5
video_backend: str | None = None
DEFAULT_DATASET_CONFIG = DatasetConfig()
############################################# Robot Config #############################################
@dataclasses.dataclass(frozen=True)
class DualArmConfig:
robot_type: str = "piper"
left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])
right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])
arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: []) # Exclude gripper
motors: list[str] = dataclasses.field(default_factory=lambda: [])
camera_keys: list[str] = dataclasses.field(default_factory=lambda: [])
cam_key_maps: dict[str, str] = dataclasses.field(default_factory=lambda: {})
@dataclasses.dataclass(frozen=True)
class DualPiperConfig(DualArmConfig):
robot_type: str = "piper"
left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 6])
right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [7, 8, 9, 10, 11, 12, 13])
arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]) # Exclude gripper
motors: list[str] = dataclasses.field(
default_factory=lambda: [
"left_waist",
"left_shoulder",
"left_elbow",
"left_forearm_roll",
"left_wrist_angle",
"left_wrist_rotate",
"left_gripper",
"right_waist",
"right_shoulder",
"right_elbow",
"right_forearm_roll",
"right_wrist_angle",
"right_wrist_rotate",
"right_gripper",
]
)
camera_keys: list[str] = dataclasses.field(
default_factory=lambda: [
"left_camera",
"right_camera",
"top_camera",
]
)
cam_key_maps: dict[str, str] = dataclasses.field(
default_factory=lambda: {
"left_camera": "cam_left_wrist",
"right_camera": "cam_right_wrist",
"top_camera": "cam_high",
}
)
@dataclasses.dataclass(frozen=True)
class DualArxConfig(DualArmConfig):
robot_type: str = "arx"
left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 6])
right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [7, 8, 9, 10, 11, 12, 13])
arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]) # Exclude gripper
motors: list[str] = dataclasses.field(
default_factory=lambda: [
"left_waist",
"left_shoulder",
"left_elbow",
"left_forearm_roll",
"left_wrist_angle",
"left_wrist_rotate",
"left_gripper",
"right_waist",
"right_shoulder",
"right_elbow",
"right_forearm_roll",
"right_wrist_angle",
"right_wrist_rotate",
"right_gripper",
]
)
camera_keys: list[str] = dataclasses.field(
default_factory=lambda: [
"left_camera",
"right_camera",
"top_camera",
]
)
cam_key_maps: dict[str, str] = dataclasses.field(
default_factory=lambda: {
"left_camera": "cam_left_wrist",
"right_camera": "cam_right_wrist",
"top_camera": "cam_high",
}
)
############################################# LeRobot Utils #############################################
def create_empty_dataset(
repo_id: str,
robot_type: str,
mode: Literal["video", "image"] = "video",
*,
dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
fps=60,
image_size: tuple[int, int] = (320, 180),
cam_key_maps: dict[str, str] = {},
motors: list[str] = [],
generate_vel: bool = False,
record_mcap_path: bool = False,
) -> LeRobotDataset:
"""Create an empty LeRobot dataset."""
cameras = list(cam_key_maps.values())
features = {
"observation.state": {
"dtype": "float32",
"shape": (len(motors),),
"names": motors,
},
"observation.commander_state": {
"dtype": "string",
"shape": (1,),
"names": ["commander_states"],
},
"action": {
"dtype": "float32",
"shape": (len(motors),),
"names": motors,
},
}
if record_mcap_path:
features["mcap_path"] = {
"dtype": "string",
"shape": (1,),
"names": ["mcap_path"],
}
if generate_vel:
features["observation.velocity"] = {
"dtype": "float32",
"shape": (len(motors),),
"names": motors,
}
features["action_vel"] = {
"dtype": "float32",
"shape": (len(motors),),
"names": motors,
}
for cam in cameras:
features[f"observation.images.{cam}"] = {
"dtype": mode,
"shape": (image_size[1], image_size[0], 3),
"names": [
"height",
"width",
"channels",
],
}
features["subtask"] = {
"dtype": "string",
"shape": (1,),
"names": ["subtask"],
}
if Path(HF_LEROBOT_HOME / repo_id).exists():
shutil.rmtree(HF_LEROBOT_HOME / repo_id)
dataset = LeRobotDataset.create(
repo_id=repo_id,
fps=fps,
robot_type=robot_type,
features=features,
use_videos=dataset_config.use_videos,
tolerance_s=dataset_config.tolerance_s,
image_writer_processes=dataset_config.image_writer_processes,
image_writer_threads=dataset_config.image_writer_threads,
video_backend=dataset_config.video_backend,
)
dataset.meta.update_chunk_settings(data_files_size_in_mb=0, video_files_size_in_mb=0)
return dataset
def check_mcap_validity(data_dict_chunk: dict, action_threshold: float = 10.0) -> bool:
actions_raw = data_dict_chunk["actions"]
if np.max(np.abs(actions_raw)) > action_threshold:
mcap_info = data_dict_chunk.get("mcap_path", "unknown")
logger.warning(
f"Skipping mcap file {mcap_info}: max abs actions value "
f"{np.max(np.abs(actions_raw)):.4f} exceeds {action_threshold}"
)
return True
return False
def populate_dataset_from_raw_loader(
dataset: LeRobotDataset,
raw_episode_loader: Iterable[dict],
cam_keys: list[str],
cam_key_maps: dict[str, str],
task: str | list[str] = "Do something",
generate_vel: bool = False,
chunk_size: int = 1000,
record_mcap_path: bool = False,
):
"""Populate a LeRobot dataset from a raw data loader."""
pbar = tqdm.tqdm(total=len(raw_episode_loader))
skip_current_episode = False
is_first_chunk_of_episode = True # Track first chunk to avoid orphaned frames
for is_new_episode, data_dict_chunk in raw_episode_loader:
if is_new_episode:
# Update the episode index
if not skip_current_episode:
dataset.save_episode()
pbar.update(1)
skip_current_episode = False # Reset for new episode
is_first_chunk_of_episode = True # New episode starts
# Only check validity on the FIRST chunk of each episode.
# Checking on later chunks is unsafe: frames from earlier chunks are already
# in the LeRobot buffer and cannot be undone, so setting skip_current_episode=True
# mid-episode leaves orphan frames that corrupt the next episode.
if is_first_chunk_of_episode:
skip_current_episode = check_mcap_validity(data_dict_chunk)
is_first_chunk_of_episode = False
if skip_current_episode:
continue
num_frames_chunk = len(data_dict_chunk["joint_poses"])
camera_images = {key: data_dict_chunk["camera_images"][key] for key in cam_keys}
valid_frames = list(range(num_frames_chunk))
joint_poses = data_dict_chunk["joint_poses"][valid_frames]
ee_poses = data_dict_chunk["ee_poses"][valid_frames]
if "commander_states" in data_dict_chunk:
commander_states = [data_dict_chunk["commander_states"][i].lower() for i in valid_frames]
else:
commander_states = ["teleop"] * len(valid_frames)
actions = data_dict_chunk["actions"][valid_frames]
if generate_vel:
joint_vel = data_dict_chunk["joint_vel"][valid_frames]
actions_vel = data_dict_chunk["actions_vel"][valid_frames]
for cam_key in cam_keys:
camera_images[cam_key] = data_dict_chunk["camera_images"][cam_key][valid_frames]
num_frames_chunk = len(joint_poses)
# Get mcap_path if recording
mcap_path = data_dict_chunk.get("mcap_path", "") if record_mcap_path else None
if "task" in data_dict_chunk:
task_episode = data_dict_chunk["task"]
elif task is None:
task_episode = "Do something"
else:
task_episode = task
for frame_idx in range(num_frames_chunk):
# FIXME: Allow the episode to change task within the episode
frame = {
"task": task_episode[frame_idx] if isinstance(task_episode, list) else task_episode,
"observation.state": joint_poses[frame_idx],
"action": actions[frame_idx],
}
if generate_vel:
frame["observation.velocity"] = joint_vel[frame_idx]
frame["action_vel"] = actions_vel[frame_idx]
frame["observation.commander_state"] = commander_states[frame_idx]
if record_mcap_path and mcap_path:
frame["mcap_path"] = mcap_path
for cam_key in cam_keys:
frame[f"observation.images.{cam_key_maps[cam_key]}"] = camera_images[cam_key][frame_idx]
frame["subtask"] = "TODO" # TODO: add subtask annotation
dataset.add_frame(frame)
# Save the last episode
if not skip_current_episode:
dataset.save_episode()
pbar.update(1)
pbar.close()
############################################# Utils #############################################
def resize_image(img_str, resize=True, image_size: tuple[int, int] = (320, 180)):
# Handle case where input is already bytes
if isinstance(img_str, bytes):
img_bytes = img_str
else:
# Original code for hex string
img_bytes = bytes.fromhex(img_str)
img_np = np.frombuffer(img_bytes, dtype=np.uint8)
img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
if resize:
img = cv2.resize(img, (image_size[0], image_size[1]))
# Convert rgb to bgr
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
############################################# Load raw data from mcap #############################################
def read_mcap_msg(mcap_path, cam_keys: list[str]):
"""
Read messages from an MCAP file.
Args:
mcap_path: Path to the MCAP file
"""
# Verify file exists
if not os.path.exists(mcap_path):
raise FileNotFoundError(f"MCAP file not found at {mcap_path}")
# Dictionary to store message type handlers
handlers = {
"robot_observation": RobotObservation,
"robot_action": RobotAction,
"sync_timestamps": SyncTimestamps,
"/tf": FrameTransforms,
}
for cam_key in cam_keys:
handlers[cam_key] = CompressedImage
# Statistics to track message counts
message_counts = {topic: 0 for topic in handlers.keys()}
messages = []
# Open and read the MCAP file
with open(mcap_path, "rb") as f:
reader = make_reader(f)
# Iterate through all messages
for schema, channel, message in reader.iter_messages():
# Get the appropriate message handler
if channel.topic in handlers:
message_type = handlers[channel.topic]
parsed_msg = message_type()
parsed_msg.ParseFromString(message.data)
# Update message count
message_counts[channel.topic] += 1
# Read out data based topic
if channel.topic == "robot_observation":
data = {
"joint_positions": parsed_msg.joint_positions,
"joint_velocities": parsed_msg.joint_velocities,
"ee_pose": parsed_msg.ee_pos,
"currents": parsed_msg.currents,
"torques": parsed_msg.torques,
"commander_state": parsed_msg.commander_state,
}
timestamp = parsed_msg.timestamp.ToNanoseconds()
elif channel.topic == "robot_action":
data = parsed_msg.action
timestamp = parsed_msg.timestamp.ToNanoseconds()
elif channel.topic == "sync_timestamps":
data = {
f"{k}_timestamp": parsed_msg.__getattribute__(f"{k}_timestamp").ToNanoseconds()
for k in handlers.keys()
if hasattr(parsed_msg, f"{k}_timestamp")
}
timestamp = min(data.values())
elif channel.topic in cam_keys:
data = parsed_msg.data
timestamp = parsed_msg.timestamp.ToNanoseconds()
elif channel.topic == "tf":
data = parsed_msg.data
timestamp = parsed_msg.timestamp.ToNanoseconds()
messages.append(
{
"timestamp": timestamp,
"data": data,
"channel": channel.topic,
"schema": schema,
}
)
return messages
def read_mcap_file(file_path, cam_keys: list[str]):
"""
Read messages from an MCAP file
"""
messages = read_mcap_msg(file_path, cam_keys=cam_keys)
robot_joint_pos = {}
robot_action = {}
robo_ee_pose = {}
commander_state = {}
camera_images = {key: {} for key in cam_keys}
sync_timestamps = {}
for message in messages:
data = message["data"]
if message["channel"] == "robot_observation":
robot_joint_pos[message["timestamp"]] = data["joint_positions"]
commander_state[message["timestamp"]] = data["commander_state"]
robo_ee_pose[message["timestamp"]] = data["ee_pose"]
elif message["channel"] == "robot_action":
robot_action[message["timestamp"]] = data
elif message["channel"] in cam_keys:
camera_images[message["channel"]][message["timestamp"]] = data
elif message["channel"] == "sync_timestamps":
sync_timestamps[message["timestamp"]] = data
return {
"robot_joint_pos": robot_joint_pos,
"robot_action": robot_action,
"robo_ee_pose": robo_ee_pose,
"commander_state": commander_state,
"camera_images": camera_images,
"sync_timestamps": sync_timestamps,
}
def load_timed_data_from_mcap(
mcap_file: str,
cam_keys,
fps=60,
start_frame=0,
max_frame=None,
resize=True,
image_size: tuple[int, int] = (320, 180),
mcap_version: str = "0.0.0",
generate_vel: bool = False,
chunk_size: int = 1000, # Process data in chunks to reduce memory pressure
robot_type: str = "piper",
filter_action_types: set[str] | None = None, # HIL: action types to keep
):
"""Load the timed data from mcap with a given fps.
Args:
mcap_file: Path to the MCAP file
cam_keys: List of camera keys
fps: Frames per second
start_frame: Starting frame index
max_frame: Maximum number of frames to process
resize: Whether to resize images
image_size: Target image size (width, height)
mcap_version: MCAP version string
generate_vel: Whether to generate velocity data
chunk_size: Process data in chunks
robot_type: Type of robot
filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
If None, all actions are kept.
"""
# Read MCAP file
mcap_dict = read_mcap_file(mcap_file, cam_keys=cam_keys)
ds_sync_timestamps = mcap_dict["sync_timestamps"]
# If there are no explicit sync_timestamps in the MCAP, build a fallback
# nearest-neighbor synchronization using robot_observation timestamps as the
# reference timeline and matching camera & action timestamps to the closest
# available times. This keeps behavior robust when recordings don't emit
# a dedicated sync message.
if not ds_sync_timestamps:
logger.info("No sync_timestamps found in MCAP; building fallback nearest-neighbor sync using camera as reference")
from bisect import bisect_left
def nearest(sorted_list, value):
if not sorted_list:
return None
i = bisect_left(sorted_list, value)
if i == 0:
return sorted_list[0]
if i == len(sorted_list):
return sorted_list[-1]
before = sorted_list[i - 1]
after = sorted_list[i]
if abs(after - value) < abs(value - before):
return after
else:
return before
# tolerance for matching (seconds -> nanoseconds).
fallback_tol_s = max(DEFAULT_DATASET_CONFIG.tolerance_s, 1.0 / fps / 2.0)
tol_ns = int(fallback_tol_s * 1e9)
# prepare sorted timestamp lists
obs_ts = sorted(mcap_dict["robot_joint_pos"].keys())
action_ts = sorted(mcap_dict["robot_action"].keys())
cam_ts_map = {k: sorted(mcap_dict["camera_images"][k].keys()) for k in cam_keys}
# Use the first camera as the reference timeline
reference_cam_key = cam_keys[0]
reference_cam_ts = cam_ts_map.get(reference_cam_key, [])
if not reference_cam_ts:
logger.warning(f"Reference camera {reference_cam_key} has no timestamps")
ds_sync_timestamps = {}
else:
ds_sync_timestamps = {}
for cam_t in reference_cam_ts:
sync = {}
sync[f"{reference_cam_key}_timestamp"] = cam_t
# nearest robot observation
no = nearest(obs_ts, cam_t)
if no is None or abs(no - cam_t) > tol_ns:
continue
sync["robot_observation_timestamp"] = no
# nearest action
na = nearest(action_ts, cam_t)
if na is None or abs(na - cam_t) > tol_ns:
continue
sync["robot_action_timestamp"] = na
# nearest timestamps for other cameras
skip = False
for cam_key in cam_keys:
if cam_key == reference_cam_key:
continue # already added
nc = nearest(cam_ts_map.get(cam_key, []), cam_t)
if nc is None or abs(nc - cam_t) > tol_ns:
# If camera is missing or too far from reference camera, skip this frame
skip = True
break
sync[f"{cam_key}_timestamp"] = nc
if skip:
continue
# use reference camera timestamp as the dict key for ordering
ds_sync_timestamps[cam_t] = sync
# Pre-allocate arrays for the current chunk
chunk_joint_poses = []
chunk_ee_poses = []
chunk_commander_states = []
chunk_actions = []
chunk_camera_images = {key: [] for key in cam_keys}
episode_length = 0
has_zero_ts = False
has_missing_ts = False
filtered_count = 0 # Count of frames filtered by action_type
# Process timestamps in sorted order
sorted_timestamps = sorted(ds_sync_timestamps.keys())
total_frames = len(sorted_timestamps)
for idx, key in enumerate(sorted_timestamps):
if idx < start_frame:
continue
if max_frame is not None and idx >= (start_frame + max_frame):
break
sync_ts = ds_sync_timestamps[key]
# Skip if any camera timestamp is None or 0
is_zero_ts = False
for cam_key in cam_keys:
if sync_ts[f"{cam_key}_timestamp"] is None or sync_ts[f"{cam_key}_timestamp"] == 0:
is_zero_ts = True
break
if is_zero_ts:
has_zero_ts = True
continue
# Check existence of sync_ts in all camera_images
is_missing_ts = False
for cam_key in cam_keys:
if sync_ts[f"{cam_key}_timestamp"] not in mcap_dict["camera_images"][cam_key]:
logger.warning(f"Sync timestamp {sync_ts[f'{cam_key}_timestamp']} not found in {cam_key} camera images, mcap file: {mcap_file}")
is_missing_ts = True
break
if is_missing_ts:
has_missing_ts = True
continue
# HIL Filtering: Check commander_state and skip if not in filter set
if filter_action_types is not None:
obs_ts = sync_ts["robot_observation_timestamp"]
cmd_state = mcap_dict["commander_state"].get(obs_ts, "")
if cmd_state not in filter_action_types:
filtered_count += 1
continue
episode_length += 1
# Process current frame
joint_pos = np.array(mcap_dict["robot_joint_pos"][sync_ts["robot_observation_timestamp"]]).reshape(1, -1)
ee_pos = np.array(mcap_dict["robo_ee_pose"][sync_ts["robot_observation_timestamp"]]).reshape(1, -1)
commander_state = mcap_dict["commander_state"][sync_ts["robot_observation_timestamp"]]
if filter_action_types is not None:
commander_state = "ap_" + commander_state.lower() # Prefix with "ap_" to indicate it's autopilot state (e.g., "ap_inference", "ap_teleop")
action = np.array(mcap_dict["robot_action"][sync_ts["robot_action_timestamp"]]).reshape(1, -1)
# Append to current chunk
chunk_joint_poses.append(joint_pos)
chunk_ee_poses.append(ee_pos)
chunk_commander_states.append(commander_state)
chunk_actions.append(action)
# Process images
for cam_key in cam_keys:
img_data = mcap_dict["camera_images"][cam_key][sync_ts[f"{cam_key}_timestamp"]]
img = resize_image(img_data, resize=resize, image_size=image_size)
chunk_camera_images[cam_key].append(img)
# Process chunk if it reaches the specified size or we're at the end
if len(chunk_joint_poses) >= chunk_size or idx == total_frames - 1:
# Skip if no data in chunk (all frames were filtered)
if len(chunk_joint_poses) == 0:
continue
# Convert lists to numpy arrays
joint_poses_chunk = np.concatenate(chunk_joint_poses, axis=0).astype(np.float32)
ee_poses_chunk = np.concatenate(chunk_ee_poses, axis=0).astype(np.float32)
actions_chunk = np.concatenate(chunk_actions, axis=0).astype(np.float32)
# Version-aware action normalization
if version.parse(mcap_version) <= version.parse("1.10.1"):
actions_chunk[:, 6] = actions_chunk[:, 6] / 0.08
actions_chunk[:, 13] = actions_chunk[:, 13] / 0.08
# if robot_type == "arx" and version.parse(mcap_version) <= version.parse("1.12.7"):
# actions_chunk[:, 6] = actions_chunk[:, 6] * 0.08
# actions_chunk[:, 13] = actions_chunk[:, 13] * 0.08
# Process camera images
camera_images_chunk = {}
for cam_key in cam_keys:
camera_images_chunk[cam_key] = np.stack(chunk_camera_images[cam_key], axis=0).astype(np.uint8)
# Generate velocities if requested
if generate_vel:
joint_vel_chunk = np.diff(joint_poses_chunk, axis=0)
joint_vel_chunk = np.concatenate([joint_vel_chunk, np.zeros((1, joint_vel_chunk.shape[1]))], axis=0).astype(np.float32)
actions_vel_chunk = np.diff(actions_chunk, axis=0)
actions_vel_chunk = np.concatenate([actions_vel_chunk, np.zeros((1, actions_vel_chunk.shape[1]))], axis=0).astype(np.float32)
# Yield the current chunk
chunk_data = {
"joint_poses": joint_poses_chunk,
"ee_poses": ee_poses_chunk,
"commander_states": chunk_commander_states,
"actions": actions_chunk,
"camera_images": camera_images_chunk,
"info": {
"has_zero_ts": has_zero_ts,
"has_missing_ts": has_missing_ts,
"filtered_count": filtered_count, # Include filtered count in info
},
}
if generate_vel:
chunk_data["joint_vel"] = joint_vel_chunk
chunk_data["actions_vel"] = actions_vel_chunk
yield chunk_data
# Clear chunk data
chunk_joint_poses = []
chunk_ee_poses = []
chunk_commander_states = []
chunk_actions = []
chunk_camera_images = {key: [] for key in cam_keys}
# Force garbage collection
gc.collect()
# Log filtering statistics
if filter_action_types is not None and filtered_count > 0:
logger.info(f"HIL filtering: {filtered_count} frames filtered out (kept action_types: {filter_action_types})")
############################################# Generate LeRobot Dataset #############################################
class McapDataLoader:
"""
Load data from mcap files and convert to LeRobot format.
McapDataLoader load mcap in chunks to reduce memory pressure.
"""
def __init__(
self,
mcap_files: list[str],
mcap_versions: list[str],
cam_keys: list[str],
image_size: tuple[int, int],
generate_vel: bool = False,
chunk_size: int = 1000,
robot_type: str = "piper",
record_mcap_path: bool = False,
filter_action_types: set[str] | None = None, # HIL: action types to keep
):
self.mcap_files = mcap_files
self.mcap_versions = mcap_versions
self.cam_keys = cam_keys
self.image_size = image_size
self.generate_vel = generate_vel
self.episode_idx = 0
self.chunk_size = chunk_size
self.robot_type = robot_type
self.record_mcap_path = record_mcap_path
self.filter_action_types = filter_action_types
def __len__(self):
return len(self.mcap_files)
def __iter__(self):
while self.episode_idx < len(self.mcap_files):
mcap_file = self.mcap_files[self.episode_idx]
mcap_version = self.mcap_versions[self.episode_idx]
print(f"Processing {mcap_file} with version {mcap_version}")
# Ensure the loop variable exists even if the loader yields nothing
data_dict_chunk = None
for _i, data_dict_chunk in enumerate(load_timed_data_from_mcap(
mcap_file,
cam_keys=self.cam_keys,
image_size=self.image_size,
mcap_version=mcap_version,
generate_vel=self.generate_vel,
chunk_size=self.chunk_size,
robot_type=self.robot_type,
filter_action_types=self.filter_action_types, # Pass HIL filter
)):
# Add mcap_path to chunk data if recording
if self.record_mcap_path:
data_dict_chunk["mcap_path"] = mcap_file
yield (_i == 0) and (self.episode_idx != 0), data_dict_chunk
# Clear memory (only delete if assigned)
if data_dict_chunk is not None:
del data_dict_chunk
# Collect garbage
gc.collect()
# Increment episode index
self.episode_idx += 1
def populate_dataset_from_mcap(
task: str | list[str],
dataset: LeRobotDataset,
mcap_files: list[str],
mcap_versions: list[str],
episodes: list[int] | None = None,
image_size: tuple[int, int] = (320, 180),
cam_keys: list[str] = ["top_camera", "left_camera", "right_camera"],
cam_key_maps: dict[str, str] = {
"top_camera": "cam_high",
"left_camera": "cam_left_wrist",
"right_camera": "cam_right_wrist",
},
arm_joint_idx: list[int] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12],
generate_vel: bool = False,
chunk_size: int = 1000,
robot_type: str = "piper",
record_mcap_path: bool = False,
filter_action_types: set[str] | None = None, # HIL: action types to keep
) -> LeRobotDataset:
"""
Populate the dataset with the raw data from the mcap files.
Args:
dataset: The dataset to populate.
mcap_files: The list of mcap files to populate the dataset with.
mcap_versions: The list of mcap versions corresponding to the mcap files.
episodes: The list of episodes to populate the dataset with.
image_size: The size of the images to resize to.
generate_vel: Whether to generate velocity data.
record_mcap_path: Whether to record mcap path in the dataset.
filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
"""
if episodes is None:
episodes = range(len(mcap_files))
mcap_data_loader = McapDataLoader(
mcap_files=mcap_files,
mcap_versions=mcap_versions,
cam_keys=cam_keys,
image_size=image_size,
generate_vel=generate_vel,
chunk_size=chunk_size,
robot_type=robot_type,
record_mcap_path=record_mcap_path,
filter_action_types=filter_action_types, # Pass HIL filter
)
populate_dataset_from_raw_loader(
dataset=dataset,
raw_episode_loader=mcap_data_loader,
cam_keys=cam_keys,
cam_key_maps=cam_key_maps,
task=task,
generate_vel=generate_vel,
chunk_size=chunk_size,
record_mcap_path=record_mcap_path,
)
def convert_mcap_to_lerobot(
repo_id: str,
task: str,
mcap_files: list[str],
mcap_versions: list[str],
robot_type: str,
fps: int,
episodes: list[int] | None = None,
push_to_hub: bool = False,
mode: str = "video",
image_size: tuple[int, int] = (320, 180),
robot_config: DualPiperConfig = DualPiperConfig(),
dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
generate_vel: bool = False,
chunk_size: int = 1000,
record_mcap_path: bool = False,
filter_action_types: set[str] | None = None, # HIL: action types to keep
**kwargs
):
if (HF_LEROBOT_HOME / repo_id).exists():
shutil.rmtree(HF_LEROBOT_HOME / repo_id)
dataset = create_empty_dataset(
repo_id,
robot_type=robot_type,
mode=mode,
dataset_config=dataset_config,
fps=fps,
image_size=image_size,
cam_key_maps=robot_config.cam_key_maps,
motors=robot_config.motors,
generate_vel=generate_vel,
record_mcap_path=record_mcap_path,
)
dataset = populate_dataset_from_mcap(
task=task,
dataset=dataset,
mcap_files=mcap_files,
mcap_versions=mcap_versions,
episodes=episodes,
image_size=image_size,
cam_keys=robot_config.camera_keys,
cam_key_maps=robot_config.cam_key_maps,
arm_joint_idx=robot_config.arm_joint_idx,
generate_vel=generate_vel,
chunk_size=chunk_size,
robot_type=robot_type,
record_mcap_path=record_mcap_path,
filter_action_types=filter_action_types, # Pass HIL filter
)
if push_to_hub:
dataset.push_to_hub()
def process_worker(
process_id: int,
process_episodes: list[int],
repo_id: str,
task: str,
mcap_files: list[str],
mcap_versions: list[str],
robot_type: str,
fps: int,
mode: str,
image_size: tuple[int, int],
dataset_config: DatasetConfig,
generate_vel: bool,
chunk_size: int,
record_mcap_path: bool,
filter_action_types: set[str] | None = None, # HIL: action types to keep
):
temp_repo_id = f"{repo_id}_{process_id}"
process_mcap_files = [mcap_files[i] for i in process_episodes]
process_mcap_versions = [mcap_versions[i] for i in process_episodes]
# Create and populate dataset for this process
convert_mcap_to_lerobot(
repo_id=temp_repo_id,
task=task,
mcap_files=process_mcap_files,
mcap_versions=process_mcap_versions,
robot_type=robot_type,
fps=fps,
episodes=process_episodes,
push_to_hub=False,
mode=mode,
image_size=image_size,
dataset_config=dataset_config,
generate_vel=generate_vel,
chunk_size=chunk_size,
record_mcap_path=record_mcap_path,
filter_action_types=filter_action_types, # Pass HIL filter
)
return temp_repo_id
def convert_mcap_to_lerobot_multiple_process(
repo_id: str,
task: str,
mcap_files: list[str],
mcap_versions: list[str],
num_processes: int = 4,
robot_type: str = "piper",
fps: int = 60,
episodes: list[int] | None = None,
mode: Literal["video", "image"] = "video",
image_size: tuple[int, int] = (320, 180),
robot_config=DualPiperConfig(),
dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
generate_vel: bool = False,
chunk_size: int = 1000,
push_to_hub: bool = False,
record_mcap_path: bool = False,
filter_action_types: set[str] | None = None, # HIL: action types to keep
) -> list[str]:
"""
Convert MCAP files to LeRobot format using multiple processes.
Each process processes a subset of episodes and saves to a temporary repo.
Returns a list of temporary repo_ids that need to be merged.
Args:
repo_id: Base repo_id for the dataset
task: Task name
mcap_files: List of MCAP file paths
mcap_versions: List of MCAP versions
num_processes: Number of processes to use
fps: Frames per second
episodes: List of episode indices to process
mode: Dataset mode (video or image)
image_size: Size of images
dataset_config: Dataset configuration
generate_vel: Whether to generate velocity data
filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
Returns:
List of temporary repo_ids that need to be merged
"""
if episodes is None:
episodes = list(range(len(mcap_files)))
# Split episodes among processes
episodes_per_process = len(episodes) // num_processes
remaining_episodes = len(episodes) % num_processes
process_episodes = []
start_idx = 0
for i in range(num_processes):
# Distribute remaining episodes among processes
extra = 1 if i < remaining_episodes else 0
end_idx = start_idx + episodes_per_process + extra
process_episodes.append(episodes[start_idx:end_idx])
start_idx = end_idx
temp_repo_ids = []
# Create and start processes using ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=num_processes) as executor:
futures = []
for i in range(num_processes):
future = executor.submit(
process_worker,
i,
process_episodes[i],
repo_id,
task,
mcap_files,
mcap_versions,
robot_type,
fps,
mode,
image_size,
dataset_config,
generate_vel,
chunk_size,
record_mcap_path,
filter_action_types, # Pass HIL filter
)
futures.append(future)
# Wait for all processes to complete and collect results
for future in futures:
temp_repo_ids.append(future.result())
return temp_repo_ids
############################################# Convert Task to LeRobot #############################################
def convert_task_to_lerobot(
task_name: str,
repo_id: str | None = None,
robot_type: str = "piper",
fps: int = 60,
mode: str = "video",
image_size: tuple[int, int] = (320, 180),
robot_config: DualArmConfig | None = None,
dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
generate_vel: bool = False,
chunk_size: int = 1000,
num_processes: int = 1,
push_to_hub: bool = False,
tasks_json_path: str = TASKS_JSON_PATH,
dataset_root: str = DATASET_ROOT,
filter_action_types: set[str] | None = None, # HIL: action types to keep,
final_dataset_repo_root: str | Path = "we_d900",
):
"""
Convert all mcap files for a specific task to a single LeRobot dataset.
Args:
task_name: The task name from tasks_merged.json
repo_id: Repository ID for the dataset (default: task_name with spaces replaced by underscores)
robot_type: Type of robot ("piper" or "arx")
fps: Frames per second
mode: Dataset mode ("video" or "image")
image_size: Size of images to resize to
robot_config: Robot configuration (auto-selected based on robot_type if None)
dataset_config: Dataset configuration
generate_vel: Whether to generate velocity data
chunk_size: Process data in chunks
num_processes: Number of processes for parallel processing
push_to_hub: Whether to push to Hugging Face Hub
tasks_json_path: Path to tasks_merged.json
dataset_root: Root directory containing the dataset folders
filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
Default is None (keep all). For HIL data, use DEFAULT_HIL_ACTION_TYPES.
"""
# Load folders for the task
folders = load_task_folders(task_name, tasks_json_path)
print(f"Found {len(folders)} folders for task '{task_name}'")
# Collect mcap files and versions
mcap_files = []
mcap_versions = []
for folder in tqdm.tqdm(folders, desc="Collecting mcap files"):
if os.path.exists(folder):
folder_path = folder
elif os.path.exists(os.path.join(dataset_root, folder)):
folder_path = os.path.join(dataset_root, folder)
elif os.path.exists(os.path.join(dataset_root, task_name, folder)):
folder_path = os.path.join(dataset_root, task_name, folder)
else:
raise FileNotFoundError(f"Folder {folder} not found in dataset_root {dataset_root}")
mcap_path, mcap_version = get_mcap_info_from_folder(folder_path)
if mcap_path:
mcap_files.append(mcap_path)
mcap_versions.append(mcap_version)
print(f"Found {len(mcap_files)} mcap files")
if not mcap_files:
print("No mcap files found, exiting")
return
# Set default repo_id
if repo_id is None:
repo_id = f"worldengine/{task_name.replace(' ', '_').lower()}"
# Set default robot_config based on robot_type
if robot_config is None:
if robot_type == "arx":
robot_config = DualArxConfig()
else:
robot_config = DualPiperConfig()
# Log HIL filtering info
if filter_action_types is not None:
print(f"HIL filtering enabled: keeping action_types {filter_action_types}")
# Convert to LeRobot dataset
config = {
"mcap_files": mcap_files,
"mcap_versions": mcap_versions,
"robot_type": robot_type,
"fps": fps,
"mode": mode,
"num_processes": num_processes,
"image_size": image_size,
"robot_config": robot_config,
"dataset_config": dataset_config,
"generate_vel": generate_vel,
"chunk_size": chunk_size,
"repo_id": repo_id,
"task": task_name,
"episodes": None,
"push_to_hub": push_to_hub,
"record_mcap_path": True, # Always record mcap path
"filter_action_types": filter_action_types, # HIL filter
}
if num_processes > 1:
temp_repo_ids = convert_mcap_to_lerobot_multiple_process(**config)
if not isinstance(temp_repo_ids, list):
temp_repo_ids = [temp_repo_ids]
# Filter out empty temp datasets (workers that produced 0 episodes have no tasks.parquet)
non_empty_repo_ids = []
for tmp_id in temp_repo_ids:
tasks_parquet = Path(HF_LEROBOT_HOME) / tmp_id / "meta" / "tasks.parquet"
if tasks_parquet.exists():
non_empty_repo_ids.append(tmp_id)
else:
print(f" Skipping empty temp dataset (0 episodes): {tmp_id}")
if not non_empty_repo_ids:
print("All worker datasets are empty — no episodes to merge. Aborting.")
return
print(f"Merging {len(non_empty_repo_ids)}/{len(temp_repo_ids)} non-empty temporary datasets...")
repo_ids_str = json.dumps(non_empty_repo_ids)
cmd = [
"python", "-m", "lerobot.scripts.lerobot_edit_dataset",
"--repo_id", f"{final_dataset_repo_root}/{task_name}",
"--operation.type", "merge",
"--operation.repo_ids", repo_ids_str,
"--data_files_size_in_mb", "0",
"--video_files_size_in_mb", "0"
]
try:
result = subprocess.run(
cmd,
check=True,
capture_output=True,
text=True
)
print("Command executed successfully!")
print("STDOUT:", result.stdout)
return result
except subprocess.CalledProcessError as e:
print(f"Error executing command: {e}")
print("STDERR:", e.stderr)
raise
finally:
# Delete all temp datasets (including empty ones)
for repo_id in temp_repo_ids:
tmp_path = Path(HF_LEROBOT_HOME) / repo_id
if tmp_path.exists():
shutil.rmtree(tmp_path)
else:
convert_mcap_to_lerobot(**config)
print(f"Dataset saved to {HF_LEROBOT_HOME / repo_id}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert MCAP files to LeRobot format (with HIL support).")
parser.add_argument("--task", type=str, default=None, required=True, help="Task name from tasks_merged.json to convert")
parser.add_argument("--num_process", type=int, default=1, help="Number of processes to use")
parser.add_argument("--robot_type", type=str, default="piper", help="Type of robot (e.g., 'arx', 'piper')")
parser.add_argument("--repo_id", type=str, default=None, help="Repository ID for the dataset")
parser.add_argument("--fps", type=int, default=60, help="Frames per second")
parser.add_argument("--tasks_json_path", type=str, default=TASKS_JSON_PATH, help="The json path to store the raw data directories of each task")
parser.add_argument("--dataset_root", type=str, default=DATASET_ROOT, help="the dataset root of the raw mcap data")
parser.add_argument("--final_dataset_repo_root", type=str, default="we_d900", help="The final dataset repo root to save the merged dataset")
parser.add_argument(
"--hil_filter",
action="store_true",
help="Enable HIL filtering: only keep 'inference' and 'teleoperation' action types"
)
parser.add_argument(
"--action_types",
type=str,
nargs="+",
default=None,
help="Custom action types to keep (e.g., --action_types inference teleoperation). Overrides --hil_filter."
)
args = parser.parse_args()
# Determine action types filter
filter_action_types = None
if args.action_types:
filter_action_types = set(args.action_types)
elif args.hil_filter:
filter_action_types = DEFAULT_HIL_ACTION_TYPES
convert_task_to_lerobot(
task_name=args.task,
repo_id=args.repo_id,
robot_type=args.robot_type,
fps=args.fps,
num_processes=args.num_process,
tasks_json_path=args.tasks_json_path,
dataset_root=args.dataset_root,
filter_action_types=filter_action_types,
final_dataset_repo_root=args.final_dataset_repo_root
)