CyberDJ commited on
Commit
2b81d26
Β·
verified Β·
1 Parent(s): f83b064

Upload scripts/convert_mcap_pipeline.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/convert_mcap_pipeline.py +603 -0
scripts/convert_mcap_pipeline.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Unified MCAP β†’ LeRobot pipeline
4
+
5
+ Runs the full conversion in sequence:
6
+ 1. MCAP β†’ LeRobot v3.0 (full-episode or DAgger-segment mode)
7
+ 2. Fix dataset bugs (episode metadata file_index + optional gripper scaling)
8
+ 3. v3.0 β†’ v2.1 (saved alongside v3.0; original v3.0 is preserved)
9
+
10
+ Usage (full-episode mode):
11
+ python convert_mcap_pipeline.py \\
12
+ --task insert-mouse-battery \\
13
+ --robot_type arx \\
14
+ --final_dataset_repo_root we_d900 \\
15
+ --tasks_json_path /path/to/tasks_hil.json \\
16
+ --dataset_root /nas/volume1/scratch/datasets \\
17
+ --num_process 40
18
+
19
+ Usage (DAgger-segment mode):
20
+ python convert_mcap_pipeline.py \\
21
+ --task insert-mouse-battery \\
22
+ --robot_type arx \\
23
+ --mode dagger \\
24
+ --min_segment_length 10 \\
25
+ --final_dataset_repo_root we_d900 \\
26
+ --tasks_json_path /path/to/tasks_hil.json \\
27
+ --dataset_root /nas/volume1/scratch/datasets \\
28
+ --num_process 20
29
+
30
+ Output locations (for final_dataset_repo_root=we_d900, task=insert-mouse-battery):
31
+ v3.0: $HF_LEROBOT_HOME/we_d900/insert-mouse-battery
32
+ v2.1: $HF_LEROBOT_HOME/we_d900/insert-mouse-battery_v21
33
+ """
34
+
35
+ import argparse
36
+ import json
37
+ import logging
38
+ import shutil
39
+ import subprocess
40
+ import sys
41
+ from pathlib import Path
42
+
43
+ import numpy as np
44
+ import pandas as pd
45
+ import pyarrow as pa
46
+ import pyarrow.parquet as pq
47
+ import jsonlines
48
+ import tqdm
49
+
50
+ # ── import sibling convert scripts ────────────────────────────────────────────
51
+ _SCRIPTS_DIR = Path(__file__).parent
52
+ sys.path.insert(0, str(_SCRIPTS_DIR))
53
+
54
+ from convert_mcap_to_lerobot import ( # noqa: E402
55
+ convert_task_to_lerobot,
56
+ DEFAULT_HIL_ACTION_TYPES,
57
+ DATASET_ROOT,
58
+ TASKS_JSON_PATH,
59
+ )
60
+ from convert_mcap_to_lerobot_dagger_segment import ( # noqa: E402
61
+ convert_task_to_lerobot_dagger,
62
+ )
63
+
64
+ # ── lerobot utils ─────────────────────────────────────────────────────────────
65
+ from lerobot.utils.constants import HF_LEROBOT_HOME # noqa: E402
66
+ from lerobot.datasets.utils import ( # noqa: E402
67
+ DEFAULT_CHUNK_SIZE,
68
+ DEFAULT_TASKS_PATH,
69
+ DEFAULT_VIDEO_PATH,
70
+ LEGACY_EPISODES_PATH,
71
+ LEGACY_EPISODES_STATS_PATH,
72
+ LEGACY_TASKS_PATH,
73
+ load_info,
74
+ load_nested_dataset,
75
+ unflatten_dict,
76
+ write_info,
77
+ )
78
+
79
+ # ── constants ─────────────────────────────────────────────────────────────────
80
+ GRIPPER_THRESHOLD = 0.1 # gripper max below this β†’ needs rescaling
81
+ GRIPPER_SCALE = 0.08 # old recordings store gripper in [0, 0.08]
82
+
83
+ V21 = "v2.1"
84
+ V30 = "v3.0"
85
+ LEGACY_DATA_PATH = "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet"
86
+ LEGACY_VIDEO_PATH = "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4"
87
+
88
+
89
+ # ══════════════════════════════════════════════════════════════════════════════
90
+ # Step 2: Fix dataset bugs (inlined from tools/fix_lerobot_dataset.py)
91
+ # ══════════════════════════════════════════════════════════════════════════════
92
+
93
+ def fix_file_index(root: Path) -> int:
94
+ """
95
+ Rebuild data/file_index in meta/episodes/*.parquet from actual data files.
96
+
97
+ Bug: convert scripts that use rglob("*.parquet") accidentally pick up meta
98
+ parquet files and produce duplicate / wrong data/file_index entries.
99
+
100
+ Returns number of corrected episode entries.
101
+ """
102
+ # Build ground-truth: episode_index β†’ (chunk_idx, file_idx)
103
+ ep_to_file: dict[int, tuple[int, int]] = {}
104
+ for p in sorted((root / "data").glob("*/*.parquet")):
105
+ chunk_idx = int(p.parent.name.split("-")[1])
106
+ file_idx = int(p.stem.split("-")[1])
107
+ df_ep = pd.read_parquet(p, columns=["episode_index"])
108
+ for ep in df_ep["episode_index"].unique():
109
+ ep_to_file[int(ep)] = (chunk_idx, file_idx)
110
+
111
+ fixed_count = 0
112
+ for eps_file in sorted((root / "meta" / "episodes").glob("*/*.parquet")):
113
+ df = pd.read_parquet(eps_file)
114
+ changed = False
115
+ for i, row in df.iterrows():
116
+ ep = int(row["episode_index"])
117
+ if ep not in ep_to_file:
118
+ continue
119
+ correct_chunk, correct_file = ep_to_file[ep]
120
+ if (int(row["data/chunk_index"]) != correct_chunk
121
+ or int(row["data/file_index"]) != correct_file):
122
+ df.at[i, "data/chunk_index"] = correct_chunk
123
+ df.at[i, "data/file_index"] = correct_file
124
+ fixed_count += 1
125
+ changed = True
126
+ if changed:
127
+ df.to_parquet(eps_file, index=False)
128
+
129
+ return fixed_count
130
+
131
+
132
+ def needs_gripper_fix(root: Path, gripper_indices: list[int] = [6, 13]) -> list[tuple[Path, float]]:
133
+ """
134
+ Check which data parquet files have gripper values in [0, 0.08] range
135
+ (old MCAP format) instead of [0, 1].
136
+
137
+ Returns list of (path, current_max) for files that need fixing.
138
+ """
139
+ data_files = sorted((root / "data").glob("*/*.parquet"))
140
+ to_fix = []
141
+
142
+ for pf in tqdm.tqdm(data_files, desc=" Checking gripper values", leave=False):
143
+ table = pq.read_table(pf)
144
+ if "action" not in table.column_names:
145
+ continue
146
+ actions = np.array([r.as_py() for r in table.column("action")], dtype=np.float32)
147
+ if actions.ndim != 2:
148
+ continue
149
+ gripper_max = max(
150
+ (actions[:, idx].max() for idx in gripper_indices if idx < actions.shape[1]),
151
+ default=0.0,
152
+ )
153
+ if gripper_max <= GRIPPER_THRESHOLD:
154
+ to_fix.append((pf, float(gripper_max)))
155
+
156
+ return to_fix
157
+
158
+
159
+ def fix_gripper(files_to_fix: list[tuple[Path, float]], gripper_indices: list[int] = [6, 13]) -> int:
160
+ """
161
+ Rescale gripper dimensions from [0, 0.08] to [0, 1] in-place.
162
+ Returns number of files modified.
163
+ """
164
+ modified = 0
165
+ for pf, _ in tqdm.tqdm(files_to_fix, desc=" Fixing gripper", leave=False):
166
+ table = pq.read_table(pf)
167
+ if "action" not in table.column_names:
168
+ continue
169
+ action_col = table.column("action")
170
+ actions = np.array([r.as_py() for r in action_col], dtype=np.float32)
171
+ if actions.ndim != 2:
172
+ continue
173
+ for idx in gripper_indices:
174
+ if idx < actions.shape[1]:
175
+ actions[:, idx] = np.clip(actions[:, idx] / GRIPPER_SCALE, 0.0, 1.0)
176
+ new_col = pa.array([row.tolist() for row in actions], type=action_col.type)
177
+ col_idx = table.column_names.index("action")
178
+ table = table.set_column(col_idx, "action", new_col)
179
+ pq.write_table(table, pf)
180
+ modified += 1
181
+ return modified
182
+
183
+
184
+ def run_fixes(dataset_path: Path, fix_gripper_flag: bool = False):
185
+ """Run all dataset bug fixes on a v3.0 dataset in-place."""
186
+ info_path = dataset_path / "meta" / "info.json"
187
+ if not info_path.exists():
188
+ logging.warning(f" No info.json found at {dataset_path}, skipping fixes")
189
+ return
190
+
191
+ with open(info_path) as f:
192
+ info = json.load(f)
193
+ version = info.get("codebase_version", "unknown")
194
+
195
+ if version != V30:
196
+ logging.warning(f" Dataset version is {version}, skipping v3.0-specific fixes")
197
+ return
198
+
199
+ # Fix 1: episode metadata file_index
200
+ logging.info(" [fix 1/2] Checking episodes metadata (data/file_index)...")
201
+ n_fixed = fix_file_index(dataset_path)
202
+ if n_fixed > 0:
203
+ logging.info(f" βœ“ Fixed {n_fixed} file_index entries")
204
+ else:
205
+ logging.info(" βœ“ file_index OK")
206
+
207
+ # Fix 2: gripper scaling β€” auto-detected from actual values; skipped only with --no_fix_gripper
208
+ logging.info(" [fix 2/2] Checking gripper values...")
209
+ files_to_fix = needs_gripper_fix(dataset_path)
210
+ if files_to_fix:
211
+ if fix_gripper_flag:
212
+ logging.info(
213
+ f" Detected {len(files_to_fix)} files with gripper in [0,0.08] range β†’ auto-rescaling to [0,1]"
214
+ )
215
+ n_fixed = fix_gripper(files_to_fix)
216
+ logging.info(f" βœ“ Fixed gripper in {n_fixed} files")
217
+ else:
218
+ logging.warning(
219
+ f" ⚠ Skipping gripper fix (--no_fix_gripper): "
220
+ f"{len(files_to_fix)} files still have gripper in [0,0.08] range"
221
+ )
222
+ else:
223
+ logging.info(" βœ“ Gripper values OK (no rescaling needed)")
224
+
225
+
226
+ # ══════════════════════════════════════════════════════════════════════════════
227
+ # Step 3: v3.0 β†’ v2.1 (inlined from convert_lerobot_v30_to_v21.py)
228
+ # ══════════════════════════════════════════════════════════════════════════════
229
+
230
+ def _to_jsonable(obj):
231
+ """Recursively convert numpy types to JSON-serializable Python objects."""
232
+ if isinstance(obj, dict):
233
+ return {str(k): _to_jsonable(v) for k, v in obj.items()}
234
+ if isinstance(obj, (list, tuple)):
235
+ return [_to_jsonable(v) for v in obj]
236
+ if isinstance(obj, np.ndarray):
237
+ if obj.dtype == object:
238
+ return [_to_jsonable(v) for v in obj.tolist()]
239
+ return obj.tolist()
240
+ if isinstance(obj, np.generic):
241
+ return obj.item()
242
+ return obj
243
+
244
+
245
+ def _load_episodes_metadata(root: Path) -> pd.DataFrame:
246
+ episodes_dir = root / "meta" / "episodes"
247
+ ds = load_nested_dataset(episodes_dir)
248
+ return ds.to_pandas()
249
+
250
+
251
+ def _load_tasks(root: Path) -> pd.DataFrame:
252
+ tasks_path = root / DEFAULT_TASKS_PATH
253
+ return pd.read_parquet(tasks_path)
254
+
255
+
256
+ def _get_video_keys(root: Path) -> list[str]:
257
+ info = load_info(root)
258
+ return sorted(k for k, ft in info["features"].items() if ft["dtype"] == "video")
259
+
260
+
261
+ def _get_image_keys(root: Path) -> list[str]:
262
+ info = load_info(root)
263
+ return [k for k, ft in info["features"].items() if ft["dtype"] == "image"]
264
+
265
+
266
+ def _convert_tasks_to_jsonl(root: Path, new_root: Path):
267
+ df_tasks = _load_tasks(root)
268
+ tasks_path = new_root / LEGACY_TASKS_PATH
269
+ tasks_path.parent.mkdir(parents=True, exist_ok=True)
270
+ with jsonlines.open(tasks_path, mode="w") as writer:
271
+ for task_str, row in df_tasks.iterrows():
272
+ writer.write({"task_index": int(row["task_index"]), "task": str(task_str)})
273
+
274
+
275
+ def _convert_episodes_to_jsonl(root: Path, new_root: Path):
276
+ df_episodes = _load_episodes_metadata(root)
277
+ df_tasks = _load_tasks(root)
278
+ task_index_to_task = {int(row["task_index"]): str(t) for t, row in df_tasks.iterrows()}
279
+
280
+ episodes_path = new_root / LEGACY_EPISODES_PATH
281
+ episodes_path.parent.mkdir(parents=True, exist_ok=True)
282
+ stats_path = new_root / LEGACY_EPISODES_STATS_PATH
283
+ stats_columns = [c for c in df_episodes.columns if c.startswith("stats/")]
284
+
285
+ with jsonlines.open(episodes_path, mode="w") as ep_w, \
286
+ jsonlines.open(stats_path, mode="w") as st_w:
287
+ for _, row in df_episodes.iterrows():
288
+ episode_index = int(row["episode_index"])
289
+
290
+ if "tasks" in row:
291
+ tasks = list(row["tasks"]) if isinstance(row["tasks"], (list, tuple)) else [row["tasks"]]
292
+ else:
293
+ task_idx = row.get("task_index", 0)
294
+ tasks = [task_index_to_task.get(int(task_idx), "")]
295
+
296
+ length = int(row["dataset_to_index"] - row["dataset_from_index"])
297
+ ep_w.write({"episode_index": episode_index, "tasks": tasks[0][0], "length": length})
298
+
299
+ if stats_columns:
300
+ stats_dict = {}
301
+ for col in stats_columns:
302
+ key = col[6:] # strip "stats/"
303
+ value = row[col]
304
+ if hasattr(value, "tolist"):
305
+ value = value.tolist()
306
+ stats_dict[key] = value
307
+ unflat = _to_jsonable(unflatten_dict(stats_dict))
308
+ st_w.write({"episode_index": episode_index, "stats": unflat})
309
+
310
+
311
+ def _convert_data_files(root: Path, new_root: Path):
312
+ from datasets import Features, Image
313
+
314
+ data_paths = sorted((root / "data").glob("*/*.parquet"))
315
+ if not data_paths:
316
+ logging.warning("No data files found for v2.1 conversion")
317
+ return
318
+
319
+ image_keys = _get_image_keys(root)
320
+ all_data = pd.concat([pd.read_parquet(p) for p in data_paths], ignore_index=True)
321
+
322
+ for episode_index, ep_df in tqdm.tqdm(
323
+ all_data.groupby("episode_index"), desc=" Writing v2.1 data files"
324
+ ):
325
+ chunk_idx = episode_index // DEFAULT_CHUNK_SIZE
326
+ out_path = new_root / LEGACY_DATA_PATH.format(
327
+ episode_chunk=chunk_idx, episode_index=episode_index
328
+ )
329
+ out_path.parent.mkdir(parents=True, exist_ok=True)
330
+
331
+ ep_df = ep_df.copy().sort_values("frame_index").reset_index(drop=True)
332
+
333
+ if image_keys:
334
+ schema = pa.Schema.from_pandas(ep_df)
335
+ features = Features.from_arrow_schema(schema)
336
+ for key in image_keys:
337
+ features[key] = Image()
338
+ schema = features.arrow_schema
339
+ else:
340
+ schema = None
341
+
342
+ ep_df.to_parquet(out_path, index=False, schema=schema)
343
+
344
+
345
+ def _split_video(src: Path, dst: Path, start_time: float, end_time: float):
346
+ dst.parent.mkdir(parents=True, exist_ok=True)
347
+ cmd = [
348
+ "ffmpeg", "-y",
349
+ "-ss", str(start_time),
350
+ "-i", str(src),
351
+ "-t", str(end_time - start_time),
352
+ "-c", "copy",
353
+ "-avoid_negative_ts", "make_zero",
354
+ str(dst),
355
+ ]
356
+ result = subprocess.run(cmd, capture_output=True, text=True)
357
+ if result.returncode != 0:
358
+ raise RuntimeError(f"ffmpeg failed: {result.stderr}")
359
+
360
+
361
+ def _convert_video_files(root: Path, new_root: Path):
362
+ video_keys = _get_video_keys(root)
363
+ if not video_keys:
364
+ return
365
+
366
+ df_episodes = _load_episodes_metadata(root)
367
+
368
+ for video_key in video_keys:
369
+ chunk_col = f"videos/{video_key}/chunk_index"
370
+ file_col = f"videos/{video_key}/file_index"
371
+ from_ts_col = f"videos/{video_key}/from_timestamp"
372
+ to_ts_col = f"videos/{video_key}/to_timestamp"
373
+
374
+ if chunk_col not in df_episodes.columns:
375
+ logging.warning(f" Missing video metadata for {video_key}, skipping")
376
+ continue
377
+
378
+ for _, row in tqdm.tqdm(
379
+ df_episodes.iterrows(),
380
+ desc=f" Converting {video_key} videos",
381
+ total=len(df_episodes),
382
+ ):
383
+ episode_index = int(row["episode_index"])
384
+ src = root / DEFAULT_VIDEO_PATH.format(
385
+ video_key=video_key,
386
+ chunk_index=int(row[chunk_col]),
387
+ file_index=int(row[file_col]),
388
+ )
389
+ if not src.exists():
390
+ logging.warning(f" Source video not found: {src}")
391
+ continue
392
+
393
+ legacy_chunk = episode_index // DEFAULT_CHUNK_SIZE
394
+ dst = new_root / LEGACY_VIDEO_PATH.format(
395
+ episode_chunk=legacy_chunk,
396
+ video_key=video_key,
397
+ episode_index=episode_index,
398
+ )
399
+ _split_video(src, dst, float(row[from_ts_col]), float(row[to_ts_col]))
400
+
401
+
402
+ def _convert_info(root: Path, new_root: Path):
403
+ info = load_info(root)
404
+ df_episodes = _load_episodes_metadata(root)
405
+ num_episodes = len(df_episodes)
406
+ total_chunks = (num_episodes // DEFAULT_CHUNK_SIZE) + (1 if num_episodes % DEFAULT_CHUNK_SIZE else 0)
407
+
408
+ info["codebase_version"] = V21
409
+ info["total_chunks"] = total_chunks
410
+ info["total_videos"] = num_episodes * len(_get_video_keys(root))
411
+ info.pop("data_files_size_in_mb", None)
412
+ info.pop("video_files_size_in_mb", None)
413
+ info["data_path"] = LEGACY_DATA_PATH
414
+ if info.get("video_path") is not None:
415
+ info["video_path"] = LEGACY_VIDEO_PATH
416
+
417
+ for key in info["features"]:
418
+ if "fps" in info["features"][key] and info["features"][key]["dtype"] != "video":
419
+ del info["features"][key]["fps"]
420
+
421
+ write_info(info, new_root)
422
+
423
+
424
+ def convert_v30_to_v21(v30_path: Path) -> Path:
425
+ """
426
+ Convert a v3.0 dataset to v2.1, saving the result at {v30_path}_v21.
427
+ The original v3.0 dataset is left intact.
428
+
429
+ Returns the path to the new v2.1 dataset.
430
+ """
431
+ info_path = v30_path / "meta" / "info.json"
432
+ if not info_path.exists():
433
+ raise FileNotFoundError(f"No info.json at {v30_path}")
434
+ with open(info_path) as f:
435
+ version = json.load(f).get("codebase_version", "unknown")
436
+ if version != V30:
437
+ raise ValueError(f"Expected v3.0 dataset, got {version}")
438
+
439
+ v21_path = v30_path.parent / f"{v30_path.name}_v21"
440
+ if v21_path.exists():
441
+ logging.info(f" Removing existing v2.1 dir: {v21_path}")
442
+ shutil.rmtree(v21_path)
443
+
444
+ logging.info(f" Converting {v30_path.name} β†’ {v21_path.name}")
445
+ _convert_info(v30_path, v21_path)
446
+ _convert_tasks_to_jsonl(v30_path, v21_path)
447
+ _convert_episodes_to_jsonl(v30_path, v21_path)
448
+ _convert_data_files(v30_path, v21_path)
449
+ _convert_video_files(v30_path, v21_path)
450
+
451
+ return v21_path
452
+
453
+
454
+ # ══════════════════════════════════════════════════════════════════════════════
455
+ # Pipeline orchestration
456
+ # ══════════════════════════════════════════════════════════════════════════════
457
+
458
+ def run_pipeline(args):
459
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
460
+
461
+ # ── Determine output path ─────────────────────────────────────────────────
462
+ # Single-process: HF_LEROBOT_HOME / repo_id
463
+ # Multi-process: HF_LEROBOT_HOME / final_dataset_repo_root / task_name
464
+ if args.num_process > 1:
465
+ v30_path = Path(HF_LEROBOT_HOME) / args.final_dataset_repo_root / args.task
466
+ repo_id = f"{args.final_dataset_repo_root}_temp/{args.task}"
467
+ else:
468
+ repo_id = f"{args.final_dataset_repo_root}/{args.task}"
469
+ v30_path = Path(HF_LEROBOT_HOME) / repo_id
470
+
471
+ # ── Step 1: MCAP β†’ v3.0 ──────────────────────────────────────────────────
472
+ print(f"\n{'='*60}")
473
+ print(f"Step 1: MCAP β†’ LeRobot v3.0 (mode={args.mode})")
474
+ print(f" task: {args.task}")
475
+ print(f" robot_type: {args.robot_type}")
476
+ print(f" num_process: {args.num_process}")
477
+ print(f" output: {v30_path}")
478
+ print(f"{'='*60}")
479
+
480
+ if args.mode == "full":
481
+ # Determine HIL filter
482
+ filter_action_types = None
483
+ if args.action_types:
484
+ filter_action_types = set(args.action_types)
485
+ elif args.hil_filter:
486
+ filter_action_types = DEFAULT_HIL_ACTION_TYPES
487
+
488
+ convert_task_to_lerobot(
489
+ task_name=args.task,
490
+ repo_id=repo_id,
491
+ robot_type=args.robot_type,
492
+ num_processes=args.num_process,
493
+ tasks_json_path=args.tasks_json_path,
494
+ dataset_root=args.dataset_root,
495
+ filter_action_types=filter_action_types,
496
+ final_dataset_repo_root=args.final_dataset_repo_root,
497
+ )
498
+
499
+ elif args.mode == "dagger":
500
+ convert_task_to_lerobot_dagger(
501
+ task_name=args.task,
502
+ repo_id=repo_id,
503
+ robot_type=args.robot_type,
504
+ num_processes=args.num_process,
505
+ tasks_json_path=args.tasks_json_path,
506
+ dataset_root=args.dataset_root,
507
+ min_segment_length=args.min_segment_length,
508
+ action_threshold=args.action_threshold,
509
+ final_dataset_repo_root=args.final_dataset_repo_root,
510
+ )
511
+
512
+ else:
513
+ raise ValueError(f"Unknown mode: {args.mode}. Use 'full' or 'dagger'.")
514
+
515
+ if not v30_path.exists():
516
+ raise RuntimeError(
517
+ f"Conversion completed but dataset not found at expected path: {v30_path}\n"
518
+ f"Check HF_LEROBOT_HOME ({HF_LEROBOT_HOME}) and final_dataset_repo_root."
519
+ )
520
+
521
+ # ── Step 2: Fix bugs ──────────────────────────────────────────────────────
522
+ print(f"\n{'='*60}")
523
+ print("Step 2: Fix dataset bugs")
524
+ print(f" dataset: {v30_path}")
525
+ print(f"{'='*60}")
526
+
527
+ run_fixes(v30_path, fix_gripper_flag=not args.no_fix_gripper)
528
+
529
+ # ── Step 3: v3.0 β†’ v2.1 ──────────────────────────────────────────────────
530
+ if args.no_v21:
531
+ print("\nStep 3: Skipped (--no_v21)")
532
+ else:
533
+ print(f"\n{'='*60}")
534
+ print("Step 3: v3.0 β†’ v2.1")
535
+ print(f"{'='*60}")
536
+ v21_path = convert_v30_to_v21(v30_path)
537
+ print(f" βœ“ v2.1 dataset saved to: {v21_path}")
538
+
539
+ print(f"\n{'='*60}")
540
+ print("Pipeline complete!")
541
+ print(f" v3.0: {v30_path}")
542
+ if not args.no_v21:
543
+ print(f" v2.1: {v30_path.parent / (v30_path.name + '_v21')}")
544
+ print(f"{'='*60}\n")
545
+
546
+
547
+ # ══════════════════════════════════════════════════════════════════════════════
548
+ # Entry point
549
+ # ══════════════════════════════════════════════════════════════════════════════
550
+
551
+ def main():
552
+ parser = argparse.ArgumentParser(
553
+ description="Unified MCAP β†’ LeRobot pipeline (v3.0 + fix + v2.1)",
554
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
555
+ )
556
+
557
+ # ── required ──────────────────────────────────────────────────────────────
558
+ parser.add_argument("--task", type=str, required=True,
559
+ help="Task name (key in tasks_json_path)")
560
+ parser.add_argument("--robot_type", type=str, required=True,
561
+ help="Robot type: 'arx' or 'piper'")
562
+
563
+ # ── paths ─────────────────────────────────────────────────────────────────
564
+ parser.add_argument("--tasks_json_path", type=str, default=TASKS_JSON_PATH,
565
+ help="Path to tasks JSON mapping task names to episode folders")
566
+ parser.add_argument("--dataset_root", type=str, default=DATASET_ROOT,
567
+ help="Root directory containing raw MCAP episode folders")
568
+ parser.add_argument("--final_dataset_repo_root", type=str, default="we_d900",
569
+ help="Subdirectory under HF_LEROBOT_HOME for the output dataset")
570
+
571
+ # ── conversion mode ───────────────────────────────────────────────────────
572
+ parser.add_argument("--mode", type=str, default="full", choices=["full", "dagger"],
573
+ help="'full' = full episode per MCAP; 'dagger' = teleop segments only")
574
+ parser.add_argument("--num_process", type=int, default=1,
575
+ help="Number of parallel worker processes")
576
+
577
+ # ── full mode options ─────────────────────────────────────────────────────
578
+ parser.add_argument("--hil_filter", action="store_true",
579
+ help="[full mode] Keep only INFERENCE+TELEOP frames (HIL filtering)")
580
+ parser.add_argument("--action_types", type=str, nargs="+", default=None,
581
+ help="[full mode] Custom action types to keep (overrides --hil_filter)")
582
+
583
+ # ── dagger mode options ───────────────────────────────────────────────────
584
+ parser.add_argument("--min_segment_length", type=int, default=10,
585
+ help="[dagger mode] Minimum teleop segment length (frames)")
586
+ parser.add_argument("--action_threshold", type=float, default=10.0,
587
+ help="[dagger mode] Discard segments with max|action| above this value")
588
+
589
+ # ── fix options ───────────────────────────────────────────────────────────
590
+ parser.add_argument("--no_fix_gripper", action="store_true",
591
+ help="Disable auto gripper rescaling. By default the script detects "
592
+ "files with gripper in [0,0.08] range and rescales to [0,1] automatically.")
593
+
594
+ # ── output options ────────────────────────────────────────────────────────
595
+ parser.add_argument("--no_v21", action="store_true",
596
+ help="Skip v2.1 conversion (keep v3.0 only)")
597
+
598
+ args = parser.parse_args()
599
+ run_pipeline(args)
600
+
601
+
602
+ if __name__ == "__main__":
603
+ main()