| |
| """ |
| Short-MetaWorld Dataset Loader |
| Loads the dataset with proper structure preservation and task prompts. |
| """ |
|
|
| import os |
| import pickle |
| import json |
| import glob |
| from pathlib import Path |
| from PIL import Image |
| import torch |
| import torchvision.transforms as T |
| from torch.utils.data import Dataset |
|
|
| class ShortMetaWorldDataset(Dataset): |
| """ |
| Short-MetaWorld dataset loader that preserves the original structure. |
| |
| Args: |
| data_root (str): Path to the dataset root directory |
| task_list (list): List of tasks to load (default: all available tasks) |
| image_size (int): Target image size for transforms (default: 224) |
| transform (callable): Optional custom transform |
| load_prompts (bool): Whether to load task prompts (default: True) |
| """ |
| |
| def __init__(self, data_root, task_list=None, image_size=224, transform=None, load_prompts=True): |
| self.data_root = Path(data_root) |
| self.image_size = image_size |
| |
| |
| self.prompts = {} |
| if load_prompts: |
| prompt_file = self.data_root / "mt50_task_prompts.json" |
| if prompt_file.exists(): |
| with open(prompt_file, 'r') as f: |
| self.prompts = json.load(f) |
| print(f"📖 Loaded {len(self.prompts)} task prompts") |
| else: |
| print("⚠️ Task prompts not found, using fallback prompts") |
| |
| |
| self.img_root = self.data_root / "short-MetaWorld" / "short-MetaWorld" / "img_only" |
| self.data_pkl_root = self.data_root / "short-MetaWorld" / "r3m-processed" / "r3m_MT10_20" |
| |
| |
| available_tasks = [] |
| if self.data_pkl_root.exists(): |
| for pkl_file in self.data_pkl_root.glob("*.pkl"): |
| task_name = pkl_file.stem |
| if (self.img_root / task_name).exists(): |
| available_tasks.append(task_name) |
| |
| |
| if task_list is not None: |
| self.tasks = [task for task in task_list if task in available_tasks] |
| else: |
| self.tasks = available_tasks |
| |
| print(f"📊 Loading {len(self.tasks)} tasks: {self.tasks}") |
| |
| |
| if transform is None: |
| self.transform = T.Compose([ |
| T.Resize((image_size, image_size)), |
| T.ToTensor(), |
| ]) |
| else: |
| self.transform = transform |
| |
| |
| self.trajectories = self._load_trajectories() |
| print(f"✅ Loaded {len(self.trajectories)} trajectory steps") |
| |
| def _load_trajectories(self): |
| """Load all trajectory data""" |
| all_trajectories = [] |
| |
| for task in self.tasks: |
| |
| pkl_path = self.data_pkl_root / f"{task}.pkl" |
| if not pkl_path.exists(): |
| print(f"⚠️ Pickle file not found: {pkl_path}") |
| continue |
| |
| with open(pkl_path, "rb") as f: |
| data = pickle.load(f) |
| |
| |
| task_img_dir = self.img_root / task |
| if not task_img_dir.exists(): |
| print(f"⚠️ Image directory not found: {task_img_dir}") |
| continue |
| |
| |
| traj_dirs = sorted(task_img_dir.glob("*"), key=lambda x: int(x.name)) |
| |
| for traj_idx, traj_dir in enumerate(traj_dirs): |
| if traj_idx >= len(data['actions']): |
| continue |
| |
| |
| img_paths = sorted(traj_dir.glob("*.jpg"), |
| key=lambda x: int(x.stem)) |
| |
| num_steps = len(data['actions'][traj_idx]) |
| num_images = len(img_paths) |
| |
| |
| min_steps = min(num_images, num_steps) |
| if min_steps < 1: |
| continue |
| |
| |
| for step_idx in range(min_steps): |
| trajectory_entry = { |
| 'task_name': task, |
| 'trajectory_id': traj_idx, |
| 'step_id': step_idx, |
| 'image_path': str(img_paths[step_idx]), |
| 'state': data['state'][traj_idx][step_idx][:7], |
| 'action': data['actions'][traj_idx][step_idx], |
| 'prompt': self._get_prompt(task) |
| } |
| all_trajectories.append(trajectory_entry) |
| |
| return all_trajectories |
| |
| def _get_prompt(self, task_name): |
| """Get prompt for a task""" |
| if task_name in self.prompts: |
| |
| return self.prompts[task_name].get('simple', f"Perform the task: {task_name.replace('-', ' ')}") |
| else: |
| return f"Perform the task: {task_name.replace('-', ' ')}" |
| |
| def get_task_info(self, task_name): |
| """Get comprehensive task information""" |
| if task_name in self.prompts: |
| return self.prompts[task_name] |
| return {"simple": f"Perform the task: {task_name.replace('-', ' ')}"} |
| |
| def get_available_tasks(self): |
| """Get list of available tasks""" |
| return self.tasks.copy() |
| |
| def get_dataset_stats(self): |
| """Get dataset statistics""" |
| task_counts = {} |
| for traj in self.trajectories: |
| task = traj['task_name'] |
| task_counts[task] = task_counts.get(task, 0) + 1 |
| |
| return { |
| 'total_steps': len(self.trajectories), |
| 'num_tasks': len(self.tasks), |
| 'task_step_counts': task_counts, |
| 'tasks': self.tasks |
| } |
| |
| def __len__(self): |
| return len(self.trajectories) |
| |
| def __getitem__(self, idx): |
| """Get a single trajectory step""" |
| traj = self.trajectories[idx] |
| |
| |
| image = Image.open(traj['image_path']).convert("RGB") |
| image_tensor = self.transform(image) |
| |
| |
| state = torch.tensor(traj['state'], dtype=torch.float32) |
| action = torch.tensor(traj['action'], dtype=torch.float32) |
| |
| return { |
| 'image': image_tensor, |
| 'state': state, |
| 'action': action, |
| 'prompt': traj['prompt'], |
| 'task_name': traj['task_name'], |
| 'trajectory_id': traj['trajectory_id'], |
| 'step_id': traj['step_id'] |
| } |
|
|
| |
| def load_short_metaworld(data_root, tasks=None, image_size=224): |
| """ |
| Convenience function to load the dataset. |
| |
| Args: |
| data_root (str): Path to dataset root |
| tasks (list): List of tasks to load (None for all) |
| image_size (int): Image size for transforms |
| |
| Returns: |
| ShortMetaWorldDataset: The loaded dataset |
| """ |
| return ShortMetaWorldDataset( |
| data_root=data_root, |
| task_list=tasks, |
| image_size=image_size |
| ) |
|
|
| def get_mt10_tasks(): |
| """Get the MT10 task list""" |
| return [ |
| "reach-v2", "push-v2", "pick-place-v2", "door-open-v2", "drawer-open-v2", |
| "drawer-close-v2", "button-press-topdown-v2", "button-press-v2", |
| "button-press-wall-v2", "button-press-topdown-wall-v2" |
| ] |
|
|
| def demo_usage(): |
| """Demonstrate how to use the dataset""" |
| print("📖 Short-MetaWorld Dataset Usage Example") |
| print("=" * 50) |
| |
| |
| dataset = load_short_metaworld("./", tasks=get_mt10_tasks()) |
| |
| |
| stats = dataset.get_dataset_stats() |
| print(f"📊 Dataset Statistics:") |
| print(f" Total steps: {stats['total_steps']}") |
| print(f" Number of tasks: {stats['num_tasks']}") |
| print(f" Available tasks: {stats['tasks']}") |
| |
| |
| if len(dataset) > 0: |
| sample = dataset[0] |
| print(f"\n📋 Sample data:") |
| print(f" Image shape: {sample['image'].shape}") |
| print(f" State shape: {sample['state'].shape}") |
| print(f" Action shape: {sample['action'].shape}") |
| print(f" Task: {sample['task_name']}") |
| print(f" Prompt: {sample['prompt']}") |
|
|
| if __name__ == "__main__": |
| demo_usage() |
|
|