| """ |
| Preprocess DROID Dataset for ControlNet Training |
| |
| Generates 32-point tracks (25 grid + 7 mesh) for DROID episodes using: |
| - Camera parameters from raw metadata_*.json (uuid-matched) |
| - Franka mesh projection via forward kinematics |
| - Data source: local LeRobot dataset |
| |
| Example:: |
| |
| python preprocess_droid_tracks.py \\ |
| --lerobot-root /path/to/lerobot_dataset \\ |
| --raw-data-root /path/to/raw_droid \\ |
| --calib-dir /path/to/cameras \\ |
| --output /path/to/out_npz |
| """ |
|
|
| from __future__ import annotations |
| import os |
| import sys |
| from pathlib import Path |
|
|
|
|
| def _ensure_droid_main_on_syspath() -> Path: |
| """Prepend the directory that contains ``utils/`` to ``sys.path`` (for ``import utils.*``). |
| |
| Uses ``$DROID_MAIN_ROOT`` when it exists and contains ``utils/``; otherwise this script's |
| parent directory (the ``droid/`` folder in this repo). |
| """ |
| default_root = Path(__file__).resolve().parent.parent |
| env = os.environ.get("DROID_MAIN_ROOT", "").strip() |
| if env: |
| alt = Path(env).expanduser().resolve() |
| root = alt if (alt / "utils").is_dir() else default_root |
| else: |
| root = default_root |
| p = str(root) |
| if p not in sys.path: |
| sys.path.insert(0, p) |
| return root |
|
|
|
|
| _ensure_droid_main_on_syspath() |
|
|
| import argparse |
| import json |
| import re |
| from typing import Any, Dict, List, Optional, Tuple |
| import cv2 |
| import numpy as np |
| import torch |
| from scipy.spatial.transform import Rotation as R |
| from tqdm import tqdm |
| from cotracker.predictor import CoTrackerPredictor |
| from lerobot.common.datasets.lerobot_dataset import LeRobotDataset |
| from utils.franka_mesh_projection import FrankaMeshProjector |
|
|
|
|
| def _normalize_task(text: str) -> str: |
| return re.sub(r"[^a-z0-9]+", " ", str(text).lower()).strip() |
|
|
|
|
| def _scale_intrinsics(K: np.ndarray, ref_hw: Tuple[int, int], new_hw: Tuple[int, int]) -> np.ndarray: |
| """Scale pinhole K from reference (H_ref, W_ref) to new (H_new, W_new).""" |
| href, wref = ref_hw |
| hnew, wnew = new_hw |
| Ks = np.array(K, dtype=np.float64, copy=True) |
| sx = wnew / float(wref) |
| sy = hnew / float(href) |
| Ks[0, 0] *= sx |
| Ks[0, 2] *= sx |
| Ks[1, 1] *= sy |
| Ks[1, 2] *= sy |
| return Ks |
|
|
|
|
| def _image_to_uint8_hwc(img: Any, *, expect_rgb: bool) -> np.ndarray: |
| """LeRobot / torch -> HWC uint8.""" |
| if hasattr(img, "detach"): |
| img = img.detach().cpu().numpy() |
| else: |
| img = np.asarray(img) |
| if img.ndim == 3 and img.shape[0] in (1, 3) and img.shape[-1] not in (1, 3, 4): |
| |
| img = np.transpose(img, (1, 2, 0)) |
| if np.issubdtype(img.dtype, np.floating): |
| img = np.clip(img, 0.0, 1.0) |
| img = (img * 255.0).astype(np.uint8) |
| else: |
| img = img.astype(np.uint8) |
| if not expect_rgb and img.shape[-1] == 3: |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
| return np.ascontiguousarray(img) |
|
|
|
|
| def build_uuid_lookup_from_raw( |
| raw_data_root: Path, |
| annotations: Optional[Dict[str, Any]], |
| ) -> Dict[Tuple[int, str], str]: |
| """ |
| Map (trajectory_length, normalized_language) -> uuid using per-episode metadata JSON. |
| |
| Used to align LeRobot episodes (length + task string) with raw DROID calibration uuid. |
| """ |
| lookup: Dict[Tuple[int, str], str] = {} |
| for meta_path in sorted(raw_data_root.glob("**/metadata_*.json")): |
| with meta_path.open() as f: |
| m = json.load(f) |
| uuid = m.get("uuid") |
| if not uuid: |
| continue |
| length = int(m.get("trajectory_length", -1)) |
| if length < 0: |
| continue |
| if annotations is not None and uuid in annotations: |
| lang = annotations[uuid].get("language_instruction1", "") |
| else: |
| lang = str(m.get("current_task", "")).split("\n")[0] |
| key = (length, _normalize_task(lang)) |
| if key in lookup and lookup[key] != uuid: |
| raise ValueError( |
| f"Ambiguous uuid lookup for key {key}: {lookup[key]} vs {uuid} " |
| f"(metadata files collide on length+language — check raw_data_root)." |
| ) |
| lookup[key] = uuid |
| return lookup |
|
|
|
|
| def _task_token_similarity(lerobot_task: str, candidate_text: str) -> float: |
| a = set(_normalize_task(lerobot_task).split()) |
| b = set(_normalize_task(candidate_text).split()) |
| if not a or not b: |
| return 0.0 |
| return len(a & b) / max(1, len(a | b)) |
|
|
|
|
| def build_uuid_resolution_tables( |
| raw_data_root: Path, |
| annotations: Optional[Dict[str, Any]], |
| *, |
| episode_order_sorted: bool, |
| ) -> tuple[ |
| Dict[Tuple[int, str], str], |
| Dict[int, str], |
| List[Tuple[str, int]], |
| Dict[str, str], |
| Dict[int, List[str]], |
| ]: |
| """ |
| Returns: |
| - lookup (length, norm_task) -> uuid |
| - unique_by_length: trajectory_length -> uuid when exactly one episode has that length in metadata |
| - episode_order: [(uuid, trajectory_length), ...] in the same discovery order as convert_droid_data_to_lerobot |
| - uuid_to_langtext: uuid -> raw language string for similarity |
| - uuids_by_length: trajectory_length -> list of uuids (for similarity tie-break) |
| """ |
| from collections import defaultdict |
|
|
| lookup = build_uuid_lookup_from_raw(raw_data_root, annotations) |
| by_len_sets: defaultdict[int, set[str]] = defaultdict(set) |
| uuid_to_langtext: Dict[str, str] = {} |
|
|
| for meta_path in raw_data_root.glob("**/metadata_*.json"): |
| with meta_path.open() as f: |
| m = json.load(f) |
| uuid = m.get("uuid") |
| if not uuid: |
| continue |
| L = int(m.get("trajectory_length", -1)) |
| if L < 0: |
| continue |
| by_len_sets[L].add(uuid) |
| if annotations is not None and uuid in annotations: |
| uuid_to_langtext[uuid] = str(annotations[uuid].get("language_instruction1", "")) |
| else: |
| uuid_to_langtext[uuid] = str(m.get("current_task", "")).split("\n")[0] |
|
|
| uuids_by_length: Dict[int, List[str]] = {L: list(s) for L, s in by_len_sets.items()} |
| unique_by_length = {length: us[0] for length, us in uuids_by_length.items() if len(us) == 1} |
|
|
| traj_paths = list(raw_data_root.glob("**/trajectory.h5")) |
| if episode_order_sorted: |
| traj_paths = sorted(traj_paths) |
| episode_order: List[Tuple[str, int]] = [] |
| if traj_paths: |
| for tp in traj_paths: |
| parent = tp.parent |
| metas = list(parent.glob("metadata_*.json")) |
| if not metas: |
| continue |
| meta_path = min(metas, key=lambda p: p.name) |
| with meta_path.open() as f: |
| m = json.load(f) |
| uuid = m.get("uuid") |
| if not uuid: |
| continue |
| episode_order.append((uuid, int(m.get("trajectory_length", -1)))) |
| else: |
| meta_paths = sorted(raw_data_root.glob("**/metadata_*.json")) if episode_order_sorted else list( |
| raw_data_root.glob("**/metadata_*.json") |
| ) |
| for meta_path in meta_paths: |
| with meta_path.open() as f: |
| m = json.load(f) |
| uuid = m.get("uuid") |
| if not uuid: |
| continue |
| episode_order.append((uuid, int(m.get("trajectory_length", -1)))) |
|
|
| return lookup, unique_by_length, episode_order, uuid_to_langtext, uuids_by_length |
|
|
|
|
| def lerobot_episode_bounds(ds: Any, ep_idx: int) -> Tuple[int, int, str]: |
| ep_from = int(ds.episode_data_index["from"][ep_idx]) |
| ep_to = int(ds.episode_data_index["to"][ep_idx]) |
| task = ds.meta.episodes[ep_idx]["tasks"][0] |
| return ep_from, ep_to, task |
|
|
|
|
| def _resolve_default_cotracker_checkpoint() -> Optional[str]: |
| candidates = [ |
| os.environ.get("COTRACKER_CHECKPOINT", "").strip(), |
| "/scratch1/home/zhicao/openpi/co-tracker/checkpoints/scaled_offline.pth", |
| "/scratch1/home/zhicao/co-tracker/checkpoints/scaled_offline.pth", |
| "/scratch1/home/zhicao/cotracker/checkpoints/scaled_offline.pth", |
| ] |
| for p in candidates: |
| if p and Path(p).is_file(): |
| return p |
| return None |
|
|
|
|
| def _se3_vector_to_matrix(xyz_euler6: np.ndarray) -> np.ndarray: |
| """ |
| Build 4x4 world->camera transform from [tx,ty,tz,rx,ry,rz] where r is XYZ Euler. |
| """ |
| x = np.asarray(xyz_euler6, dtype=np.float64).reshape(-1) |
| if x.size < 6: |
| raise ValueError(f"Extrinsics vector must have >=6 values, got shape={x.shape}") |
| t_world = x[:3] |
| euler = x[3:6] |
| R_wc = R.from_euler("xyz", euler).as_matrix() |
| R_cw = R_wc.T |
| t_c = -R_cw @ t_world |
| T = np.eye(4, dtype=np.float64) |
| T[:3, :3] = R_cw |
| T[:3, 3] = t_c |
| return T |
|
|
|
|
| def _run_cotracker( |
| cotracker: Any, |
| *, |
| frames_rgb: np.ndarray, |
| query_points_xy: np.ndarray, |
| device: torch.device, |
| ) -> tuple[np.ndarray, np.ndarray]: |
| """ |
| Run CoTracker on one video. |
| |
| Args: |
| frames_rgb: [T, H, W, 3] uint8 |
| query_points_xy: [N, 2] pixel coordinates on frame 0 |
| Returns: |
| tracks: [T, N, 2] in pixel coords |
| vis: [T, N] bool-like (float32 0/1) |
| """ |
| if frames_rgb.ndim != 4 or frames_rgb.shape[-1] != 3: |
| raise ValueError(f"frames_rgb must be [T,H,W,3], got {frames_rgb.shape}") |
| video = torch.from_numpy(frames_rgb).float().permute(0, 3, 1, 2) / 255.0 |
| video = video.unsqueeze(0).to(device) |
| queries = np.zeros((query_points_xy.shape[0], 3), dtype=np.float32) |
| queries[:, 0] = 0.0 |
| queries[:, 1:] = query_points_xy.astype(np.float32) |
| queries_t = torch.from_numpy(queries).unsqueeze(0).to(device) |
| with torch.no_grad(): |
| tracks, vis = cotracker(video, queries=queries_t, backward_tracking=False) |
| return tracks[0].detach().cpu().numpy(), vis[0].detach().cpu().numpy() |
|
|
|
|
| class DROIDTrackPreprocessor: |
| """Preprocess DROID episodes to generate 32-point tracks.""" |
| def __init__( |
| self, |
| *, |
| lerobot_root: Optional[str], |
| raw_data_root: Optional[str], |
| annotations_path: Optional[str], |
| calib_path: str, |
| output_path: str, |
| min_len: int = 16, |
| max_len: int = 70, |
| max_episodes: int = 20000, |
| use_cartesian: bool = True, |
| require_refined: bool = True, |
| img_size: int = 448, |
| intrinsic_ref_hw: Tuple[int, int] = (360, 640), |
| cotracker_checkpoint: Optional[str] = None, |
| cotracker_device: str = "cuda:0", |
| episode_order_sorted: bool = False, |
| ): |
| self.source = "lerobot" |
| self.output_path = Path(output_path) |
| self.min_len = min_len |
| self.max_len = max_len |
| self.max_episodes = max_episodes |
| self.use_cartesian = use_cartesian |
| self.require_refined = require_refined |
| self.img_size = int(img_size) |
| self.intrinsic_ref_hw = intrinsic_ref_hw |
| self.episode_order_sorted = episode_order_sorted |
| self.output_path.mkdir(parents=True, exist_ok=True) |
| self.projector = FrankaMeshProjector(use_gui=False) |
| |
| |
| |
| self.cotracker_device = torch.device( |
| cotracker_device if cotracker_device.startswith("cuda") and torch.cuda.is_available() else "cpu" |
| ) |
| ckpt = cotracker_checkpoint or _resolve_default_cotracker_checkpoint() |
| if not ckpt or not Path(ckpt).is_file(): |
| raise FileNotFoundError( |
| "CoTracker checkpoint not found. Pass --cotracker-checkpoint or set COTRACKER_CHECKPOINT." |
| ) |
| print(f"Loading CoTracker from: {ckpt}") |
| self.cotracker = CoTrackerPredictor(checkpoint=ckpt).to(self.cotracker_device) |
| self.cotracker.eval() |
| |
| |
| |
| self.lerobot_ds = None |
| if not lerobot_root: |
| raise ValueError("lerobot_root is required.") |
| if not raw_data_root: |
| raise ValueError("raw_data_root is required.") |
| root = Path(lerobot_root) |
| self.raw_data_root = Path(raw_data_root) |
| print(f"Loading LeRobot dataset from {root}...") |
| self.lerobot_ds = LeRobotDataset(str(root)) |
| |
|
|
| |
| self.annotations: Optional[Dict[str, Any]] = None |
| ann_path = Path(annotations_path) if annotations_path else Path(raw_data_root) / "aggregated-annotations-030724.json" |
| if ann_path.is_file(): |
| with ann_path.open() as f: |
| self.annotations = json.load(f) |
| print(f"Loaded language annotations: {ann_path}") |
| else: |
| print(f"No annotations file at {ann_path}; using current_task from metadata only.") |
|
|
|
|
| |
| self.uuid_lookup: Dict[Tuple[int, str], str] = {} |
| self.uuid_unique_by_length: Dict[int, str] = {} |
| self.uuid_episode_order: List[Tuple[str, int]] = [] |
| self.uuid_to_langtext: Dict[str, str] = {} |
| self.uuids_by_length: Dict[int, List[str]] = {} |
| ( |
| self.uuid_lookup, |
| self.uuid_unique_by_length, |
| self.uuid_episode_order, |
| self.uuid_to_langtext, |
| self.uuids_by_length, |
| ) = build_uuid_resolution_tables( |
| Path(raw_data_root), |
| self.annotations, |
| episode_order_sorted=self.episode_order_sorted, |
| ) |
| print(f"Built uuid lookup with {len(self.uuid_lookup)} (length, task) keys under {raw_data_root}") |
| print(f" Unique-by-length uuid slots: {len(self.uuid_unique_by_length)}") |
| print(f" Episode-order pairs (trajectory.h5 or metadata glob): {len(self.uuid_episode_order)}") |
|
|
| self.uuid_to_metadata_path = self._build_uuid_to_metadata_path(self.raw_data_root) |
| print(f"Built uuid->metadata index with {len(self.uuid_to_metadata_path)} entries") |
|
|
|
|
| def _scaled_dual_params(self, dual_params: Dict[str, Any]) -> Dict[str, Any]: |
| """Apply intrinsics scaling to match resized square images.""" |
| h_new = w_new = self.img_size |
| href, wref = self.intrinsic_ref_hw |
| out = {} |
| for name, (K, E) in dual_params.items(): |
| Ks = _scale_intrinsics(np.asarray(K), (href, wref), (h_new, w_new)) |
| out[name] = (Ks, np.asarray(E)) |
| return out |
|
|
| def _default_intrinsics(self) -> np.ndarray: |
| href, wref = self.intrinsic_ref_hw |
| cx = (wref - 1.0) / 2.0 |
| cy = (href - 1.0) / 2.0 |
| |
| fx = 0.9 * float(wref) |
| fy = 0.9 * float(href) |
| return np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]], dtype=np.float64) |
|
|
| @staticmethod |
| def _build_uuid_to_metadata_path(raw_data_root: Path) -> Dict[str, Path]: |
| out: Dict[str, Path] = {} |
| for meta_path in raw_data_root.glob("**/metadata_*.json"): |
| try: |
| with meta_path.open() as f: |
| m = json.load(f) |
| except Exception: |
| continue |
| uuid = str(m.get("uuid", "")).strip() |
| if uuid and uuid not in out: |
| out[uuid] = meta_path |
| return out |
|
|
| def _dual_params_from_raw_metadata(self, uuid: str) -> Optional[Dict[str, Tuple[np.ndarray, np.ndarray]]]: |
| meta_path = self.uuid_to_metadata_path.get(uuid) |
| if meta_path is None: |
| return None |
| with meta_path.open() as f: |
| m = json.load(f) |
|
|
| ext1_raw = m.get("ext1_cam_extrinsics") |
| wrist_raw = m.get("wrist_cam_extrinsics") |
| if ext1_raw is None or wrist_raw is None: |
| return None |
|
|
| E_ext = _se3_vector_to_matrix(np.asarray(ext1_raw, dtype=np.float64).reshape(-1)) |
| E_wrist = _se3_vector_to_matrix(np.asarray(wrist_raw, dtype=np.float64).reshape(-1)) |
|
|
| |
| K_default = self._default_intrinsics() |
| K_ext = np.asarray(m.get("ext1_cam_intrinsics", K_default), dtype=np.float64).reshape(3, 3) |
| K_wrist = np.asarray(m.get("wrist_cam_intrinsics", K_default), dtype=np.float64).reshape(3, 3) |
| return {"exterior_1": (K_ext, E_ext), "wrist": (K_wrist, E_wrist)} |
| |
|
|
| def _resolve_lerobot_uuid(self, episode_idx: int, num_steps: int, task: str) -> tuple[Optional[str], str]: |
| """ |
| Match LeRobot episode to raw calibration uuid. |
| |
| Order: exact (len+norm task) -> unique trajectory_length in metadata |
| -> token similarity among episodes sharing that length |
| -> episode index order (same glob rule as convert_droid_data_to_lerobot) with length check. |
| """ |
| key = (num_steps, _normalize_task(task)) |
| u = self.uuid_lookup.get(key) |
| if u: |
| return u, "exact" |
| u = self.uuid_unique_by_length.get(num_steps) |
| if u: |
| return u, "unique_len" |
| cands = self.uuids_by_length.get(num_steps, []) |
| if len(cands) > 1: |
| best_u: Optional[str] = None |
| best_s = 0.0 |
| for cu in cands: |
| s = _task_token_similarity(task, self.uuid_to_langtext.get(cu, "")) |
| if s > best_s: |
| best_s, best_u = s, cu |
| if best_u is not None and best_s >= 0.2: |
| return best_u, "similarity" |
| if self.uuid_episode_order and episode_idx < len(self.uuid_episode_order): |
| u2, meta_len = self.uuid_episode_order[episode_idx] |
| if meta_len == num_steps or abs(meta_len - num_steps) <= 2: |
| return u2, "episode_order" |
| return None, "" |
|
|
|
|
| def process_lerobot_episode(self, episode_idx: int) -> bool: |
| ds = self.lerobot_ds |
| ep_from, ep_to, task = lerobot_episode_bounds(ds, episode_idx) |
| num_steps = ep_to - ep_from |
| if num_steps < self.min_len or num_steps > self.max_len: |
| return False |
| uuid, how = self._resolve_lerobot_uuid(episode_idx, num_steps, task) |
| if uuid is None: |
| print(f"Warning: no uuid for ep {episode_idx} len={num_steps} task={task!r}") |
| return False |
| if how != "exact": |
| print(f" ep {episode_idx}: uuid via {how} -> {uuid} (len={num_steps})") |
| try: |
| dual_params = self._dual_params_from_raw_metadata(uuid) |
| if dual_params is None: |
| print(f"Warning: no usable camera params in raw metadata for {uuid}") |
| return False |
| except Exception as e: |
| print(f"Warning: failed reading raw metadata camera params for {uuid}: {e}") |
| return False |
| dual_params = self._scaled_dual_params(dual_params) |
| steps_range = range(ep_from, ep_to) |
| return self._process_steps( |
| num_steps=num_steps, |
| episode_idx=episode_idx, |
| uuid=uuid, |
| dual_params=dual_params, |
| language=task, |
| joint_iter=self._iter_lerobot_frames(ds, steps_range), |
| image_from_bgr=False, |
| ) |
|
|
| def _iter_lerobot_frames(self, ds: Any, steps_range: range): |
| for i in steps_range: |
| row = ds[i] |
| jp = np.asarray(row["joint_position"], dtype=np.float32).reshape(-1) |
| img_ext = _image_to_uint8_hwc(row["exterior_image_1_left"], expect_rgb=True) |
| img_wrist = _image_to_uint8_hwc(row["wrist_image_left"], expect_rgb=True) |
| yield jp, img_ext, img_wrist |
|
|
| def _process_steps( |
| self, |
| *, |
| num_steps: int, |
| episode_idx: int, |
| uuid: str, |
| dual_params: Dict[str, Any], |
| language: str, |
| joint_iter, |
| image_from_bgr: bool, |
| ) -> bool: |
| images_exterior: List[np.ndarray] = [] |
| images_wrist: List[np.ndarray] = [] |
| state0: Optional[np.ndarray] = None |
|
|
| K_ext, E_ext = dual_params["exterior_1"] |
| K_wrist, E_wrist = dual_params["wrist"] |
| h = w = self.img_size |
|
|
| for state, img_ext, img_wrist in joint_iter: |
| if self.use_cartesian and state.shape[0] < 6: |
| return False |
| proj_state = np.asarray(state, dtype=np.float32) |
| if state0 is None: |
| state0 = proj_state |
|
|
| if img_ext is None: |
| img_rgb = np.zeros((h, w, 3), dtype=np.uint8) |
| else: |
| img_rgb = cv2.cvtColor(img_ext, cv2.COLOR_BGR2RGB) if image_from_bgr else np.asarray(img_ext) |
| img_rgb = cv2.resize(img_rgb, (w, h)) |
|
|
| if img_wrist is None: |
| img_wrist_rgb = np.zeros((h, w, 3), dtype=np.uint8) |
| else: |
| img_wrist_rgb = ( |
| cv2.cvtColor(img_wrist, cv2.COLOR_BGR2RGB) if image_from_bgr else np.asarray(img_wrist) |
| ) |
| img_wrist_rgb = cv2.resize(img_wrist_rgb, (w, h)) |
|
|
| images_exterior.append(img_rgb) |
| images_wrist.append(img_wrist_rgb) |
| if not images_exterior or not images_wrist or state0 is None: |
| return False |
|
|
| |
| if self.use_cartesian: |
| proj_fn_e = self.projector.project_32_points_cartesian |
| proj_fn_w = self.projector.project_32_points_cartesian |
| else: |
| proj_fn_e = self.projector.project_32_points |
| proj_fn_w = self.projector.project_32_points |
| query_ext, _ = proj_fn_e(state0, K_ext, E_ext, img_h=h, img_w=w) |
| query_wrist, _ = proj_fn_w(state0, K_wrist, E_wrist, img_h=h, img_w=w) |
|
|
| images_exterior_arr = np.array(images_exterior, dtype=np.uint8) |
| images_wrist_arr = np.array(images_wrist, dtype=np.uint8) |
| tracks_exterior_arr, vis_exterior_arr = _run_cotracker( |
| self.cotracker, |
| frames_rgb=images_exterior_arr, |
| query_points_xy=np.asarray(query_ext, dtype=np.float32), |
| device=self.cotracker_device, |
| ) |
| tracks_wrist_arr, vis_wrist_arr = _run_cotracker( |
| self.cotracker, |
| frames_rgb=images_wrist_arr, |
| query_points_xy=np.asarray(query_wrist, dtype=np.float32), |
| device=self.cotracker_device, |
| ) |
|
|
| output_file = self.output_path / f"episode_{episode_idx:06d}.npz" |
| np.savez_compressed( |
| output_file, |
| tracks_exterior=tracks_exterior_arr, |
| tracks_wrist=tracks_wrist_arr, |
| vis_exterior=vis_exterior_arr, |
| vis_wrist=vis_wrist_arr, |
| images_exterior=images_exterior_arr, |
| images_wrist=images_wrist_arr, |
| language=language, |
| uuid=uuid, |
| num_steps=num_steps, |
| ) |
| return True |
|
|
| def run(self): |
| print("Starting preprocessing:") |
| print(f" Source: {self.source}") |
| print(f" Output: {self.output_path}") |
| print(f" Episode length: [{self.min_len}, {self.max_len}]") |
| print(f" Max episodes: {self.max_episodes}") |
| print(f" Image size: {self.img_size}x{self.img_size} (intrinsics scaled from {self.intrinsic_ref_hw})") |
| print(f" Mesh projection: {'cartesian_position' if self.use_cartesian else 'joint_position (FK)'}") |
| print(f" Require refined extrinsics: {self.require_refined}") |
| print(f" CoTracker device: {self.cotracker_device}") |
| print() |
|
|
| processed = 0 |
| skipped = 0 |
| pbar = tqdm(total=self.max_episodes, desc="Processing episodes") |
|
|
| n_eps = len(self.lerobot_ds.meta.episodes) |
| for idx in range(n_eps): |
| if processed >= self.max_episodes: |
| break |
| try: |
| if self.process_lerobot_episode(idx): |
| processed += 1 |
| pbar.update(1) |
| else: |
| skipped += 1 |
| except Exception as e: |
| print(f"\nError processing LeRobot episode {idx}: {e}") |
| skipped += 1 |
|
|
| pbar.close() |
|
|
| metadata = { |
| "num_processed": processed, |
| "num_skipped": skipped, |
| "source": self.source, |
| "min_len": self.min_len, |
| "max_len": self.max_len, |
| "img_size": self.img_size, |
| "intrinsic_ref_hw": list(self.intrinsic_ref_hw), |
| "num_points": 32, |
| "grid_points": 25, |
| "mesh_points": 7, |
| } |
| metadata_file = self.output_path / "metadata.json" |
| with metadata_file.open("w") as f: |
| json.dump(metadata, f, indent=2) |
|
|
| print(f"\nPreprocessing complete:") |
| print(f" Processed: {processed} episodes") |
| print(f" Skipped: {skipped} episodes") |
| print(f" Output: {self.output_path}") |
| print(f" Metadata: {metadata_file}") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Preprocess DROID tracks for ControlNet training") |
| parser.add_argument( |
| "--lerobot-root", |
| type=str, |
| default="/scratch1/home/zhicao/openpi_org/lerobot_cache/droid_small", |
| help="Root directory of the LeRobot dataset.", |
| ) |
| parser.add_argument( |
| "--raw-data-root", |
| type=str, |
| default="/scratch1/home/zhicao/openpi/data", |
| help="Root of raw DROID data (metadata_*.json per episode) for uuid alignment.", |
| ) |
| parser.add_argument( |
| "--annotations-json", |
| type=str, |
| default="/scratch1/home/zhicao/openpi/data/aggregated-annotations-030724.json", |
| help="Optional aggregated-annotations JSON. If empty, use raw_data_root/aggregated-annotations-030724.json when present.", |
| ) |
| parser.add_argument( |
| "--calib-dir", |
| type=str, |
| default="/scratch1/home/zhicao/openpi/data/cameras", |
| help="Deprecated (kept for backward compatibility; script reads camera params from raw metadata now).", |
| ) |
| parser.add_argument( |
| "--output", |
| type=str, |
| default="/scratch1/home/zhicao/openpi/data_track", |
| help="Output directory for .npz files and metadata.json.", |
| ) |
| parser.add_argument( |
| "--uuid-episode-order-sorted", |
| action="store_true", |
| help="If set, use sorted(glob) for episode order; default False matches convert script list(glob).", |
| ) |
| parser.add_argument("--min-len", type=int, default=16, help="Minimum episode length") |
| parser.add_argument("--max-len", type=int, default=800, help="Maximum episode length (raise for long demos)") |
| parser.add_argument("--max-episodes", type=int, default=20000, help="Max successfully written episodes") |
| parser.add_argument("--img-size", type=int, default=448, help="Square resize (pixels) for images + projection") |
| parser.add_argument( |
| "--intrinsic-ref-h", |
| type=int, |
| default=360, |
| help="Reference intrinsics height (DROID measured K is often for 360p)", |
| ) |
| parser.add_argument( |
| "--intrinsic-ref-w", |
| type=int, |
| default=640, |
| help="Reference intrinsics width", |
| ) |
| parser.add_argument( |
| "--allow-measured-fallback", |
| action="store_true", |
| help=( |
| "If set, allow measured extrinsics fallback when refined_extrinsics is missing. " |
| "Default is strict mode (require refined_extrinsics)." |
| ), |
| ) |
| parser.add_argument( |
| "--cotracker-checkpoint", |
| type=str, |
| default="/scratch1/home/zhicao/openpi/co-tracker/checkpoints/scaled_offline.pth", |
| help="Path to CoTracker checkpoint (.pth). If empty, auto-discover from known paths/env.", |
| ) |
| parser.add_argument( |
| "--cotracker-device", |
| type=str, |
| default="cuda:0", |
| help="CoTracker torch device (e.g. cuda:0 or cpu).", |
| ) |
| args = parser.parse_args() |
|
|
| ann_path = str(args.annotations_json).strip() or None |
|
|
| preprocessor = DROIDTrackPreprocessor( |
| lerobot_root=str(args.lerobot_root).strip(), |
| raw_data_root=str(args.raw_data_root).strip(), |
| annotations_path=ann_path, |
| calib_path=str(args.calib_dir).strip(), |
| output_path=str(args.output).strip(), |
| min_len=args.min_len, |
| max_len=args.max_len, |
| max_episodes=args.max_episodes, |
| use_cartesian=False, |
| require_refined=not args.allow_measured_fallback, |
| img_size=args.img_size, |
| intrinsic_ref_hw=(args.intrinsic_ref_h, args.intrinsic_ref_w), |
| cotracker_checkpoint=args.cotracker_checkpoint.strip() or None, |
| cotracker_device=args.cotracker_device, |
| episode_order_sorted=bool(args.uuid_episode_order_sorted), |
| ) |
| preprocessor.run() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|