mcap / scripts /convert_mcap_pipeline.py
CyberDJ's picture
Upload scripts/convert_mcap_pipeline.py with huggingface_hub
2b81d26 verified
Raw
History Blame Contribute Delete
26.2 kB
#!/usr/bin/env python3
"""
Unified MCAP β†’ LeRobot pipeline
Runs the full conversion in sequence:
1. MCAP β†’ LeRobot v3.0 (full-episode or DAgger-segment mode)
2. Fix dataset bugs (episode metadata file_index + optional gripper scaling)
3. v3.0 β†’ v2.1 (saved alongside v3.0; original v3.0 is preserved)
Usage (full-episode mode):
python convert_mcap_pipeline.py \\
--task insert-mouse-battery \\
--robot_type arx \\
--final_dataset_repo_root we_d900 \\
--tasks_json_path /path/to/tasks_hil.json \\
--dataset_root /nas/volume1/scratch/datasets \\
--num_process 40
Usage (DAgger-segment mode):
python convert_mcap_pipeline.py \\
--task insert-mouse-battery \\
--robot_type arx \\
--mode dagger \\
--min_segment_length 10 \\
--final_dataset_repo_root we_d900 \\
--tasks_json_path /path/to/tasks_hil.json \\
--dataset_root /nas/volume1/scratch/datasets \\
--num_process 20
Output locations (for final_dataset_repo_root=we_d900, task=insert-mouse-battery):
v3.0: $HF_LEROBOT_HOME/we_d900/insert-mouse-battery
v2.1: $HF_LEROBOT_HOME/we_d900/insert-mouse-battery_v21
"""
import argparse
import json
import logging
import shutil
import subprocess
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import jsonlines
import tqdm
# ── import sibling convert scripts ────────────────────────────────────────────
_SCRIPTS_DIR = Path(__file__).parent
sys.path.insert(0, str(_SCRIPTS_DIR))
from convert_mcap_to_lerobot import ( # noqa: E402
convert_task_to_lerobot,
DEFAULT_HIL_ACTION_TYPES,
DATASET_ROOT,
TASKS_JSON_PATH,
)
from convert_mcap_to_lerobot_dagger_segment import ( # noqa: E402
convert_task_to_lerobot_dagger,
)
# ── lerobot utils ─────────────────────────────────────────────────────────────
from lerobot.utils.constants import HF_LEROBOT_HOME # noqa: E402
from lerobot.datasets.utils import ( # noqa: E402
DEFAULT_CHUNK_SIZE,
DEFAULT_TASKS_PATH,
DEFAULT_VIDEO_PATH,
LEGACY_EPISODES_PATH,
LEGACY_EPISODES_STATS_PATH,
LEGACY_TASKS_PATH,
load_info,
load_nested_dataset,
unflatten_dict,
write_info,
)
# ── constants ─────────────────────────────────────────────────────────────────
GRIPPER_THRESHOLD = 0.1 # gripper max below this β†’ needs rescaling
GRIPPER_SCALE = 0.08 # old recordings store gripper in [0, 0.08]
V21 = "v2.1"
V30 = "v3.0"
LEGACY_DATA_PATH = "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet"
LEGACY_VIDEO_PATH = "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4"
# ══════════════════════════════════════════════════════════════════════════════
# Step 2: Fix dataset bugs (inlined from tools/fix_lerobot_dataset.py)
# ══════════════════════════════════════════════════════════════════════════════
def fix_file_index(root: Path) -> int:
"""
Rebuild data/file_index in meta/episodes/*.parquet from actual data files.
Bug: convert scripts that use rglob("*.parquet") accidentally pick up meta
parquet files and produce duplicate / wrong data/file_index entries.
Returns number of corrected episode entries.
"""
# Build ground-truth: episode_index β†’ (chunk_idx, file_idx)
ep_to_file: dict[int, tuple[int, int]] = {}
for p in sorted((root / "data").glob("*/*.parquet")):
chunk_idx = int(p.parent.name.split("-")[1])
file_idx = int(p.stem.split("-")[1])
df_ep = pd.read_parquet(p, columns=["episode_index"])
for ep in df_ep["episode_index"].unique():
ep_to_file[int(ep)] = (chunk_idx, file_idx)
fixed_count = 0
for eps_file in sorted((root / "meta" / "episodes").glob("*/*.parquet")):
df = pd.read_parquet(eps_file)
changed = False
for i, row in df.iterrows():
ep = int(row["episode_index"])
if ep not in ep_to_file:
continue
correct_chunk, correct_file = ep_to_file[ep]
if (int(row["data/chunk_index"]) != correct_chunk
or int(row["data/file_index"]) != correct_file):
df.at[i, "data/chunk_index"] = correct_chunk
df.at[i, "data/file_index"] = correct_file
fixed_count += 1
changed = True
if changed:
df.to_parquet(eps_file, index=False)
return fixed_count
def needs_gripper_fix(root: Path, gripper_indices: list[int] = [6, 13]) -> list[tuple[Path, float]]:
"""
Check which data parquet files have gripper values in [0, 0.08] range
(old MCAP format) instead of [0, 1].
Returns list of (path, current_max) for files that need fixing.
"""
data_files = sorted((root / "data").glob("*/*.parquet"))
to_fix = []
for pf in tqdm.tqdm(data_files, desc=" Checking gripper values", leave=False):
table = pq.read_table(pf)
if "action" not in table.column_names:
continue
actions = np.array([r.as_py() for r in table.column("action")], dtype=np.float32)
if actions.ndim != 2:
continue
gripper_max = max(
(actions[:, idx].max() for idx in gripper_indices if idx < actions.shape[1]),
default=0.0,
)
if gripper_max <= GRIPPER_THRESHOLD:
to_fix.append((pf, float(gripper_max)))
return to_fix
def fix_gripper(files_to_fix: list[tuple[Path, float]], gripper_indices: list[int] = [6, 13]) -> int:
"""
Rescale gripper dimensions from [0, 0.08] to [0, 1] in-place.
Returns number of files modified.
"""
modified = 0
for pf, _ in tqdm.tqdm(files_to_fix, desc=" Fixing gripper", leave=False):
table = pq.read_table(pf)
if "action" not in table.column_names:
continue
action_col = table.column("action")
actions = np.array([r.as_py() for r in action_col], dtype=np.float32)
if actions.ndim != 2:
continue
for idx in gripper_indices:
if idx < actions.shape[1]:
actions[:, idx] = np.clip(actions[:, idx] / GRIPPER_SCALE, 0.0, 1.0)
new_col = pa.array([row.tolist() for row in actions], type=action_col.type)
col_idx = table.column_names.index("action")
table = table.set_column(col_idx, "action", new_col)
pq.write_table(table, pf)
modified += 1
return modified
def run_fixes(dataset_path: Path, fix_gripper_flag: bool = False):
"""Run all dataset bug fixes on a v3.0 dataset in-place."""
info_path = dataset_path / "meta" / "info.json"
if not info_path.exists():
logging.warning(f" No info.json found at {dataset_path}, skipping fixes")
return
with open(info_path) as f:
info = json.load(f)
version = info.get("codebase_version", "unknown")
if version != V30:
logging.warning(f" Dataset version is {version}, skipping v3.0-specific fixes")
return
# Fix 1: episode metadata file_index
logging.info(" [fix 1/2] Checking episodes metadata (data/file_index)...")
n_fixed = fix_file_index(dataset_path)
if n_fixed > 0:
logging.info(f" βœ“ Fixed {n_fixed} file_index entries")
else:
logging.info(" βœ“ file_index OK")
# Fix 2: gripper scaling β€” auto-detected from actual values; skipped only with --no_fix_gripper
logging.info(" [fix 2/2] Checking gripper values...")
files_to_fix = needs_gripper_fix(dataset_path)
if files_to_fix:
if fix_gripper_flag:
logging.info(
f" Detected {len(files_to_fix)} files with gripper in [0,0.08] range β†’ auto-rescaling to [0,1]"
)
n_fixed = fix_gripper(files_to_fix)
logging.info(f" βœ“ Fixed gripper in {n_fixed} files")
else:
logging.warning(
f" ⚠ Skipping gripper fix (--no_fix_gripper): "
f"{len(files_to_fix)} files still have gripper in [0,0.08] range"
)
else:
logging.info(" βœ“ Gripper values OK (no rescaling needed)")
# ══════════════════════════════════════════════════════════════════════════════
# Step 3: v3.0 β†’ v2.1 (inlined from convert_lerobot_v30_to_v21.py)
# ══════════════════════════════════════════════════════════════════════════════
def _to_jsonable(obj):
"""Recursively convert numpy types to JSON-serializable Python objects."""
if isinstance(obj, dict):
return {str(k): _to_jsonable(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [_to_jsonable(v) for v in obj]
if isinstance(obj, np.ndarray):
if obj.dtype == object:
return [_to_jsonable(v) for v in obj.tolist()]
return obj.tolist()
if isinstance(obj, np.generic):
return obj.item()
return obj
def _load_episodes_metadata(root: Path) -> pd.DataFrame:
episodes_dir = root / "meta" / "episodes"
ds = load_nested_dataset(episodes_dir)
return ds.to_pandas()
def _load_tasks(root: Path) -> pd.DataFrame:
tasks_path = root / DEFAULT_TASKS_PATH
return pd.read_parquet(tasks_path)
def _get_video_keys(root: Path) -> list[str]:
info = load_info(root)
return sorted(k for k, ft in info["features"].items() if ft["dtype"] == "video")
def _get_image_keys(root: Path) -> list[str]:
info = load_info(root)
return [k for k, ft in info["features"].items() if ft["dtype"] == "image"]
def _convert_tasks_to_jsonl(root: Path, new_root: Path):
df_tasks = _load_tasks(root)
tasks_path = new_root / LEGACY_TASKS_PATH
tasks_path.parent.mkdir(parents=True, exist_ok=True)
with jsonlines.open(tasks_path, mode="w") as writer:
for task_str, row in df_tasks.iterrows():
writer.write({"task_index": int(row["task_index"]), "task": str(task_str)})
def _convert_episodes_to_jsonl(root: Path, new_root: Path):
df_episodes = _load_episodes_metadata(root)
df_tasks = _load_tasks(root)
task_index_to_task = {int(row["task_index"]): str(t) for t, row in df_tasks.iterrows()}
episodes_path = new_root / LEGACY_EPISODES_PATH
episodes_path.parent.mkdir(parents=True, exist_ok=True)
stats_path = new_root / LEGACY_EPISODES_STATS_PATH
stats_columns = [c for c in df_episodes.columns if c.startswith("stats/")]
with jsonlines.open(episodes_path, mode="w") as ep_w, \
jsonlines.open(stats_path, mode="w") as st_w:
for _, row in df_episodes.iterrows():
episode_index = int(row["episode_index"])
if "tasks" in row:
tasks = list(row["tasks"]) if isinstance(row["tasks"], (list, tuple)) else [row["tasks"]]
else:
task_idx = row.get("task_index", 0)
tasks = [task_index_to_task.get(int(task_idx), "")]
length = int(row["dataset_to_index"] - row["dataset_from_index"])
ep_w.write({"episode_index": episode_index, "tasks": tasks[0][0], "length": length})
if stats_columns:
stats_dict = {}
for col in stats_columns:
key = col[6:] # strip "stats/"
value = row[col]
if hasattr(value, "tolist"):
value = value.tolist()
stats_dict[key] = value
unflat = _to_jsonable(unflatten_dict(stats_dict))
st_w.write({"episode_index": episode_index, "stats": unflat})
def _convert_data_files(root: Path, new_root: Path):
from datasets import Features, Image
data_paths = sorted((root / "data").glob("*/*.parquet"))
if not data_paths:
logging.warning("No data files found for v2.1 conversion")
return
image_keys = _get_image_keys(root)
all_data = pd.concat([pd.read_parquet(p) for p in data_paths], ignore_index=True)
for episode_index, ep_df in tqdm.tqdm(
all_data.groupby("episode_index"), desc=" Writing v2.1 data files"
):
chunk_idx = episode_index // DEFAULT_CHUNK_SIZE
out_path = new_root / LEGACY_DATA_PATH.format(
episode_chunk=chunk_idx, episode_index=episode_index
)
out_path.parent.mkdir(parents=True, exist_ok=True)
ep_df = ep_df.copy().sort_values("frame_index").reset_index(drop=True)
if image_keys:
schema = pa.Schema.from_pandas(ep_df)
features = Features.from_arrow_schema(schema)
for key in image_keys:
features[key] = Image()
schema = features.arrow_schema
else:
schema = None
ep_df.to_parquet(out_path, index=False, schema=schema)
def _split_video(src: Path, dst: Path, start_time: float, end_time: float):
dst.parent.mkdir(parents=True, exist_ok=True)
cmd = [
"ffmpeg", "-y",
"-ss", str(start_time),
"-i", str(src),
"-t", str(end_time - start_time),
"-c", "copy",
"-avoid_negative_ts", "make_zero",
str(dst),
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"ffmpeg failed: {result.stderr}")
def _convert_video_files(root: Path, new_root: Path):
video_keys = _get_video_keys(root)
if not video_keys:
return
df_episodes = _load_episodes_metadata(root)
for video_key in video_keys:
chunk_col = f"videos/{video_key}/chunk_index"
file_col = f"videos/{video_key}/file_index"
from_ts_col = f"videos/{video_key}/from_timestamp"
to_ts_col = f"videos/{video_key}/to_timestamp"
if chunk_col not in df_episodes.columns:
logging.warning(f" Missing video metadata for {video_key}, skipping")
continue
for _, row in tqdm.tqdm(
df_episodes.iterrows(),
desc=f" Converting {video_key} videos",
total=len(df_episodes),
):
episode_index = int(row["episode_index"])
src = root / DEFAULT_VIDEO_PATH.format(
video_key=video_key,
chunk_index=int(row[chunk_col]),
file_index=int(row[file_col]),
)
if not src.exists():
logging.warning(f" Source video not found: {src}")
continue
legacy_chunk = episode_index // DEFAULT_CHUNK_SIZE
dst = new_root / LEGACY_VIDEO_PATH.format(
episode_chunk=legacy_chunk,
video_key=video_key,
episode_index=episode_index,
)
_split_video(src, dst, float(row[from_ts_col]), float(row[to_ts_col]))
def _convert_info(root: Path, new_root: Path):
info = load_info(root)
df_episodes = _load_episodes_metadata(root)
num_episodes = len(df_episodes)
total_chunks = (num_episodes // DEFAULT_CHUNK_SIZE) + (1 if num_episodes % DEFAULT_CHUNK_SIZE else 0)
info["codebase_version"] = V21
info["total_chunks"] = total_chunks
info["total_videos"] = num_episodes * len(_get_video_keys(root))
info.pop("data_files_size_in_mb", None)
info.pop("video_files_size_in_mb", None)
info["data_path"] = LEGACY_DATA_PATH
if info.get("video_path") is not None:
info["video_path"] = LEGACY_VIDEO_PATH
for key in info["features"]:
if "fps" in info["features"][key] and info["features"][key]["dtype"] != "video":
del info["features"][key]["fps"]
write_info(info, new_root)
def convert_v30_to_v21(v30_path: Path) -> Path:
"""
Convert a v3.0 dataset to v2.1, saving the result at {v30_path}_v21.
The original v3.0 dataset is left intact.
Returns the path to the new v2.1 dataset.
"""
info_path = v30_path / "meta" / "info.json"
if not info_path.exists():
raise FileNotFoundError(f"No info.json at {v30_path}")
with open(info_path) as f:
version = json.load(f).get("codebase_version", "unknown")
if version != V30:
raise ValueError(f"Expected v3.0 dataset, got {version}")
v21_path = v30_path.parent / f"{v30_path.name}_v21"
if v21_path.exists():
logging.info(f" Removing existing v2.1 dir: {v21_path}")
shutil.rmtree(v21_path)
logging.info(f" Converting {v30_path.name} β†’ {v21_path.name}")
_convert_info(v30_path, v21_path)
_convert_tasks_to_jsonl(v30_path, v21_path)
_convert_episodes_to_jsonl(v30_path, v21_path)
_convert_data_files(v30_path, v21_path)
_convert_video_files(v30_path, v21_path)
return v21_path
# ══════════════════════════════════════════════════════════════════════════════
# Pipeline orchestration
# ══════════════════════════════════════════════════════════════════════════════
def run_pipeline(args):
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
# ── Determine output path ─────────────────────────────────────────────────
# Single-process: HF_LEROBOT_HOME / repo_id
# Multi-process: HF_LEROBOT_HOME / final_dataset_repo_root / task_name
if args.num_process > 1:
v30_path = Path(HF_LEROBOT_HOME) / args.final_dataset_repo_root / args.task
repo_id = f"{args.final_dataset_repo_root}_temp/{args.task}"
else:
repo_id = f"{args.final_dataset_repo_root}/{args.task}"
v30_path = Path(HF_LEROBOT_HOME) / repo_id
# ── Step 1: MCAP β†’ v3.0 ──────────────────────────────────────────────────
print(f"\n{'='*60}")
print(f"Step 1: MCAP β†’ LeRobot v3.0 (mode={args.mode})")
print(f" task: {args.task}")
print(f" robot_type: {args.robot_type}")
print(f" num_process: {args.num_process}")
print(f" output: {v30_path}")
print(f"{'='*60}")
if args.mode == "full":
# Determine HIL 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=repo_id,
robot_type=args.robot_type,
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,
)
elif args.mode == "dagger":
convert_task_to_lerobot_dagger(
task_name=args.task,
repo_id=repo_id,
robot_type=args.robot_type,
num_processes=args.num_process,
tasks_json_path=args.tasks_json_path,
dataset_root=args.dataset_root,
min_segment_length=args.min_segment_length,
action_threshold=args.action_threshold,
final_dataset_repo_root=args.final_dataset_repo_root,
)
else:
raise ValueError(f"Unknown mode: {args.mode}. Use 'full' or 'dagger'.")
if not v30_path.exists():
raise RuntimeError(
f"Conversion completed but dataset not found at expected path: {v30_path}\n"
f"Check HF_LEROBOT_HOME ({HF_LEROBOT_HOME}) and final_dataset_repo_root."
)
# ── Step 2: Fix bugs ──────────────────────────────────────────────────────
print(f"\n{'='*60}")
print("Step 2: Fix dataset bugs")
print(f" dataset: {v30_path}")
print(f"{'='*60}")
run_fixes(v30_path, fix_gripper_flag=not args.no_fix_gripper)
# ── Step 3: v3.0 β†’ v2.1 ──────────────────────────────────────────────────
if args.no_v21:
print("\nStep 3: Skipped (--no_v21)")
else:
print(f"\n{'='*60}")
print("Step 3: v3.0 β†’ v2.1")
print(f"{'='*60}")
v21_path = convert_v30_to_v21(v30_path)
print(f" βœ“ v2.1 dataset saved to: {v21_path}")
print(f"\n{'='*60}")
print("Pipeline complete!")
print(f" v3.0: {v30_path}")
if not args.no_v21:
print(f" v2.1: {v30_path.parent / (v30_path.name + '_v21')}")
print(f"{'='*60}\n")
# ══════════════════════════════════════════════════════════════════════════════
# Entry point
# ══════════════════════════════════════════════════════════════════════════════
def main():
parser = argparse.ArgumentParser(
description="Unified MCAP β†’ LeRobot pipeline (v3.0 + fix + v2.1)",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# ── required ──────────────────────────────────────────────────────────────
parser.add_argument("--task", type=str, required=True,
help="Task name (key in tasks_json_path)")
parser.add_argument("--robot_type", type=str, required=True,
help="Robot type: 'arx' or 'piper'")
# ── paths ─────────────────────────────────────────────────────────────────
parser.add_argument("--tasks_json_path", type=str, default=TASKS_JSON_PATH,
help="Path to tasks JSON mapping task names to episode folders")
parser.add_argument("--dataset_root", type=str, default=DATASET_ROOT,
help="Root directory containing raw MCAP episode folders")
parser.add_argument("--final_dataset_repo_root", type=str, default="we_d900",
help="Subdirectory under HF_LEROBOT_HOME for the output dataset")
# ── conversion mode ───────────────────────────────────────────────────────
parser.add_argument("--mode", type=str, default="full", choices=["full", "dagger"],
help="'full' = full episode per MCAP; 'dagger' = teleop segments only")
parser.add_argument("--num_process", type=int, default=1,
help="Number of parallel worker processes")
# ── full mode options ─────────────────────────────────────────────────────
parser.add_argument("--hil_filter", action="store_true",
help="[full mode] Keep only INFERENCE+TELEOP frames (HIL filtering)")
parser.add_argument("--action_types", type=str, nargs="+", default=None,
help="[full mode] Custom action types to keep (overrides --hil_filter)")
# ── dagger mode options ───────────────────────────────────────────────────
parser.add_argument("--min_segment_length", type=int, default=10,
help="[dagger mode] Minimum teleop segment length (frames)")
parser.add_argument("--action_threshold", type=float, default=10.0,
help="[dagger mode] Discard segments with max|action| above this value")
# ── fix options ───────────────────────────────────────────────────────────
parser.add_argument("--no_fix_gripper", action="store_true",
help="Disable auto gripper rescaling. By default the script detects "
"files with gripper in [0,0.08] range and rescales to [0,1] automatically.")
# ── output options ────────────────────────────────────────────────────────
parser.add_argument("--no_v21", action="store_true",
help="Skip v2.1 conversion (keep v3.0 only)")
args = parser.parse_args()
run_pipeline(args)
if __name__ == "__main__":
main()