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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Short-MetaWorld Dataset Loader
|
| 4 |
+
Loads the dataset with proper structure preservation and task prompts.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import pickle
|
| 9 |
+
import json
|
| 10 |
+
import glob
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import torch
|
| 14 |
+
import torchvision.transforms as T
|
| 15 |
+
from torch.utils.data import Dataset
|
| 16 |
+
|
| 17 |
+
class ShortMetaWorldDataset(Dataset):
|
| 18 |
+
"""
|
| 19 |
+
Short-MetaWorld dataset loader that preserves the original structure.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
data_root (str): Path to the dataset root directory
|
| 23 |
+
task_list (list): List of tasks to load (default: all available tasks)
|
| 24 |
+
image_size (int): Target image size for transforms (default: 224)
|
| 25 |
+
transform (callable): Optional custom transform
|
| 26 |
+
load_prompts (bool): Whether to load task prompts (default: True)
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, data_root, task_list=None, image_size=224, transform=None, load_prompts=True):
|
| 30 |
+
self.data_root = Path(data_root)
|
| 31 |
+
self.image_size = image_size
|
| 32 |
+
|
| 33 |
+
# Load task prompts
|
| 34 |
+
self.prompts = {}
|
| 35 |
+
if load_prompts:
|
| 36 |
+
prompt_file = self.data_root / "mt50_task_prompts.json"
|
| 37 |
+
if prompt_file.exists():
|
| 38 |
+
with open(prompt_file, 'r') as f:
|
| 39 |
+
self.prompts = json.load(f)
|
| 40 |
+
print(f"π Loaded {len(self.prompts)} task prompts")
|
| 41 |
+
else:
|
| 42 |
+
print("β οΈ Task prompts not found, using fallback prompts")
|
| 43 |
+
|
| 44 |
+
# Set up paths
|
| 45 |
+
self.img_root = self.data_root / "short-MetaWorld" / "short-MetaWorld" / "img_only"
|
| 46 |
+
self.data_pkl_root = self.data_root / "short-MetaWorld" / "r3m-processed" / "r3m_MT10_20"
|
| 47 |
+
|
| 48 |
+
# Discover available tasks
|
| 49 |
+
available_tasks = []
|
| 50 |
+
if self.data_pkl_root.exists():
|
| 51 |
+
for pkl_file in self.data_pkl_root.glob("*.pkl"):
|
| 52 |
+
task_name = pkl_file.stem
|
| 53 |
+
if (self.img_root / task_name).exists():
|
| 54 |
+
available_tasks.append(task_name)
|
| 55 |
+
|
| 56 |
+
# Filter tasks if task_list provided
|
| 57 |
+
if task_list is not None:
|
| 58 |
+
self.tasks = [task for task in task_list if task in available_tasks]
|
| 59 |
+
else:
|
| 60 |
+
self.tasks = available_tasks
|
| 61 |
+
|
| 62 |
+
print(f"π Loading {len(self.tasks)} tasks: {self.tasks}")
|
| 63 |
+
|
| 64 |
+
# Default transform
|
| 65 |
+
if transform is None:
|
| 66 |
+
self.transform = T.Compose([
|
| 67 |
+
T.Resize((image_size, image_size)),
|
| 68 |
+
T.ToTensor(),
|
| 69 |
+
])
|
| 70 |
+
else:
|
| 71 |
+
self.transform = transform
|
| 72 |
+
|
| 73 |
+
# Load all trajectories
|
| 74 |
+
self.trajectories = self._load_trajectories()
|
| 75 |
+
print(f"β
Loaded {len(self.trajectories)} trajectory steps")
|
| 76 |
+
|
| 77 |
+
def _load_trajectories(self):
|
| 78 |
+
"""Load all trajectory data"""
|
| 79 |
+
all_trajectories = []
|
| 80 |
+
|
| 81 |
+
for task in self.tasks:
|
| 82 |
+
# Load pickle data
|
| 83 |
+
pkl_path = self.data_pkl_root / f"{task}.pkl"
|
| 84 |
+
if not pkl_path.exists():
|
| 85 |
+
print(f"β οΈ Pickle file not found: {pkl_path}")
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
with open(pkl_path, "rb") as f:
|
| 89 |
+
data = pickle.load(f)
|
| 90 |
+
|
| 91 |
+
# Get image directories
|
| 92 |
+
task_img_dir = self.img_root / task
|
| 93 |
+
if not task_img_dir.exists():
|
| 94 |
+
print(f"β οΈ Image directory not found: {task_img_dir}")
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
# Process each trajectory
|
| 98 |
+
traj_dirs = sorted(task_img_dir.glob("*"), key=lambda x: int(x.name))
|
| 99 |
+
|
| 100 |
+
for traj_idx, traj_dir in enumerate(traj_dirs):
|
| 101 |
+
if traj_idx >= len(data['actions']):
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
# Get image paths
|
| 105 |
+
img_paths = sorted(traj_dir.glob("*.jpg"),
|
| 106 |
+
key=lambda x: int(x.stem))
|
| 107 |
+
|
| 108 |
+
num_steps = len(data['actions'][traj_idx])
|
| 109 |
+
num_images = len(img_paths)
|
| 110 |
+
|
| 111 |
+
# Use minimum length to handle mismatched data
|
| 112 |
+
min_steps = min(num_images, num_steps)
|
| 113 |
+
if min_steps < 1:
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
# Create trajectory entries
|
| 117 |
+
for step_idx in range(min_steps):
|
| 118 |
+
trajectory_entry = {
|
| 119 |
+
'task_name': task,
|
| 120 |
+
'trajectory_id': traj_idx,
|
| 121 |
+
'step_id': step_idx,
|
| 122 |
+
'image_path': str(img_paths[step_idx]),
|
| 123 |
+
'state': data['state'][traj_idx][step_idx][:7], # First 7 dims
|
| 124 |
+
'action': data['actions'][traj_idx][step_idx],
|
| 125 |
+
'prompt': self._get_prompt(task)
|
| 126 |
+
}
|
| 127 |
+
all_trajectories.append(trajectory_entry)
|
| 128 |
+
|
| 129 |
+
return all_trajectories
|
| 130 |
+
|
| 131 |
+
def _get_prompt(self, task_name):
|
| 132 |
+
"""Get prompt for a task"""
|
| 133 |
+
if task_name in self.prompts:
|
| 134 |
+
# Use simple prompt by default
|
| 135 |
+
return self.prompts[task_name].get('simple', f"Perform the task: {task_name.replace('-', ' ')}")
|
| 136 |
+
else:
|
| 137 |
+
return f"Perform the task: {task_name.replace('-', ' ')}"
|
| 138 |
+
|
| 139 |
+
def get_task_info(self, task_name):
|
| 140 |
+
"""Get comprehensive task information"""
|
| 141 |
+
if task_name in self.prompts:
|
| 142 |
+
return self.prompts[task_name]
|
| 143 |
+
return {"simple": f"Perform the task: {task_name.replace('-', ' ')}"}
|
| 144 |
+
|
| 145 |
+
def get_available_tasks(self):
|
| 146 |
+
"""Get list of available tasks"""
|
| 147 |
+
return self.tasks.copy()
|
| 148 |
+
|
| 149 |
+
def get_dataset_stats(self):
|
| 150 |
+
"""Get dataset statistics"""
|
| 151 |
+
task_counts = {}
|
| 152 |
+
for traj in self.trajectories:
|
| 153 |
+
task = traj['task_name']
|
| 154 |
+
task_counts[task] = task_counts.get(task, 0) + 1
|
| 155 |
+
|
| 156 |
+
return {
|
| 157 |
+
'total_steps': len(self.trajectories),
|
| 158 |
+
'num_tasks': len(self.tasks),
|
| 159 |
+
'task_step_counts': task_counts,
|
| 160 |
+
'tasks': self.tasks
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
def __len__(self):
|
| 164 |
+
return len(self.trajectories)
|
| 165 |
+
|
| 166 |
+
def __getitem__(self, idx):
|
| 167 |
+
"""Get a single trajectory step"""
|
| 168 |
+
traj = self.trajectories[idx]
|
| 169 |
+
|
| 170 |
+
# Load and transform image
|
| 171 |
+
image = Image.open(traj['image_path']).convert("RGB")
|
| 172 |
+
image_tensor = self.transform(image)
|
| 173 |
+
|
| 174 |
+
# Convert to tensors
|
| 175 |
+
state = torch.tensor(traj['state'], dtype=torch.float32)
|
| 176 |
+
action = torch.tensor(traj['action'], dtype=torch.float32)
|
| 177 |
+
|
| 178 |
+
return {
|
| 179 |
+
'image': image_tensor,
|
| 180 |
+
'state': state,
|
| 181 |
+
'action': action,
|
| 182 |
+
'prompt': traj['prompt'],
|
| 183 |
+
'task_name': traj['task_name'],
|
| 184 |
+
'trajectory_id': traj['trajectory_id'],
|
| 185 |
+
'step_id': traj['step_id']
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
# Example usage functions
|
| 189 |
+
def load_short_metaworld(data_root, tasks=None, image_size=224):
|
| 190 |
+
"""
|
| 191 |
+
Convenience function to load the dataset.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
data_root (str): Path to dataset root
|
| 195 |
+
tasks (list): List of tasks to load (None for all)
|
| 196 |
+
image_size (int): Image size for transforms
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
ShortMetaWorldDataset: The loaded dataset
|
| 200 |
+
"""
|
| 201 |
+
return ShortMetaWorldDataset(
|
| 202 |
+
data_root=data_root,
|
| 203 |
+
task_list=tasks,
|
| 204 |
+
image_size=image_size
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
def get_mt10_tasks():
|
| 208 |
+
"""Get the MT10 task list"""
|
| 209 |
+
return [
|
| 210 |
+
"reach-v2", "push-v2", "pick-place-v2", "door-open-v2", "drawer-open-v2",
|
| 211 |
+
"drawer-close-v2", "button-press-topdown-v2", "button-press-v2",
|
| 212 |
+
"button-press-wall-v2", "button-press-topdown-wall-v2"
|
| 213 |
+
]
|
| 214 |
+
|
| 215 |
+
def demo_usage():
|
| 216 |
+
"""Demonstrate how to use the dataset"""
|
| 217 |
+
print("π Short-MetaWorld Dataset Usage Example")
|
| 218 |
+
print("=" * 50)
|
| 219 |
+
|
| 220 |
+
# Load dataset
|
| 221 |
+
dataset = load_short_metaworld("./", tasks=get_mt10_tasks())
|
| 222 |
+
|
| 223 |
+
# Print stats
|
| 224 |
+
stats = dataset.get_dataset_stats()
|
| 225 |
+
print(f"π Dataset Statistics:")
|
| 226 |
+
print(f" Total steps: {stats['total_steps']}")
|
| 227 |
+
print(f" Number of tasks: {stats['num_tasks']}")
|
| 228 |
+
print(f" Available tasks: {stats['tasks']}")
|
| 229 |
+
|
| 230 |
+
# Get a sample
|
| 231 |
+
if len(dataset) > 0:
|
| 232 |
+
sample = dataset[0]
|
| 233 |
+
print(f"\nπ Sample data:")
|
| 234 |
+
print(f" Image shape: {sample['image'].shape}")
|
| 235 |
+
print(f" State shape: {sample['state'].shape}")
|
| 236 |
+
print(f" Action shape: {sample['action'].shape}")
|
| 237 |
+
print(f" Task: {sample['task_name']}")
|
| 238 |
+
print(f" Prompt: {sample['prompt']}")
|
| 239 |
+
|
| 240 |
+
if __name__ == "__main__":
|
| 241 |
+
demo_usage()
|