Datasets:
File size: 8,606 Bytes
a44dd93 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | #!/usr/bin/env python3
"""
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
# Load task prompts
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")
# Set up paths
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"
# Discover available tasks
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)
# Filter tasks if task_list provided
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}")
# Default transform
if transform is None:
self.transform = T.Compose([
T.Resize((image_size, image_size)),
T.ToTensor(),
])
else:
self.transform = transform
# Load all trajectories
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:
# Load pickle data
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)
# Get image directories
task_img_dir = self.img_root / task
if not task_img_dir.exists():
print(f"⚠️ Image directory not found: {task_img_dir}")
continue
# Process each trajectory
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
# Get image paths
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)
# Use minimum length to handle mismatched data
min_steps = min(num_images, num_steps)
if min_steps < 1:
continue
# Create trajectory entries
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], # First 7 dims
'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:
# Use simple prompt by default
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]
# Load and transform image
image = Image.open(traj['image_path']).convert("RGB")
image_tensor = self.transform(image)
# Convert to tensors
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']
}
# Example usage functions
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)
# Load dataset
dataset = load_short_metaworld("./", tasks=get_mt10_tasks())
# Print stats
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']}")
# Get a sample
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()
|