Download droid/scripts/preprocess_chunk.py from zhicao/openpi: direct link, hf CLI and curl.
- Browser
- Download file 9.45 kB
-
https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/preprocess_chunk.py
- Command line
-
hf download hf://datasets/zhicao/openpi/droid/scripts/preprocess_chunk.py
-
curl -L -o preprocess_chunk.py https://huggingface.co/datasets/zhicao/openpi/resolve/main/droid/scripts/preprocess_chunk.py
9.45 kB
| #!/usr/bin/env python3 | |
| """ | |
| Process a specific chunk of DROID episodes. | |
| Reads chunk file with episode indices and processes only those episodes. | |
| """ | |
| import json | |
| from pathlib import Path | |
| import tensorflow_datasets as tfds | |
| from tqdm import tqdm | |
| import torch | |
| import numpy as np | |
| import cv2 | |
| from droid.calibration.calibration_loader import CalibrationLoader | |
| from droid.misc.projector import Projector | |
| # Import preprocessing functions from the main script | |
| import sys | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| # Copy necessary functions | |
| def find_closest_calibration(episode, uuid_list): | |
| """Find closest calibration UUID by timestamp.""" | |
| ts = float(episode['episode_metadata']['recording_timestamp'].numpy()) | |
| closest_uuid = None | |
| min_diff = float('inf') | |
| for uuid, calib_ts in uuid_list: | |
| diff = abs(ts - calib_ts) | |
| if diff < min_diff: | |
| min_diff = diff | |
| closest_uuid = uuid | |
| return closest_uuid | |
| def sample_arm_shaped_points(mesh_2d_visible, img_h, img_w, num_points=993, seed=0): | |
| """Sample points in arm-shaped region excluding mesh vertices.""" | |
| np.random.seed(seed) | |
| u_coords = [] | |
| v_coords = [] | |
| mesh_u = mesh_2d_visible[:, 0] | |
| mesh_v = mesh_2d_visible[:, 1] | |
| u_min = max(0, int(mesh_u.min()) - 50) | |
| u_max = min(img_w, int(mesh_u.max()) + 50) | |
| v_min = max(0, int(mesh_v.min()) - 50) | |
| v_max = min(img_h, int(mesh_v.max()) + 50) | |
| attempts = 0 | |
| max_attempts = num_points * 100 | |
| while len(u_coords) < num_points and attempts < max_attempts: | |
| u = np.random.randint(u_min, u_max) | |
| v = np.random.randint(v_min, v_max) | |
| # Check distance from mesh vertices | |
| dists = np.sqrt((mesh_u - u)**2 + (mesh_v - v)**2) | |
| if dists.min() > 10: | |
| u_coords.append(u) | |
| v_coords.append(v) | |
| attempts += 1 | |
| if len(u_coords) < num_points: | |
| remaining = num_points - len(u_coords) | |
| u_coords.extend([img_w // 2] * remaining) | |
| v_coords.extend([img_h // 2] * remaining) | |
| return np.array(u_coords), np.array(v_coords) | |
| def sample_wrist_points(img_h, img_w, num_sparse=300, num_dense=700, seed=0): | |
| """Sample wrist camera points with dense sampling in bottom region.""" | |
| np.random.seed(seed) | |
| # Sparse uniform sampling | |
| u_sparse = np.random.randint(0, img_w, num_sparse) | |
| v_sparse = np.random.randint(0, img_h, num_sparse) | |
| # Dense sampling in bottom 60%-100% | |
| v_min_dense = int(img_h * 0.6) | |
| u_dense = np.random.randint(0, img_w, num_dense) | |
| v_dense = np.random.randint(v_min_dense, img_h, num_dense) | |
| u_all = np.concatenate([u_sparse, u_dense]) | |
| v_all = np.concatenate([v_sparse, v_dense]) | |
| return u_all, v_all | |
| def load_cotracker(): | |
| """Load CoTracker v3 offline model.""" | |
| from cotracker.predictor import CoTrackerPredictor | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| cotracker_paths = [ | |
| '/mnt/kevin/vlm_models/cotracker/scaled_offline.pth', | |
| '/mnt/kevin/vlm_models/hub/checkpoints/scaled_offline.pth', | |
| '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/co-tracker/checkpoints/scaled_offline.pth', | |
| ] | |
| cotracker_checkpoint = None | |
| for path in cotracker_paths: | |
| if Path(path).exists(): | |
| cotracker_checkpoint = path | |
| print(f"Found CoTracker checkpoint: {cotracker_checkpoint}") | |
| break | |
| if cotracker_checkpoint is None: | |
| raise FileNotFoundError(f"CoTracker checkpoint not found. Tried:\n" + "\n".join(cotracker_paths)) | |
| cotracker = CoTrackerPredictor(checkpoint=cotracker_checkpoint) | |
| cotracker = cotracker.to(device) | |
| cotracker.eval() | |
| return cotracker, device | |
| def process_episode(episode, episode_idx, uuid, calib_loader, projector, cotracker, device, | |
| max_frames=400, save_preview=False, output_dir=None): | |
| """Process a single episode.""" | |
| # ... [Copy full function from preprocess_droid_rlds_final.py] | |
| # I'll use the existing implementation | |
| from preprocess_droid_rlds_final import process_episode as original_process_episode | |
| return original_process_episode( | |
| episode, episode_idx, uuid, calib_loader, projector, cotracker, device, | |
| max_frames, save_preview, output_dir | |
| ) | |
| def main(): | |
| import argparse | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--chunk-file', type=str, required=True, | |
| help='Chunk JSON file with episode indices to process') | |
| parser.add_argument('--output-dir', type=str, default='/mnt/kevin/data/droid_processed_1000pts', | |
| help='Output directory') | |
| parser.add_argument('--max-frames', type=int, default=400, | |
| help='Max frames per episode') | |
| parser.add_argument('--save-previews', type=int, default=3, | |
| help='Number of preview videos to save') | |
| parser.add_argument('--chunk-id', type=int, default=None, | |
| help='Chunk ID for logging') | |
| args = parser.parse_args() | |
| # Load chunk data | |
| with open(args.chunk_file) as f: | |
| chunk_data = json.load(f) | |
| chunk_id = chunk_data['chunk_id'] if args.chunk_id is None else args.chunk_id | |
| episode_indices_set = set(chunk_data['episode_indices']) | |
| label = f"Chunk {chunk_id}" | |
| print("="*80) | |
| print(f"DROID Preprocessing: {label}") | |
| print("="*80) | |
| print(f" Chunk file: {args.chunk_file}") | |
| print(f" Episodes to process: {len(episode_indices_set)}") | |
| print(f" Output: {args.output_dir}") | |
| print("="*80) | |
| # Setup output directories | |
| output_dir = Path(args.output_dir) | |
| data_dir = output_dir / 'data' | |
| preview_dir = output_dir / 'preview_videos' | |
| data_dir.mkdir(parents=True, exist_ok=True) | |
| preview_dir.mkdir(parents=True, exist_ok=True) | |
| # Load CoTracker | |
| cotracker, device = load_cotracker() | |
| # Load camera calibrations | |
| calib_loader = CalibrationLoader() | |
| uuid_list = [(uuid, calib_loader.get_timestamp(uuid)) | |
| for uuid in calib_loader.list_calibrations()] | |
| print(f"Loaded {len(uuid_list)} camera calibrations") | |
| # Setup projector | |
| projector = Projector() | |
| # Load dataset | |
| droid_path = '/mnt/kevin/data/droid/droid/1.0.0' | |
| print("Loading DROID dataset...") | |
| builder = tfds.builder_from_directory(droid_path) | |
| dataset = builder.as_dataset(split='train') | |
| # Process only episodes in chunk | |
| processed_count = 0 | |
| skipped_count = 0 | |
| preview_count = 0 | |
| pbar = tqdm(total=len(episode_indices_set), desc=label) | |
| for episode_idx, episode in enumerate(dataset): | |
| # Skip episodes not in this chunk | |
| if episode_idx not in episode_indices_set: | |
| continue | |
| # Check if already processed | |
| npz_path = data_dir / f"episode_{episode_idx:06d}.npz" | |
| if npz_path.exists(): | |
| processed_count += 1 | |
| pbar.update(1) | |
| continue | |
| # Find calibration | |
| uuid = find_closest_calibration(episode, uuid_list) | |
| if uuid is None or not calib_loader.has_refined_extrinsics(uuid): | |
| skipped_count += 1 | |
| episode_indices_set.remove(episode_idx) | |
| pbar.update(1) | |
| continue | |
| # Process episode | |
| try: | |
| save_preview = (preview_count < args.save_previews) | |
| result = process_episode( | |
| episode, episode_idx, uuid, calib_loader, projector, | |
| cotracker, device, args.max_frames, save_preview, output_dir | |
| ) | |
| if result is not None: | |
| # Save as NPZ | |
| np.savez_compressed( | |
| npz_path, | |
| episode_idx=result['episode_idx'], | |
| tracked_points_exterior=result['tracks_exterior'], | |
| tracked_points_wrist=result['tracks_wrist'], | |
| tracks_vis_exterior=result['tracks_vis_exterior'], | |
| tracks_vis_wrist=result['tracks_vis_wrist'], | |
| images_exterior=result['images_exterior'], | |
| images_wrist=result['images_wrist'], | |
| actions=result['actions'], | |
| uuid=uuid | |
| ) | |
| processed_count += 1 | |
| if save_preview: | |
| preview_count += 1 | |
| else: | |
| skipped_count += 1 | |
| except Exception as e: | |
| print(f"\nError processing episode {episode_idx}: {e}") | |
| skipped_count += 1 | |
| pbar.update(1) | |
| # Early exit if all episodes processed | |
| if processed_count + skipped_count >= len(chunk_data['episode_indices']): | |
| break | |
| pbar.close() | |
| # Save metadata | |
| metadata = { | |
| 'chunk_id': chunk_id, | |
| 'chunk_file': str(args.chunk_file), | |
| 'processed': processed_count, | |
| 'skipped': skipped_count, | |
| 'total': len(chunk_data['episode_indices']) | |
| } | |
| metadata_path = output_dir / f'metadata_chunk_{chunk_id:02d}.json' | |
| with open(metadata_path, 'w') as f: | |
| json.dump(metadata, f, indent=2) | |
| print("\n" + "="*80) | |
| print("Preprocessing Complete") | |
| print("="*80) | |
| print(f" Processed: {processed_count} episodes") | |
| print(f" Skipped: {skipped_count} episodes") | |
| print(f" Preview videos: {preview_dir}") | |
| print(f" NPZ data: {data_dir}") | |
| print(f" Metadata: {metadata_path}") | |
| print("="*80) | |
| if __name__ == '__main__': | |
| main() | |