openpi / scripts /lerobot_preprocess_mesh_only.py
zhicao's picture
Upload folder using huggingface_hub
e4eb88a verified
Raw
History Blame Contribute Delete
6.07 kB
#!/usr/bin/env python3
"""
Reprocess LIBERO LeRobot dataset to mesh-only tracks using simulator vertices.
This script keeps core fields (image, wrist_image, state, actions, task) and writes
only mesh-point tracks for both views, using per-task BDDL dynamic gripper selection.
"""
from __future__ import annotations
import openpi.shared.local_cache_bootstrap # noqa: F401
import argparse
import os
import shutil
import sys
from pathlib import Path
import numpy as np
from lerobot.common.datasets.lerobot_dataset import LeRobotDataset
import lerobot_preprocess_cotracker as cot
def _build_features() -> dict[str, dict]:
return {
"image": {"dtype": "image", "shape": (256, 256, 3), "names": ["height", "width", "channel"]},
"wrist_image": {"dtype": "image", "shape": (256, 256, 3), "names": ["height", "width", "channel"]},
"state": {"dtype": "float32", "shape": (8,), "names": ["state"]},
"actions": {"dtype": "float32", "shape": (7,), "names": ["actions"]},
"agentview_tracks": {"dtype": "float32", "shape": (7, 2), "names": ["points", "xy"]},
"agentview_vis": {"dtype": "float32", "shape": (7,), "names": ["points"]},
"wrist_tracks": {"dtype": "float32", "shape": (7, 2), "names": ["points", "xy"]},
"wrist_vis": {"dtype": "float32", "shape": (7,), "names": ["points"]},
"agentview_mesh_vertices_2d": {"dtype": "float32", "shape": (7, 2), "names": ["points", "xy"]},
"wrist_mesh_vertices_2d": {"dtype": "float32", "shape": (7, 2), "names": ["points", "xy"]},
"has_track_mesh": {"dtype": "float32", "shape": (1,), "names": ["flag"]},
}
def process_episode(ds: LeRobotDataset, ep_idx: int):
bnds = cot._episode_bounds(ds, ep_idx)
scene = cot._scene_from_task(bnds.task)
frames = []
for i in range(bnds.start, bnds.end):
row = ds[i]
frames.append(
(
cot._to_hwc_uint8(np.asarray(row["image"])),
cot._to_hwc_uint8(np.asarray(row["wrist_image"])),
np.asarray(row["state"], dtype=np.float32),
np.asarray(row["actions"], dtype=np.float32),
row["task"],
)
)
images = np.stack([f[0] for f in frames], axis=0)
wrist_images = np.stack([f[1] for f in frames], axis=0)
states = np.stack([f[2] for f in frames], axis=0)
actions = np.stack([f[3] for f in frames], axis=0)
task = frames[0][4]
agent_mesh_seq, wrist_mesh_seq = cot._get_mesh_sequence_from_sim(
scene,
states[0],
actions,
task_name=task,
img_hw=(images.shape[1], images.shape[2]),
)
T = min(images.shape[0], agent_mesh_seq.shape[0], wrist_mesh_seq.shape[0])
for t in range(T):
yield {
"image": images[t],
"wrist_image": wrist_images[t],
"state": states[t],
"actions": actions[t],
"task": task,
"agentview_tracks": agent_mesh_seq[t],
"agentview_vis": np.ones((7,), dtype=np.float32),
"wrist_tracks": wrist_mesh_seq[t],
"wrist_vis": np.ones((7,), dtype=np.float32),
"agentview_mesh_vertices_2d": agent_mesh_seq[t],
"wrist_mesh_vertices_2d": wrist_mesh_seq[t],
"has_track_mesh": np.asarray([1.0], dtype=np.float32),
}
def main():
p = argparse.ArgumentParser(description="Reprocess LIBERO to mesh-only (both views, dynamic BDDL).")
p.add_argument("--source-repo-id", default="/mnt/kevin/data/physical-intelligence/libero")
p.add_argument("--target-repo-id", default="/mnt/kevin/data/physical-intelligence/libero_mesh_only_dynamic")
p.add_argument("--overwrite", action="store_true")
p.add_argument("--max-episodes", type=int, default=None)
p.add_argument("--start-episode", type=int, default=0)
p.add_argument("--end-episode", type=int, default=None)
p.add_argument("--libero-root", type=str, default=None)
p.add_argument("--libero-data", type=str, default=None)
p.add_argument(
"--extra-libero-path",
type=str,
default="/mnt/kevin/code/wmrl/howard-branch/openpi/third_party/libero/libero",
)
args = p.parse_args()
cot.EXTRA_LIBERO_PATH = args.extra_libero_path
if args.libero_root and (Path(args.libero_root) / "libero" / "envs" / "mesh_vertex_wrapper.py").exists():
cot.EXTRA_LIBERO_PATH = args.libero_root
for pth in [args.libero_root, args.extra_libero_path]:
if not pth:
continue
candidates = [Path(pth), Path(pth) / "libero"]
for cand in candidates:
s = str(cand)
if cand.exists() and s not in sys.path:
sys.path.insert(0, s)
if args.libero_data:
os.environ.setdefault("LIBERO_PATH", args.libero_data)
os.environ.setdefault("MUJOCO_GL", "egl")
os.environ.setdefault("PYOPENGL_PLATFORM", "egl")
src = LeRobotDataset(args.source_repo_id)
total_eps = len(src.meta.episodes)
start_ep = max(0, int(args.start_episode))
end_ep = total_eps if args.end_episode is None else min(int(args.end_episode), total_eps)
if args.max_episodes is not None:
end_ep = min(end_ep, start_ep + int(args.max_episodes))
if end_ep <= start_ep:
raise ValueError(f"Invalid episode range [{start_ep}, {end_ep})")
target_path = Path(args.target_repo_id)
if target_path.exists() and args.overwrite:
shutil.rmtree(target_path)
dst = LeRobotDataset.create(
repo_id=str(target_path),
robot_type="panda",
fps=src.fps,
features=_build_features(),
image_writer_threads=10,
image_writer_processes=5,
)
for ep_idx in range(start_ep, end_ep):
print(f"[ep {ep_idx-start_ep}/{end_ep-start_ep}] abs={ep_idx}")
for frame in process_episode(src, ep_idx):
dst.add_frame(frame)
dst.save_episode()
print(f"Done. Wrote {end_ep-start_ep} episodes ({start_ep}:{end_ep}) to {target_path}")
if __name__ == "__main__":
main()