CyberDJ commited on
Commit
f83b064
·
verified ·
1 Parent(s): 562e744

Upload scripts/convert_mcap_to_lerobot.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/convert_mcap_to_lerobot.py +1361 -0
scripts/convert_mcap_to_lerobot.py ADDED
@@ -0,0 +1,1361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert mcap files to lerobot format within a single file.
3
+ Supports Human-in-the-Loop (HIL) data filtering by action_type.
4
+
5
+ Example Usage:
6
+ Notice:
7
+ if use multiprocessing, please make sure the repo id is a temperary repo (e.g., we_d900_temp/accessory-return)
8
+ to avoid multiple processes pushing to the same repo at the same time. After the conversion is done,
9
+ you can rename the repo to the final name (e.g., we_d900/accessory-return).
10
+
11
+ 1. Normal teleoperation data processing
12
+ -> Without HIL filtering (keep all actions):
13
+
14
+ python posttraining/scripts/dataset/convert_mcap_to_lerobot.py \
15
+ --task 'accessory-return' \
16
+ --num_process 40 \
17
+ --robot_type arx \
18
+ --repo_id we_d900_temp/accessory-return \
19
+ --final_dataset_repo_root we_d900 \
20
+ --tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
21
+ --dataset_root /nas/volume1/scratch/datasets \
22
+
23
+ 2. Generate human-in-the-loop (HIL) data with filtering:
24
+ python posttraining/scripts/dataset/convert_mcap_to_lerobot.py \
25
+ --task 'accessory-return' \
26
+ --num_process 40 \
27
+ --robot_type arx \
28
+ --repo_id we_d900_temp/accessory-return \
29
+ --final_dataset_repo_root we_d900 \
30
+ --tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
31
+ --dataset_root /nas/volume1/scratch/datasets \
32
+ --hil_filter
33
+
34
+ 3. With custom action types, e.g. only keep "teleop":
35
+ python posttraining/scripts/dataset/convert_mcap_to_lerobot.py
36
+ --task 'accessory-return' \
37
+ --num_process 40 \
38
+ --robot_type arx \
39
+ --repo_id we_d900_temp/accessory-return \
40
+ --final_dataset_repo_root we_d900 \
41
+ --tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
42
+ --dataset_root /nas/volume1/scratch/datasets \
43
+ --action_types ["teleop"]
44
+
45
+
46
+ """
47
+
48
+ from pathlib import Path
49
+ import gc
50
+ import os
51
+ import cv2
52
+ import tqdm
53
+ import json
54
+ import subprocess
55
+ import numpy as np
56
+ import logging
57
+ import shutil
58
+ import pandas as pd
59
+ from typing import Literal
60
+ from mcap.reader import make_reader
61
+ from lerobot.utils.constants import HF_LEROBOT_HOME
62
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
63
+ from typing import Iterable
64
+ from foxglove_schemas_protobuf.CompressedImage_pb2 import CompressedImage
65
+ from foxglove_schemas_protobuf.FrameTransforms_pb2 import FrameTransforms
66
+ from packaging import version
67
+ from concurrent.futures import ProcessPoolExecutor
68
+ from lerobot.datasets.utils import load_tasks
69
+ import pyarrow as pa
70
+ import pyarrow.parquet as pq
71
+ import dataclasses
72
+ import argparse
73
+
74
+ logger = logging.getLogger()
75
+
76
+ DATASET_ROOT = "/nas/volume1/scratch/datasets"
77
+ TASKS_JSON_PATH = "/home/shiduozhang/projects/tasks_hil.json"
78
+
79
+ # Default commander_state values to keep for HIL data
80
+ DEFAULT_HIL_ACTION_TYPES = {"INFERENCE", "TELEOP"}
81
+
82
+
83
+ def load_task_folders(task_name: str, tasks_json_path: str = TASKS_JSON_PATH) -> list[str]:
84
+ """
85
+ Load folder names for a specific task from tasks_merged.json.
86
+
87
+ Args:
88
+ task_name: The task name to look up
89
+ tasks_json_path: Path to the tasks_merged.json file
90
+
91
+ Returns:
92
+ List of folder names for the task
93
+ """
94
+ import json
95
+ with open(tasks_json_path, "r", encoding="utf-8") as f:
96
+ tasks = json.load(f)
97
+
98
+ if task_name not in tasks:
99
+ available_tasks = list(tasks.keys())
100
+ raise ValueError(f"Task '{task_name}' not found. Available tasks: {available_tasks}")
101
+
102
+ return tasks[task_name]
103
+
104
+
105
+ def get_mcap_info_from_folder(folder_path: str) -> tuple[str | None, str]:
106
+ """
107
+ Get mcap file path and version from a folder.
108
+
109
+ Args:
110
+ folder_path: Path to the folder containing mcap and metadata.json
111
+
112
+ Returns:
113
+ Tuple of (mcap_file_path, mcap_version)
114
+ """
115
+ import json
116
+ from glob import glob
117
+
118
+ # Find mcap file (recursively)
119
+ mcap_files = glob(os.path.join(folder_path, "**/*.mcap"), recursive=True)
120
+ if not mcap_files:
121
+ # Fallback to non-recursive search
122
+ mcap_files = glob(os.path.join(folder_path, "*.mcap"))
123
+ if not mcap_files:
124
+ logger.warning(f"No mcap file found in {folder_path}")
125
+ return None, "1.12.7" # Default version
126
+
127
+ mcap_path = mcap_files[0]
128
+
129
+ # Read metadata.json for version
130
+ metadata_path = os.path.join(folder_path, "metadata.json")
131
+ mcap_version = "1.12.7" # Default version
132
+ if os.path.exists(metadata_path):
133
+ try:
134
+ with open(metadata_path, "r", encoding="utf-8") as f:
135
+ metadata = json.load(f)
136
+ mcap_version = metadata.get("version", metadata.get("mcap_version", "1.12.7"))
137
+ except Exception as e:
138
+ logger.warning(f"Error reading metadata from {metadata_path}: {e}")
139
+
140
+ return mcap_path, mcap_version
141
+
142
+ ############################################# Protobuf Types #############################################
143
+ # -*- coding: utf-8 -*-
144
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
145
+ # NO CHECKED-IN PROTOBUF GENCODE
146
+ # source: robotics.proto
147
+ # Protobuf Python Version: 5.29.4
148
+ """Generated protocol buffer code."""
149
+ from google.protobuf import descriptor as _descriptor
150
+ from google.protobuf import descriptor_pool as _descriptor_pool
151
+ from google.protobuf import symbol_database as _symbol_database
152
+ from google.protobuf.internal import builder as _builder
153
+
154
+ # @@protoc_insertion_point(imports)
155
+
156
+ _sym_db = _symbol_database.Default()
157
+
158
+
159
+ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
160
+
161
+
162
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
163
+ 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'
164
+ )
165
+
166
+ _globals = globals()
167
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
168
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "robotics_pb2", _globals)
169
+ if not _descriptor._USE_C_DESCRIPTORS:
170
+ DESCRIPTOR._loaded_options = None
171
+ _globals["_ROBOTOBSERVATION"]._serialized_start = 66
172
+ _globals["_ROBOTOBSERVATION"]._serialized_end = 258
173
+ _globals["_ROBOTACTION"]._serialized_start = 260
174
+ _globals["_ROBOTACTION"]._serialized_end = 336
175
+ _globals["_SYNCTIMESTAMPS"]._serialized_start = 339
176
+ _globals["_SYNCTIMESTAMPS"]._serialized_end = 657
177
+ # @@protoc_insertion_point(module_scope)
178
+
179
+
180
+ ############################################# Dataset Config #############################################
181
+ @dataclasses.dataclass(frozen=True)
182
+ class DatasetConfig:
183
+ use_videos: bool = True
184
+ tolerance_s: float = 0.0001
185
+ image_writer_processes: int = 10
186
+ image_writer_threads: int = 5
187
+ video_backend: str | None = None
188
+
189
+
190
+ DEFAULT_DATASET_CONFIG = DatasetConfig()
191
+
192
+
193
+ ############################################# Robot Config #############################################
194
+ @dataclasses.dataclass(frozen=True)
195
+ class DualArmConfig:
196
+ robot_type: str = "piper"
197
+ left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])
198
+ right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])
199
+ arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: []) # Exclude gripper
200
+ motors: list[str] = dataclasses.field(default_factory=lambda: [])
201
+ camera_keys: list[str] = dataclasses.field(default_factory=lambda: [])
202
+ cam_key_maps: dict[str, str] = dataclasses.field(default_factory=lambda: {})
203
+
204
+
205
+ @dataclasses.dataclass(frozen=True)
206
+ class DualPiperConfig(DualArmConfig):
207
+ robot_type: str = "piper"
208
+ left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 6])
209
+ right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [7, 8, 9, 10, 11, 12, 13])
210
+ arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]) # Exclude gripper
211
+ motors: list[str] = dataclasses.field(
212
+ default_factory=lambda: [
213
+ "left_waist",
214
+ "left_shoulder",
215
+ "left_elbow",
216
+ "left_forearm_roll",
217
+ "left_wrist_angle",
218
+ "left_wrist_rotate",
219
+ "left_gripper",
220
+ "right_waist",
221
+ "right_shoulder",
222
+ "right_elbow",
223
+ "right_forearm_roll",
224
+ "right_wrist_angle",
225
+ "right_wrist_rotate",
226
+ "right_gripper",
227
+ ]
228
+ )
229
+ camera_keys: list[str] = dataclasses.field(
230
+ default_factory=lambda: [
231
+ "left_camera",
232
+ "right_camera",
233
+ "top_camera",
234
+ ]
235
+ )
236
+ cam_key_maps: dict[str, str] = dataclasses.field(
237
+ default_factory=lambda: {
238
+ "left_camera": "cam_left_wrist",
239
+ "right_camera": "cam_right_wrist",
240
+ "top_camera": "cam_high",
241
+ }
242
+ )
243
+
244
+
245
+ @dataclasses.dataclass(frozen=True)
246
+ class DualArxConfig(DualArmConfig):
247
+ robot_type: str = "arx"
248
+ left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 6])
249
+ right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [7, 8, 9, 10, 11, 12, 13])
250
+ arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]) # Exclude gripper
251
+ motors: list[str] = dataclasses.field(
252
+ default_factory=lambda: [
253
+ "left_waist",
254
+ "left_shoulder",
255
+ "left_elbow",
256
+ "left_forearm_roll",
257
+ "left_wrist_angle",
258
+ "left_wrist_rotate",
259
+ "left_gripper",
260
+ "right_waist",
261
+ "right_shoulder",
262
+ "right_elbow",
263
+ "right_forearm_roll",
264
+ "right_wrist_angle",
265
+ "right_wrist_rotate",
266
+ "right_gripper",
267
+ ]
268
+ )
269
+ camera_keys: list[str] = dataclasses.field(
270
+ default_factory=lambda: [
271
+ "left_camera",
272
+ "right_camera",
273
+ "top_camera",
274
+ ]
275
+ )
276
+ cam_key_maps: dict[str, str] = dataclasses.field(
277
+ default_factory=lambda: {
278
+ "left_camera": "cam_left_wrist",
279
+ "right_camera": "cam_right_wrist",
280
+ "top_camera": "cam_high",
281
+ }
282
+ )
283
+
284
+
285
+ ############################################# LeRobot Utils #############################################
286
+ def create_empty_dataset(
287
+ repo_id: str,
288
+ robot_type: str,
289
+ mode: Literal["video", "image"] = "video",
290
+ *,
291
+ dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
292
+ fps=60,
293
+ image_size: tuple[int, int] = (320, 180),
294
+ cam_key_maps: dict[str, str] = {},
295
+ motors: list[str] = [],
296
+ generate_vel: bool = False,
297
+ record_mcap_path: bool = False,
298
+ ) -> LeRobotDataset:
299
+ """Create an empty LeRobot dataset."""
300
+ cameras = list(cam_key_maps.values())
301
+
302
+ features = {
303
+ "observation.state": {
304
+ "dtype": "float32",
305
+ "shape": (len(motors),),
306
+ "names": motors,
307
+ },
308
+ "observation.commander_state": {
309
+ "dtype": "string",
310
+ "shape": (1,),
311
+ "names": ["commander_states"],
312
+ },
313
+ "action": {
314
+ "dtype": "float32",
315
+ "shape": (len(motors),),
316
+ "names": motors,
317
+ },
318
+ }
319
+ if record_mcap_path:
320
+ features["mcap_path"] = {
321
+ "dtype": "string",
322
+ "shape": (1,),
323
+ "names": ["mcap_path"],
324
+ }
325
+ if generate_vel:
326
+ features["observation.velocity"] = {
327
+ "dtype": "float32",
328
+ "shape": (len(motors),),
329
+ "names": motors,
330
+ }
331
+ features["action_vel"] = {
332
+ "dtype": "float32",
333
+ "shape": (len(motors),),
334
+ "names": motors,
335
+ }
336
+
337
+ for cam in cameras:
338
+ features[f"observation.images.{cam}"] = {
339
+ "dtype": mode,
340
+ "shape": (image_size[1], image_size[0], 3),
341
+ "names": [
342
+ "height",
343
+ "width",
344
+ "channels",
345
+ ],
346
+ }
347
+ features["subtask"] = {
348
+ "dtype": "string",
349
+ "shape": (1,),
350
+ "names": ["subtask"],
351
+ }
352
+
353
+ if Path(HF_LEROBOT_HOME / repo_id).exists():
354
+ shutil.rmtree(HF_LEROBOT_HOME / repo_id)
355
+
356
+ dataset = LeRobotDataset.create(
357
+ repo_id=repo_id,
358
+ fps=fps,
359
+ robot_type=robot_type,
360
+ features=features,
361
+ use_videos=dataset_config.use_videos,
362
+ tolerance_s=dataset_config.tolerance_s,
363
+ image_writer_processes=dataset_config.image_writer_processes,
364
+ image_writer_threads=dataset_config.image_writer_threads,
365
+ video_backend=dataset_config.video_backend,
366
+ )
367
+ dataset.meta.update_chunk_settings(data_files_size_in_mb=0, video_files_size_in_mb=0)
368
+ return dataset
369
+
370
+ def check_mcap_validity(data_dict_chunk: dict, action_threshold: float = 10.0) -> bool:
371
+ actions_raw = data_dict_chunk["actions"]
372
+ if np.max(np.abs(actions_raw)) > action_threshold:
373
+ mcap_info = data_dict_chunk.get("mcap_path", "unknown")
374
+ logger.warning(
375
+ f"Skipping mcap file {mcap_info}: max abs actions value "
376
+ f"{np.max(np.abs(actions_raw)):.4f} exceeds {action_threshold}"
377
+ )
378
+ return True
379
+ return False
380
+
381
+ def populate_dataset_from_raw_loader(
382
+ dataset: LeRobotDataset,
383
+ raw_episode_loader: Iterable[dict],
384
+ cam_keys: list[str],
385
+ cam_key_maps: dict[str, str],
386
+ task: str | list[str] = "Do something",
387
+ generate_vel: bool = False,
388
+ chunk_size: int = 1000,
389
+ record_mcap_path: bool = False,
390
+ ):
391
+ """Populate a LeRobot dataset from a raw data loader."""
392
+ pbar = tqdm.tqdm(total=len(raw_episode_loader))
393
+ skip_current_episode = False
394
+ is_first_chunk_of_episode = True # Track first chunk to avoid orphaned frames
395
+ for is_new_episode, data_dict_chunk in raw_episode_loader:
396
+ if is_new_episode:
397
+ # Update the episode index
398
+ if not skip_current_episode:
399
+ dataset.save_episode()
400
+ pbar.update(1)
401
+ skip_current_episode = False # Reset for new episode
402
+ is_first_chunk_of_episode = True # New episode starts
403
+
404
+ # Only check validity on the FIRST chunk of each episode.
405
+ # Checking on later chunks is unsafe: frames from earlier chunks are already
406
+ # in the LeRobot buffer and cannot be undone, so setting skip_current_episode=True
407
+ # mid-episode leaves orphan frames that corrupt the next episode.
408
+ if is_first_chunk_of_episode:
409
+ skip_current_episode = check_mcap_validity(data_dict_chunk)
410
+ is_first_chunk_of_episode = False
411
+
412
+ if skip_current_episode:
413
+ continue
414
+
415
+ num_frames_chunk = len(data_dict_chunk["joint_poses"])
416
+ camera_images = {key: data_dict_chunk["camera_images"][key] for key in cam_keys}
417
+
418
+ valid_frames = list(range(num_frames_chunk))
419
+ joint_poses = data_dict_chunk["joint_poses"][valid_frames]
420
+ ee_poses = data_dict_chunk["ee_poses"][valid_frames]
421
+ if "commander_states" in data_dict_chunk:
422
+ commander_states = [data_dict_chunk["commander_states"][i].lower() for i in valid_frames]
423
+ else:
424
+ commander_states = ["teleop"] * len(valid_frames)
425
+ actions = data_dict_chunk["actions"][valid_frames]
426
+ if generate_vel:
427
+ joint_vel = data_dict_chunk["joint_vel"][valid_frames]
428
+ actions_vel = data_dict_chunk["actions_vel"][valid_frames]
429
+ for cam_key in cam_keys:
430
+ camera_images[cam_key] = data_dict_chunk["camera_images"][cam_key][valid_frames]
431
+ num_frames_chunk = len(joint_poses)
432
+
433
+ # Get mcap_path if recording
434
+ mcap_path = data_dict_chunk.get("mcap_path", "") if record_mcap_path else None
435
+
436
+ if "task" in data_dict_chunk:
437
+ task_episode = data_dict_chunk["task"]
438
+ elif task is None:
439
+ task_episode = "Do something"
440
+ else:
441
+ task_episode = task
442
+
443
+ for frame_idx in range(num_frames_chunk):
444
+ # FIXME: Allow the episode to change task within the episode
445
+ frame = {
446
+ "task": task_episode[frame_idx] if isinstance(task_episode, list) else task_episode,
447
+ "observation.state": joint_poses[frame_idx],
448
+ "action": actions[frame_idx],
449
+ }
450
+ if generate_vel:
451
+ frame["observation.velocity"] = joint_vel[frame_idx]
452
+ frame["action_vel"] = actions_vel[frame_idx]
453
+ frame["observation.commander_state"] = commander_states[frame_idx]
454
+ if record_mcap_path and mcap_path:
455
+ frame["mcap_path"] = mcap_path
456
+ for cam_key in cam_keys:
457
+ frame[f"observation.images.{cam_key_maps[cam_key]}"] = camera_images[cam_key][frame_idx]
458
+ frame["subtask"] = "TODO" # TODO: add subtask annotation
459
+ dataset.add_frame(frame)
460
+ # Save the last episode
461
+ if not skip_current_episode:
462
+ dataset.save_episode()
463
+ pbar.update(1)
464
+ pbar.close()
465
+
466
+
467
+ ############################################# Utils #############################################
468
+ def resize_image(img_str, resize=True, image_size: tuple[int, int] = (320, 180)):
469
+ # Handle case where input is already bytes
470
+ if isinstance(img_str, bytes):
471
+ img_bytes = img_str
472
+ else:
473
+ # Original code for hex string
474
+ img_bytes = bytes.fromhex(img_str)
475
+
476
+ img_np = np.frombuffer(img_bytes, dtype=np.uint8)
477
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
478
+ if resize:
479
+ img = cv2.resize(img, (image_size[0], image_size[1]))
480
+ # Convert rgb to bgr
481
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
482
+ return img
483
+
484
+
485
+ ############################################# Load raw data from mcap #############################################
486
+
487
+
488
+ def read_mcap_msg(mcap_path, cam_keys: list[str]):
489
+ """
490
+ Read messages from an MCAP file.
491
+
492
+ Args:
493
+ mcap_path: Path to the MCAP file
494
+ """
495
+ # Verify file exists
496
+ if not os.path.exists(mcap_path):
497
+ raise FileNotFoundError(f"MCAP file not found at {mcap_path}")
498
+
499
+ # Dictionary to store message type handlers
500
+ handlers = {
501
+ "robot_observation": RobotObservation,
502
+ "robot_action": RobotAction,
503
+ "sync_timestamps": SyncTimestamps,
504
+ "/tf": FrameTransforms,
505
+ }
506
+ for cam_key in cam_keys:
507
+ handlers[cam_key] = CompressedImage
508
+
509
+ # Statistics to track message counts
510
+ message_counts = {topic: 0 for topic in handlers.keys()}
511
+ messages = []
512
+
513
+ # Open and read the MCAP file
514
+ with open(mcap_path, "rb") as f:
515
+ reader = make_reader(f)
516
+
517
+ # Iterate through all messages
518
+ for schema, channel, message in reader.iter_messages():
519
+ # Get the appropriate message handler
520
+ if channel.topic in handlers:
521
+ message_type = handlers[channel.topic]
522
+ parsed_msg = message_type()
523
+ parsed_msg.ParseFromString(message.data)
524
+
525
+ # Update message count
526
+ message_counts[channel.topic] += 1
527
+ # Read out data based topic
528
+ if channel.topic == "robot_observation":
529
+ data = {
530
+ "joint_positions": parsed_msg.joint_positions,
531
+ "joint_velocities": parsed_msg.joint_velocities,
532
+ "ee_pose": parsed_msg.ee_pos,
533
+ "currents": parsed_msg.currents,
534
+ "torques": parsed_msg.torques,
535
+ "commander_state": parsed_msg.commander_state,
536
+ }
537
+ timestamp = parsed_msg.timestamp.ToNanoseconds()
538
+ elif channel.topic == "robot_action":
539
+ data = parsed_msg.action
540
+ timestamp = parsed_msg.timestamp.ToNanoseconds()
541
+ elif channel.topic == "sync_timestamps":
542
+ data = {
543
+ f"{k}_timestamp": parsed_msg.__getattribute__(f"{k}_timestamp").ToNanoseconds()
544
+ for k in handlers.keys()
545
+ if hasattr(parsed_msg, f"{k}_timestamp")
546
+ }
547
+ timestamp = min(data.values())
548
+ elif channel.topic in cam_keys:
549
+ data = parsed_msg.data
550
+ timestamp = parsed_msg.timestamp.ToNanoseconds()
551
+ elif channel.topic == "tf":
552
+ data = parsed_msg.data
553
+ timestamp = parsed_msg.timestamp.ToNanoseconds()
554
+ messages.append(
555
+ {
556
+ "timestamp": timestamp,
557
+ "data": data,
558
+ "channel": channel.topic,
559
+ "schema": schema,
560
+ }
561
+ )
562
+ return messages
563
+
564
+
565
+ def read_mcap_file(file_path, cam_keys: list[str]):
566
+ """
567
+ Read messages from an MCAP file
568
+ """
569
+ messages = read_mcap_msg(file_path, cam_keys=cam_keys)
570
+
571
+ robot_joint_pos = {}
572
+ robot_action = {}
573
+ robo_ee_pose = {}
574
+ commander_state = {}
575
+ camera_images = {key: {} for key in cam_keys}
576
+ sync_timestamps = {}
577
+
578
+ for message in messages:
579
+ data = message["data"]
580
+
581
+ if message["channel"] == "robot_observation":
582
+ robot_joint_pos[message["timestamp"]] = data["joint_positions"]
583
+ commander_state[message["timestamp"]] = data["commander_state"]
584
+ robo_ee_pose[message["timestamp"]] = data["ee_pose"]
585
+ elif message["channel"] == "robot_action":
586
+ robot_action[message["timestamp"]] = data
587
+ elif message["channel"] in cam_keys:
588
+ camera_images[message["channel"]][message["timestamp"]] = data
589
+ elif message["channel"] == "sync_timestamps":
590
+ sync_timestamps[message["timestamp"]] = data
591
+
592
+ return {
593
+ "robot_joint_pos": robot_joint_pos,
594
+ "robot_action": robot_action,
595
+ "robo_ee_pose": robo_ee_pose,
596
+ "commander_state": commander_state,
597
+ "camera_images": camera_images,
598
+ "sync_timestamps": sync_timestamps,
599
+ }
600
+
601
+
602
+ def load_timed_data_from_mcap(
603
+ mcap_file: str,
604
+ cam_keys,
605
+ fps=60,
606
+ start_frame=0,
607
+ max_frame=None,
608
+ resize=True,
609
+ image_size: tuple[int, int] = (320, 180),
610
+ mcap_version: str = "0.0.0",
611
+ generate_vel: bool = False,
612
+ chunk_size: int = 1000, # Process data in chunks to reduce memory pressure
613
+ robot_type: str = "piper",
614
+ filter_action_types: set[str] | None = None, # HIL: action types to keep
615
+ ):
616
+ """Load the timed data from mcap with a given fps.
617
+
618
+ Args:
619
+ mcap_file: Path to the MCAP file
620
+ cam_keys: List of camera keys
621
+ fps: Frames per second
622
+ start_frame: Starting frame index
623
+ max_frame: Maximum number of frames to process
624
+ resize: Whether to resize images
625
+ image_size: Target image size (width, height)
626
+ mcap_version: MCAP version string
627
+ generate_vel: Whether to generate velocity data
628
+ chunk_size: Process data in chunks
629
+ robot_type: Type of robot
630
+ filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
631
+ If None, all actions are kept.
632
+ """
633
+ # Read MCAP file
634
+ mcap_dict = read_mcap_file(mcap_file, cam_keys=cam_keys)
635
+ ds_sync_timestamps = mcap_dict["sync_timestamps"]
636
+
637
+ # If there are no explicit sync_timestamps in the MCAP, build a fallback
638
+ # nearest-neighbor synchronization using robot_observation timestamps as the
639
+ # reference timeline and matching camera & action timestamps to the closest
640
+ # available times. This keeps behavior robust when recordings don't emit
641
+ # a dedicated sync message.
642
+ if not ds_sync_timestamps:
643
+ logger.info("No sync_timestamps found in MCAP; building fallback nearest-neighbor sync using camera as reference")
644
+ from bisect import bisect_left
645
+
646
+ def nearest(sorted_list, value):
647
+ if not sorted_list:
648
+ return None
649
+ i = bisect_left(sorted_list, value)
650
+ if i == 0:
651
+ return sorted_list[0]
652
+ if i == len(sorted_list):
653
+ return sorted_list[-1]
654
+ before = sorted_list[i - 1]
655
+ after = sorted_list[i]
656
+ if abs(after - value) < abs(value - before):
657
+ return after
658
+ else:
659
+ return before
660
+
661
+ # tolerance for matching (seconds -> nanoseconds).
662
+ fallback_tol_s = max(DEFAULT_DATASET_CONFIG.tolerance_s, 1.0 / fps / 2.0)
663
+ tol_ns = int(fallback_tol_s * 1e9)
664
+
665
+ # prepare sorted timestamp lists
666
+ obs_ts = sorted(mcap_dict["robot_joint_pos"].keys())
667
+ action_ts = sorted(mcap_dict["robot_action"].keys())
668
+ cam_ts_map = {k: sorted(mcap_dict["camera_images"][k].keys()) for k in cam_keys}
669
+
670
+ # Use the first camera as the reference timeline
671
+ reference_cam_key = cam_keys[0]
672
+ reference_cam_ts = cam_ts_map.get(reference_cam_key, [])
673
+
674
+ if not reference_cam_ts:
675
+ logger.warning(f"Reference camera {reference_cam_key} has no timestamps")
676
+ ds_sync_timestamps = {}
677
+ else:
678
+ ds_sync_timestamps = {}
679
+ for cam_t in reference_cam_ts:
680
+ sync = {}
681
+ sync[f"{reference_cam_key}_timestamp"] = cam_t
682
+
683
+ # nearest robot observation
684
+ no = nearest(obs_ts, cam_t)
685
+ if no is None or abs(no - cam_t) > tol_ns:
686
+ continue
687
+ sync["robot_observation_timestamp"] = no
688
+
689
+ # nearest action
690
+ na = nearest(action_ts, cam_t)
691
+ if na is None or abs(na - cam_t) > tol_ns:
692
+ continue
693
+ sync["robot_action_timestamp"] = na
694
+
695
+ # nearest timestamps for other cameras
696
+ skip = False
697
+ for cam_key in cam_keys:
698
+ if cam_key == reference_cam_key:
699
+ continue # already added
700
+ nc = nearest(cam_ts_map.get(cam_key, []), cam_t)
701
+ if nc is None or abs(nc - cam_t) > tol_ns:
702
+ # If camera is missing or too far from reference camera, skip this frame
703
+ skip = True
704
+ break
705
+ sync[f"{cam_key}_timestamp"] = nc
706
+
707
+ if skip:
708
+ continue
709
+
710
+ # use reference camera timestamp as the dict key for ordering
711
+ ds_sync_timestamps[cam_t] = sync
712
+ # Pre-allocate arrays for the current chunk
713
+ chunk_joint_poses = []
714
+ chunk_ee_poses = []
715
+ chunk_commander_states = []
716
+ chunk_actions = []
717
+ chunk_camera_images = {key: [] for key in cam_keys}
718
+
719
+ episode_length = 0
720
+ has_zero_ts = False
721
+ has_missing_ts = False
722
+ filtered_count = 0 # Count of frames filtered by action_type
723
+
724
+ # Process timestamps in sorted order
725
+ sorted_timestamps = sorted(ds_sync_timestamps.keys())
726
+ total_frames = len(sorted_timestamps)
727
+
728
+ for idx, key in enumerate(sorted_timestamps):
729
+ if idx < start_frame:
730
+ continue
731
+ if max_frame is not None and idx >= (start_frame + max_frame):
732
+ break
733
+
734
+ sync_ts = ds_sync_timestamps[key]
735
+
736
+ # Skip if any camera timestamp is None or 0
737
+ is_zero_ts = False
738
+ for cam_key in cam_keys:
739
+ if sync_ts[f"{cam_key}_timestamp"] is None or sync_ts[f"{cam_key}_timestamp"] == 0:
740
+ is_zero_ts = True
741
+ break
742
+ if is_zero_ts:
743
+ has_zero_ts = True
744
+ continue
745
+
746
+ # Check existence of sync_ts in all camera_images
747
+ is_missing_ts = False
748
+ for cam_key in cam_keys:
749
+ if sync_ts[f"{cam_key}_timestamp"] not in mcap_dict["camera_images"][cam_key]:
750
+ logger.warning(f"Sync timestamp {sync_ts[f'{cam_key}_timestamp']} not found in {cam_key} camera images, mcap file: {mcap_file}")
751
+ is_missing_ts = True
752
+ break
753
+ if is_missing_ts:
754
+ has_missing_ts = True
755
+ continue
756
+
757
+ # HIL Filtering: Check commander_state and skip if not in filter set
758
+ if filter_action_types is not None:
759
+ obs_ts = sync_ts["robot_observation_timestamp"]
760
+ cmd_state = mcap_dict["commander_state"].get(obs_ts, "")
761
+ if cmd_state not in filter_action_types:
762
+ filtered_count += 1
763
+ continue
764
+
765
+ episode_length += 1
766
+
767
+ # Process current frame
768
+ joint_pos = np.array(mcap_dict["robot_joint_pos"][sync_ts["robot_observation_timestamp"]]).reshape(1, -1)
769
+ ee_pos = np.array(mcap_dict["robo_ee_pose"][sync_ts["robot_observation_timestamp"]]).reshape(1, -1)
770
+ commander_state = mcap_dict["commander_state"][sync_ts["robot_observation_timestamp"]]
771
+ if filter_action_types is not None:
772
+ commander_state = "ap_" + commander_state.lower() # Prefix with "ap_" to indicate it's autopilot state (e.g., "ap_inference", "ap_teleop")
773
+ action = np.array(mcap_dict["robot_action"][sync_ts["robot_action_timestamp"]]).reshape(1, -1)
774
+
775
+ # Append to current chunk
776
+ chunk_joint_poses.append(joint_pos)
777
+ chunk_ee_poses.append(ee_pos)
778
+ chunk_commander_states.append(commander_state)
779
+ chunk_actions.append(action)
780
+
781
+ # Process images
782
+ for cam_key in cam_keys:
783
+ img_data = mcap_dict["camera_images"][cam_key][sync_ts[f"{cam_key}_timestamp"]]
784
+ img = resize_image(img_data, resize=resize, image_size=image_size)
785
+ chunk_camera_images[cam_key].append(img)
786
+
787
+ # Process chunk if it reaches the specified size or we're at the end
788
+ if len(chunk_joint_poses) >= chunk_size or idx == total_frames - 1:
789
+ # Skip if no data in chunk (all frames were filtered)
790
+ if len(chunk_joint_poses) == 0:
791
+ continue
792
+
793
+ # Convert lists to numpy arrays
794
+ joint_poses_chunk = np.concatenate(chunk_joint_poses, axis=0).astype(np.float32)
795
+ ee_poses_chunk = np.concatenate(chunk_ee_poses, axis=0).astype(np.float32)
796
+ actions_chunk = np.concatenate(chunk_actions, axis=0).astype(np.float32)
797
+
798
+ # Version-aware action normalization
799
+ if version.parse(mcap_version) <= version.parse("1.10.1"):
800
+ actions_chunk[:, 6] = actions_chunk[:, 6] / 0.08
801
+ actions_chunk[:, 13] = actions_chunk[:, 13] / 0.08
802
+ # if robot_type == "arx" and version.parse(mcap_version) <= version.parse("1.12.7"):
803
+ # actions_chunk[:, 6] = actions_chunk[:, 6] * 0.08
804
+ # actions_chunk[:, 13] = actions_chunk[:, 13] * 0.08
805
+
806
+ # Process camera images
807
+ camera_images_chunk = {}
808
+ for cam_key in cam_keys:
809
+ camera_images_chunk[cam_key] = np.stack(chunk_camera_images[cam_key], axis=0).astype(np.uint8)
810
+
811
+ # Generate velocities if requested
812
+ if generate_vel:
813
+ joint_vel_chunk = np.diff(joint_poses_chunk, axis=0)
814
+ joint_vel_chunk = np.concatenate([joint_vel_chunk, np.zeros((1, joint_vel_chunk.shape[1]))], axis=0).astype(np.float32)
815
+ actions_vel_chunk = np.diff(actions_chunk, axis=0)
816
+ actions_vel_chunk = np.concatenate([actions_vel_chunk, np.zeros((1, actions_vel_chunk.shape[1]))], axis=0).astype(np.float32)
817
+
818
+ # Yield the current chunk
819
+ chunk_data = {
820
+ "joint_poses": joint_poses_chunk,
821
+ "ee_poses": ee_poses_chunk,
822
+ "commander_states": chunk_commander_states,
823
+ "actions": actions_chunk,
824
+ "camera_images": camera_images_chunk,
825
+ "info": {
826
+ "has_zero_ts": has_zero_ts,
827
+ "has_missing_ts": has_missing_ts,
828
+ "filtered_count": filtered_count, # Include filtered count in info
829
+ },
830
+ }
831
+
832
+ if generate_vel:
833
+ chunk_data["joint_vel"] = joint_vel_chunk
834
+ chunk_data["actions_vel"] = actions_vel_chunk
835
+
836
+ yield chunk_data
837
+
838
+ # Clear chunk data
839
+ chunk_joint_poses = []
840
+ chunk_ee_poses = []
841
+ chunk_commander_states = []
842
+ chunk_actions = []
843
+ chunk_camera_images = {key: [] for key in cam_keys}
844
+
845
+ # Force garbage collection
846
+ gc.collect()
847
+
848
+ # Log filtering statistics
849
+ if filter_action_types is not None and filtered_count > 0:
850
+ logger.info(f"HIL filtering: {filtered_count} frames filtered out (kept action_types: {filter_action_types})")
851
+
852
+
853
+ ############################################# Generate LeRobot Dataset #############################################
854
+ class McapDataLoader:
855
+ """
856
+ Load data from mcap files and convert to LeRobot format.
857
+ McapDataLoader load mcap in chunks to reduce memory pressure.
858
+ """
859
+
860
+ def __init__(
861
+ self,
862
+ mcap_files: list[str],
863
+ mcap_versions: list[str],
864
+ cam_keys: list[str],
865
+ image_size: tuple[int, int],
866
+ generate_vel: bool = False,
867
+ chunk_size: int = 1000,
868
+ robot_type: str = "piper",
869
+ record_mcap_path: bool = False,
870
+ filter_action_types: set[str] | None = None, # HIL: action types to keep
871
+ ):
872
+ self.mcap_files = mcap_files
873
+ self.mcap_versions = mcap_versions
874
+ self.cam_keys = cam_keys
875
+ self.image_size = image_size
876
+ self.generate_vel = generate_vel
877
+ self.episode_idx = 0
878
+ self.chunk_size = chunk_size
879
+ self.robot_type = robot_type
880
+ self.record_mcap_path = record_mcap_path
881
+ self.filter_action_types = filter_action_types
882
+
883
+ def __len__(self):
884
+ return len(self.mcap_files)
885
+
886
+ def __iter__(self):
887
+ while self.episode_idx < len(self.mcap_files):
888
+ mcap_file = self.mcap_files[self.episode_idx]
889
+ mcap_version = self.mcap_versions[self.episode_idx]
890
+ print(f"Processing {mcap_file} with version {mcap_version}")
891
+ # Ensure the loop variable exists even if the loader yields nothing
892
+ data_dict_chunk = None
893
+ for _i, data_dict_chunk in enumerate(load_timed_data_from_mcap(
894
+ mcap_file,
895
+ cam_keys=self.cam_keys,
896
+ image_size=self.image_size,
897
+ mcap_version=mcap_version,
898
+ generate_vel=self.generate_vel,
899
+ chunk_size=self.chunk_size,
900
+ robot_type=self.robot_type,
901
+ filter_action_types=self.filter_action_types, # Pass HIL filter
902
+ )):
903
+ # Add mcap_path to chunk data if recording
904
+ if self.record_mcap_path:
905
+ data_dict_chunk["mcap_path"] = mcap_file
906
+ yield (_i == 0) and (self.episode_idx != 0), data_dict_chunk
907
+
908
+ # Clear memory (only delete if assigned)
909
+ if data_dict_chunk is not None:
910
+ del data_dict_chunk
911
+ # Collect garbage
912
+ gc.collect()
913
+ # Increment episode index
914
+ self.episode_idx += 1
915
+
916
+
917
+ def populate_dataset_from_mcap(
918
+ task: str | list[str],
919
+ dataset: LeRobotDataset,
920
+ mcap_files: list[str],
921
+ mcap_versions: list[str],
922
+ episodes: list[int] | None = None,
923
+ image_size: tuple[int, int] = (320, 180),
924
+ cam_keys: list[str] = ["top_camera", "left_camera", "right_camera"],
925
+ cam_key_maps: dict[str, str] = {
926
+ "top_camera": "cam_high",
927
+ "left_camera": "cam_left_wrist",
928
+ "right_camera": "cam_right_wrist",
929
+ },
930
+ arm_joint_idx: list[int] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12],
931
+ generate_vel: bool = False,
932
+ chunk_size: int = 1000,
933
+ robot_type: str = "piper",
934
+ record_mcap_path: bool = False,
935
+ filter_action_types: set[str] | None = None, # HIL: action types to keep
936
+ ) -> LeRobotDataset:
937
+ """
938
+ Populate the dataset with the raw data from the mcap files.
939
+ Args:
940
+ dataset: The dataset to populate.
941
+ mcap_files: The list of mcap files to populate the dataset with.
942
+ mcap_versions: The list of mcap versions corresponding to the mcap files.
943
+ episodes: The list of episodes to populate the dataset with.
944
+ image_size: The size of the images to resize to.
945
+ generate_vel: Whether to generate velocity data.
946
+ record_mcap_path: Whether to record mcap path in the dataset.
947
+ filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
948
+ """
949
+ if episodes is None:
950
+ episodes = range(len(mcap_files))
951
+
952
+ mcap_data_loader = McapDataLoader(
953
+ mcap_files=mcap_files,
954
+ mcap_versions=mcap_versions,
955
+ cam_keys=cam_keys,
956
+ image_size=image_size,
957
+ generate_vel=generate_vel,
958
+ chunk_size=chunk_size,
959
+ robot_type=robot_type,
960
+ record_mcap_path=record_mcap_path,
961
+ filter_action_types=filter_action_types, # Pass HIL filter
962
+ )
963
+ populate_dataset_from_raw_loader(
964
+ dataset=dataset,
965
+ raw_episode_loader=mcap_data_loader,
966
+ cam_keys=cam_keys,
967
+ cam_key_maps=cam_key_maps,
968
+ task=task,
969
+ generate_vel=generate_vel,
970
+ chunk_size=chunk_size,
971
+ record_mcap_path=record_mcap_path,
972
+ )
973
+
974
+
975
+ def convert_mcap_to_lerobot(
976
+ repo_id: str,
977
+ task: str,
978
+ mcap_files: list[str],
979
+ mcap_versions: list[str],
980
+ robot_type: str,
981
+ fps: int,
982
+ episodes: list[int] | None = None,
983
+ push_to_hub: bool = False,
984
+ mode: str = "video",
985
+ image_size: tuple[int, int] = (320, 180),
986
+ robot_config: DualPiperConfig = DualPiperConfig(),
987
+ dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
988
+ generate_vel: bool = False,
989
+ chunk_size: int = 1000,
990
+ record_mcap_path: bool = False,
991
+ filter_action_types: set[str] | None = None, # HIL: action types to keep
992
+ **kwargs
993
+ ):
994
+ if (HF_LEROBOT_HOME / repo_id).exists():
995
+ shutil.rmtree(HF_LEROBOT_HOME / repo_id)
996
+
997
+ dataset = create_empty_dataset(
998
+ repo_id,
999
+ robot_type=robot_type,
1000
+ mode=mode,
1001
+ dataset_config=dataset_config,
1002
+ fps=fps,
1003
+ image_size=image_size,
1004
+ cam_key_maps=robot_config.cam_key_maps,
1005
+ motors=robot_config.motors,
1006
+ generate_vel=generate_vel,
1007
+ record_mcap_path=record_mcap_path,
1008
+ )
1009
+
1010
+ dataset = populate_dataset_from_mcap(
1011
+ task=task,
1012
+ dataset=dataset,
1013
+ mcap_files=mcap_files,
1014
+ mcap_versions=mcap_versions,
1015
+ episodes=episodes,
1016
+ image_size=image_size,
1017
+ cam_keys=robot_config.camera_keys,
1018
+ cam_key_maps=robot_config.cam_key_maps,
1019
+ arm_joint_idx=robot_config.arm_joint_idx,
1020
+ generate_vel=generate_vel,
1021
+ chunk_size=chunk_size,
1022
+ robot_type=robot_type,
1023
+ record_mcap_path=record_mcap_path,
1024
+ filter_action_types=filter_action_types, # Pass HIL filter
1025
+ )
1026
+ if push_to_hub:
1027
+ dataset.push_to_hub()
1028
+
1029
+
1030
+ def process_worker(
1031
+ process_id: int,
1032
+ process_episodes: list[int],
1033
+ repo_id: str,
1034
+ task: str,
1035
+ mcap_files: list[str],
1036
+ mcap_versions: list[str],
1037
+ robot_type: str,
1038
+ fps: int,
1039
+ mode: str,
1040
+ image_size: tuple[int, int],
1041
+ dataset_config: DatasetConfig,
1042
+ generate_vel: bool,
1043
+ chunk_size: int,
1044
+ record_mcap_path: bool,
1045
+ filter_action_types: set[str] | None = None, # HIL: action types to keep
1046
+ ):
1047
+ temp_repo_id = f"{repo_id}_{process_id}"
1048
+
1049
+ process_mcap_files = [mcap_files[i] for i in process_episodes]
1050
+ process_mcap_versions = [mcap_versions[i] for i in process_episodes]
1051
+
1052
+ # Create and populate dataset for this process
1053
+ convert_mcap_to_lerobot(
1054
+ repo_id=temp_repo_id,
1055
+ task=task,
1056
+ mcap_files=process_mcap_files,
1057
+ mcap_versions=process_mcap_versions,
1058
+ robot_type=robot_type,
1059
+ fps=fps,
1060
+ episodes=process_episodes,
1061
+ push_to_hub=False,
1062
+ mode=mode,
1063
+ image_size=image_size,
1064
+ dataset_config=dataset_config,
1065
+ generate_vel=generate_vel,
1066
+ chunk_size=chunk_size,
1067
+ record_mcap_path=record_mcap_path,
1068
+ filter_action_types=filter_action_types, # Pass HIL filter
1069
+ )
1070
+ return temp_repo_id
1071
+
1072
+ def convert_mcap_to_lerobot_multiple_process(
1073
+ repo_id: str,
1074
+ task: str,
1075
+ mcap_files: list[str],
1076
+ mcap_versions: list[str],
1077
+ num_processes: int = 4,
1078
+ robot_type: str = "piper",
1079
+ fps: int = 60,
1080
+ episodes: list[int] | None = None,
1081
+ mode: Literal["video", "image"] = "video",
1082
+ image_size: tuple[int, int] = (320, 180),
1083
+ robot_config=DualPiperConfig(),
1084
+ dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
1085
+ generate_vel: bool = False,
1086
+ chunk_size: int = 1000,
1087
+ push_to_hub: bool = False,
1088
+ record_mcap_path: bool = False,
1089
+ filter_action_types: set[str] | None = None, # HIL: action types to keep
1090
+ ) -> list[str]:
1091
+ """
1092
+ Convert MCAP files to LeRobot format using multiple processes.
1093
+ Each process processes a subset of episodes and saves to a temporary repo.
1094
+ Returns a list of temporary repo_ids that need to be merged.
1095
+
1096
+ Args:
1097
+ repo_id: Base repo_id for the dataset
1098
+ task: Task name
1099
+ mcap_files: List of MCAP file paths
1100
+ mcap_versions: List of MCAP versions
1101
+ num_processes: Number of processes to use
1102
+ fps: Frames per second
1103
+ episodes: List of episode indices to process
1104
+ mode: Dataset mode (video or image)
1105
+ image_size: Size of images
1106
+ dataset_config: Dataset configuration
1107
+ generate_vel: Whether to generate velocity data
1108
+ filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
1109
+
1110
+ Returns:
1111
+ List of temporary repo_ids that need to be merged
1112
+ """
1113
+ if episodes is None:
1114
+ episodes = list(range(len(mcap_files)))
1115
+
1116
+ # Split episodes among processes
1117
+ episodes_per_process = len(episodes) // num_processes
1118
+ remaining_episodes = len(episodes) % num_processes
1119
+
1120
+ process_episodes = []
1121
+ start_idx = 0
1122
+ for i in range(num_processes):
1123
+ # Distribute remaining episodes among processes
1124
+ extra = 1 if i < remaining_episodes else 0
1125
+ end_idx = start_idx + episodes_per_process + extra
1126
+ process_episodes.append(episodes[start_idx:end_idx])
1127
+ start_idx = end_idx
1128
+
1129
+ temp_repo_ids = []
1130
+
1131
+ # Create and start processes using ProcessPoolExecutor
1132
+ with ProcessPoolExecutor(max_workers=num_processes) as executor:
1133
+ futures = []
1134
+ for i in range(num_processes):
1135
+ future = executor.submit(
1136
+ process_worker,
1137
+ i,
1138
+ process_episodes[i],
1139
+ repo_id,
1140
+ task,
1141
+ mcap_files,
1142
+ mcap_versions,
1143
+ robot_type,
1144
+ fps,
1145
+ mode,
1146
+ image_size,
1147
+ dataset_config,
1148
+ generate_vel,
1149
+ chunk_size,
1150
+ record_mcap_path,
1151
+ filter_action_types, # Pass HIL filter
1152
+ )
1153
+ futures.append(future)
1154
+
1155
+ # Wait for all processes to complete and collect results
1156
+ for future in futures:
1157
+ temp_repo_ids.append(future.result())
1158
+
1159
+ return temp_repo_ids
1160
+
1161
+
1162
+ ############################################# Convert Task to LeRobot #############################################
1163
+ def convert_task_to_lerobot(
1164
+ task_name: str,
1165
+ repo_id: str | None = None,
1166
+ robot_type: str = "piper",
1167
+ fps: int = 60,
1168
+ mode: str = "video",
1169
+ image_size: tuple[int, int] = (320, 180),
1170
+ robot_config: DualArmConfig | None = None,
1171
+ dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
1172
+ generate_vel: bool = False,
1173
+ chunk_size: int = 1000,
1174
+ num_processes: int = 1,
1175
+ push_to_hub: bool = False,
1176
+ tasks_json_path: str = TASKS_JSON_PATH,
1177
+ dataset_root: str = DATASET_ROOT,
1178
+ filter_action_types: set[str] | None = None, # HIL: action types to keep,
1179
+ final_dataset_repo_root: str | Path = "we_d900",
1180
+ ):
1181
+ """
1182
+ Convert all mcap files for a specific task to a single LeRobot dataset.
1183
+
1184
+ Args:
1185
+ task_name: The task name from tasks_merged.json
1186
+ repo_id: Repository ID for the dataset (default: task_name with spaces replaced by underscores)
1187
+ robot_type: Type of robot ("piper" or "arx")
1188
+ fps: Frames per second
1189
+ mode: Dataset mode ("video" or "image")
1190
+ image_size: Size of images to resize to
1191
+ robot_config: Robot configuration (auto-selected based on robot_type if None)
1192
+ dataset_config: Dataset configuration
1193
+ generate_vel: Whether to generate velocity data
1194
+ chunk_size: Process data in chunks
1195
+ num_processes: Number of processes for parallel processing
1196
+ push_to_hub: Whether to push to Hugging Face Hub
1197
+ tasks_json_path: Path to tasks_merged.json
1198
+ dataset_root: Root directory containing the dataset folders
1199
+ filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
1200
+ Default is None (keep all). For HIL data, use DEFAULT_HIL_ACTION_TYPES.
1201
+ """
1202
+ # Load folders for the task
1203
+ folders = load_task_folders(task_name, tasks_json_path)
1204
+ print(f"Found {len(folders)} folders for task '{task_name}'")
1205
+
1206
+ # Collect mcap files and versions
1207
+ mcap_files = []
1208
+ mcap_versions = []
1209
+ for folder in tqdm.tqdm(folders, desc="Collecting mcap files"):
1210
+ if os.path.exists(folder):
1211
+ folder_path = folder
1212
+ elif os.path.exists(os.path.join(dataset_root, folder)):
1213
+ folder_path = os.path.join(dataset_root, folder)
1214
+ elif os.path.exists(os.path.join(dataset_root, task_name, folder)):
1215
+ folder_path = os.path.join(dataset_root, task_name, folder)
1216
+ else:
1217
+ raise FileNotFoundError(f"Folder {folder} not found in dataset_root {dataset_root}")
1218
+ mcap_path, mcap_version = get_mcap_info_from_folder(folder_path)
1219
+ if mcap_path:
1220
+ mcap_files.append(mcap_path)
1221
+ mcap_versions.append(mcap_version)
1222
+
1223
+ print(f"Found {len(mcap_files)} mcap files")
1224
+
1225
+ if not mcap_files:
1226
+ print("No mcap files found, exiting")
1227
+ return
1228
+
1229
+ # Set default repo_id
1230
+ if repo_id is None:
1231
+ repo_id = f"worldengine/{task_name.replace(' ', '_').lower()}"
1232
+
1233
+ # Set default robot_config based on robot_type
1234
+ if robot_config is None:
1235
+ if robot_type == "arx":
1236
+ robot_config = DualArxConfig()
1237
+ else:
1238
+ robot_config = DualPiperConfig()
1239
+
1240
+ # Log HIL filtering info
1241
+ if filter_action_types is not None:
1242
+ print(f"HIL filtering enabled: keeping action_types {filter_action_types}")
1243
+
1244
+ # Convert to LeRobot dataset
1245
+ config = {
1246
+ "mcap_files": mcap_files,
1247
+ "mcap_versions": mcap_versions,
1248
+ "robot_type": robot_type,
1249
+ "fps": fps,
1250
+ "mode": mode,
1251
+ "num_processes": num_processes,
1252
+ "image_size": image_size,
1253
+ "robot_config": robot_config,
1254
+ "dataset_config": dataset_config,
1255
+ "generate_vel": generate_vel,
1256
+ "chunk_size": chunk_size,
1257
+ "repo_id": repo_id,
1258
+ "task": task_name,
1259
+ "episodes": None,
1260
+ "push_to_hub": push_to_hub,
1261
+ "record_mcap_path": True, # Always record mcap path
1262
+ "filter_action_types": filter_action_types, # HIL filter
1263
+ }
1264
+
1265
+ if num_processes > 1:
1266
+ temp_repo_ids = convert_mcap_to_lerobot_multiple_process(**config)
1267
+ if not isinstance(temp_repo_ids, list):
1268
+ temp_repo_ids = [temp_repo_ids]
1269
+
1270
+ # Filter out empty temp datasets (workers that produced 0 episodes have no tasks.parquet)
1271
+ non_empty_repo_ids = []
1272
+ for tmp_id in temp_repo_ids:
1273
+ tasks_parquet = Path(HF_LEROBOT_HOME) / tmp_id / "meta" / "tasks.parquet"
1274
+ if tasks_parquet.exists():
1275
+ non_empty_repo_ids.append(tmp_id)
1276
+ else:
1277
+ print(f" Skipping empty temp dataset (0 episodes): {tmp_id}")
1278
+ if not non_empty_repo_ids:
1279
+ print("All worker datasets are empty — no episodes to merge. Aborting.")
1280
+ return
1281
+ print(f"Merging {len(non_empty_repo_ids)}/{len(temp_repo_ids)} non-empty temporary datasets...")
1282
+ repo_ids_str = json.dumps(non_empty_repo_ids)
1283
+
1284
+ cmd = [
1285
+ "python", "-m", "lerobot.scripts.lerobot_edit_dataset",
1286
+ "--repo_id", f"{final_dataset_repo_root}/{task_name}",
1287
+ "--operation.type", "merge",
1288
+ "--operation.repo_ids", repo_ids_str,
1289
+ "--data_files_size_in_mb", "0",
1290
+ "--video_files_size_in_mb", "0"
1291
+ ]
1292
+
1293
+ try:
1294
+ result = subprocess.run(
1295
+ cmd,
1296
+ check=True,
1297
+ capture_output=True,
1298
+ text=True
1299
+ )
1300
+ print("Command executed successfully!")
1301
+ print("STDOUT:", result.stdout)
1302
+ return result
1303
+ except subprocess.CalledProcessError as e:
1304
+ print(f"Error executing command: {e}")
1305
+ print("STDERR:", e.stderr)
1306
+ raise
1307
+ finally:
1308
+ # Delete all temp datasets (including empty ones)
1309
+ for repo_id in temp_repo_ids:
1310
+ tmp_path = Path(HF_LEROBOT_HOME) / repo_id
1311
+ if tmp_path.exists():
1312
+ shutil.rmtree(tmp_path)
1313
+
1314
+ else:
1315
+ convert_mcap_to_lerobot(**config)
1316
+
1317
+ print(f"Dataset saved to {HF_LEROBOT_HOME / repo_id}")
1318
+
1319
+
1320
+ if __name__ == "__main__":
1321
+ parser = argparse.ArgumentParser(description="Convert MCAP files to LeRobot format (with HIL support).")
1322
+ parser.add_argument("--task", type=str, default=None, required=True, help="Task name from tasks_merged.json to convert")
1323
+ parser.add_argument("--num_process", type=int, default=1, help="Number of processes to use")
1324
+ parser.add_argument("--robot_type", type=str, default="piper", help="Type of robot (e.g., 'arx', 'piper')")
1325
+ parser.add_argument("--repo_id", type=str, default=None, help="Repository ID for the dataset")
1326
+ parser.add_argument("--fps", type=int, default=60, help="Frames per second")
1327
+ 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")
1328
+ parser.add_argument("--dataset_root", type=str, default=DATASET_ROOT, help="the dataset root of the raw mcap data")
1329
+ parser.add_argument("--final_dataset_repo_root", type=str, default="we_d900", help="The final dataset repo root to save the merged dataset")
1330
+ parser.add_argument(
1331
+ "--hil_filter",
1332
+ action="store_true",
1333
+ help="Enable HIL filtering: only keep 'inference' and 'teleoperation' action types"
1334
+ )
1335
+ parser.add_argument(
1336
+ "--action_types",
1337
+ type=str,
1338
+ nargs="+",
1339
+ default=None,
1340
+ help="Custom action types to keep (e.g., --action_types inference teleoperation). Overrides --hil_filter."
1341
+ )
1342
+ args = parser.parse_args()
1343
+
1344
+ # Determine action types filter
1345
+ filter_action_types = None
1346
+ if args.action_types:
1347
+ filter_action_types = set(args.action_types)
1348
+ elif args.hil_filter:
1349
+ filter_action_types = DEFAULT_HIL_ACTION_TYPES
1350
+
1351
+ convert_task_to_lerobot(
1352
+ task_name=args.task,
1353
+ repo_id=args.repo_id,
1354
+ robot_type=args.robot_type,
1355
+ fps=args.fps,
1356
+ num_processes=args.num_process,
1357
+ tasks_json_path=args.tasks_json_path,
1358
+ dataset_root=args.dataset_root,
1359
+ filter_action_types=filter_action_types,
1360
+ final_dataset_repo_root=args.final_dataset_repo_root
1361
+ )