Download loader.py from WorldAgents-c/MultiDojo2: direct link, hf CLI and curl.
- Browser
- Download file 9.03 kB
-
https://huggingface.co/datasets/WorldAgents-c/MultiDojo2/resolve/refs%2Fpr%2F1/loader.py
- Command line
-
hf download hf://datasets/WorldAgents-c/MultiDojo2@refs/pr/1/loader.py
-
curl -L -o loader.py https://huggingface.co/datasets/WorldAgents-c/MultiDojo2/resolve/refs%2Fpr%2F1/loader.py
9.03 kB
| """WAM-ready variable-DOF, synchronized multi-arm transitions from accepted rows.""" | |
| from collections import OrderedDict | |
| import json | |
| from pathlib import Path | |
| import pickle | |
| import cv2 | |
| cv2.setNumThreads(1) | |
| import lmdb | |
| import numpy as np | |
| from scipy.spatial.transform import Rotation | |
| import io | |
| class _ArrayUnpickler(pickle.Unpickler): | |
| # Only NumPy's data constructors used by the existing array serialization. | |
| # No arbitrary modules, callables or application classes are accepted. | |
| def find_class(self, module, name): | |
| allowed = { | |
| ('numpy', 'ndarray'), ('numpy', 'dtype'), | |
| ('numpy.core.multiarray', '_reconstruct'), ('numpy.core.multiarray', 'scalar'), | |
| ('numpy._core.multiarray', '_reconstruct'), ('numpy._core.multiarray', 'scalar'), | |
| ('numpy.core.numeric', '_frombuffer'), ('numpy._core.numeric', '_frombuffer'), | |
| } | |
| if (module, name) not in allowed: | |
| raise pickle.UnpicklingError('unsupported serialized class: '+module+'.'+name) | |
| return super().find_class(module, name) | |
| def _loads(data): | |
| return _ArrayUnpickler(io.BytesIO(data)).load() | |
| class TrainingDataset: | |
| def __init__(self,index,max_open=3): | |
| index = Path(index).expanduser().resolve() | |
| self.root = index.parent | |
| if (self.root/'PUBLICATION_REVIEW_IN_PROGRESS.json').exists(): | |
| raise RuntimeError('The portable release has not finished technical verification.') | |
| if not isinstance(max_open, int) or isinstance(max_open, bool) or max_open < 1: | |
| raise ValueError('max_open must be a positive integer') | |
| for parent in Path(index).resolve().parents: | |
| if (parent/'TRAINING_REVIEW_IN_PROGRESS.json').exists(): | |
| raise RuntimeError('Dataset review is incomplete; use the finalized refinement train.jsonl only.') | |
| self.rows=[json.loads(line) for line in Path(index).read_text().splitlines() if line.strip()] | |
| assert self.rows and all(row.get('accepted_for_training') for row in self.rows),'use an accepted train.jsonl index' | |
| for row in self.rows: | |
| for field in ('render', 'trajectory'): | |
| relative = Path(row[field]) | |
| if relative.is_absolute() or '..' in relative.parts: | |
| raise ValueError('release payload paths must be relative to train.jsonl') | |
| resolved = (self.root/relative).resolve() | |
| if self.root not in resolved.parents: | |
| raise ValueError('payload path escapes the release directory') | |
| row[field] = str(resolved) | |
| self.lengths=[row['num_steps'] for row in self.rows];self.ends=np.cumsum(self.lengths) | |
| self.cache=OrderedDict();self.max_open=max_open | |
| def __len__(self):return int(self.ends[-1]) | |
| def _open(self,episode): | |
| if episode in self.cache: | |
| entry=self.cache.pop(episode);self.cache[episode]=entry;return entry | |
| row=self.rows[episode];folder=Path(row['render']);meta=_loads((folder/'meta_info.pkl').read_bytes()) | |
| assert meta['accepted_for_training'] and meta['views']==row['views'] | |
| db=lmdb.open(str(folder/'lmdb'),readonly=True,lock=False,readahead=False);arrays={} | |
| with db.begin() as tx: | |
| for robot in meta['robots']: | |
| name=robot['name'] | |
| arrays[name]=dict(state=_loads(tx.get(f'observation/{name}/qpos'.encode())), | |
| velocity=_loads(tx.get(f'observation/{name}/qvel'.encode())), | |
| feedforward_effort=_loads(tx.get(f'action/{name}/joint_feedforward_effort'.encode())), | |
| action=_loads(tx.get(f'action/{name}/joint_position'.encode())), | |
| next_state=_loads(tx.get(f'state/{name}/next_qpos'.encode()))) | |
| with np.load(folder/'camera-calibration.npz',allow_pickle=False) as calibration: | |
| camera_poses={name:calibration[name].copy() for name in row['views']} | |
| with np.load(Path(row['trajectory'])/'trajectory.npz',allow_pickle=False) as physical: | |
| for name in row['views']: | |
| mount=meta['camera_config'][name]['mount'] | |
| if mount['type']=='world':terminal_pose=np.asarray(mount['world_pose']) | |
| else: | |
| link=physical[f'arm_{mount["arm"]+1}_link_transforms'][-1,mount['link_index']] | |
| rotation=Rotation.from_quat(link[3:]) | |
| local=Rotation.from_quat(np.asarray(mount['local_orientation_wxyz'])[[1,2,3,0]]) | |
| terminal_pose=np.r_[link[:3]+rotation.apply(mount['local_position']),(rotation*local).as_quat()[[3,0,1,2]]] | |
| camera_poses[name]=np.vstack([camera_poses[name],terminal_pose]) | |
| entry=(row,meta,db,arrays,camera_poses);self.cache[episode]=entry | |
| if len(self.cache)>self.max_open:self.cache.popitem(last=False)[1][2].close() | |
| return entry | |
| def __getitem__(self,index): | |
| if not 0<=index<len(self):raise IndexError(index) | |
| episode=int(np.searchsorted(self.ends,index,side='right')) | |
| frame=index-(int(self.ends[episode-1]) if episode else 0) | |
| return self.step(episode,frame) | |
| def step(self,episode,frame,action_horizon=1): | |
| if not 0 <= episode < len(self.rows):raise IndexError(episode) | |
| row,meta,db,arrays,camera_poses=self._open(episode);n=row['num_steps'] | |
| if not 0<=frame<n:raise IndexError(frame) | |
| if not isinstance(action_horizon,int) or isinstance(action_horizon,bool) or action_horizon<1: | |
| raise ValueError('action_horizon must be a positive integer') | |
| def image(tx,name,k): | |
| if k==n:rgb=cv2.imread(str(Path(row['render'])/f'terminal_{name}.png')) | |
| else: | |
| key=meta['keys'][f'observation/{name}/color_image'][k];payload=tx.get(key) | |
| if payload is None:raise ValueError('missing RGB image') | |
| rgb=cv2.imdecode(np.asarray(_loads(payload),dtype=np.uint8),cv2.IMREAD_COLOR) | |
| if rgb is None or rgb.shape!=(480,640,3):raise ValueError('invalid RGB image') | |
| return rgb[:,:,::-1].copy() | |
| with db.begin() as tx: | |
| images={name:image(tx,name,frame) for name in row['views']} | |
| next_images={name:image(tx,name,frame+1) for name in row['views']} | |
| indices=np.minimum(np.arange(frame,frame+action_horizon),n-1) | |
| robots={} | |
| for description in meta['robots']: | |
| name=description['name'];a=arrays[name] | |
| units=description.get('joint_units') | |
| if units is None: | |
| # Early accepted pilots predate the explicit unit field. Their | |
| # unchanged native models have revolute arms and two prismatic | |
| # fingers; all 13 Robotiq mechanism joints are revolute. | |
| count=len(description['joint_names']) | |
| units=['rad']*count if description['kind']=='robotiq' else ['rad']*(count-2)+['m','m'] | |
| robots[name]=dict(kind=description['kind'],joint_names=description['joint_names'], | |
| joint_units=units, | |
| actuator_effort_limits=description.get('actuator_effort_limits'), | |
| drive_stiffness=description.get('drive_stiffness'),drive_damping=description.get('drive_damping'), | |
| actuated_mask=np.asarray(description.get('actuated_mask',[True]*len(description['joint_names'])),dtype=bool), | |
| velocity=a['velocity'][frame].astype(np.float32),feedforward_effort=a['feedforward_effort'][frame].astype(np.float32), | |
| state=a['state'][frame].astype(np.float32),action=a['action'][frame].astype(np.float32), | |
| next_state=a['next_state'][frame].astype(np.float32),action_chunk=a['action'][indices].astype(np.float32)) | |
| return dict(episode=row['episode'],task=row['task'],instruction=row['instruction'],frame=frame,timestamp_s=frame/30, | |
| robots=robots,images=images,next_images=next_images,terminal=frame==n-1, | |
| cameras={name:dict(intrinsics=np.asarray(meta['camera_config'][name]['intrinsics'],dtype=np.float32), | |
| pose_world_wxyz=camera_poses[name][frame].copy(),next_pose_world_wxyz=camera_poses[name][frame+1].copy(), | |
| axes='ros',resolution=[640,480]) for name in row['views']}, | |
| action_chunk_mask=np.arange(frame,frame+action_horizon)<n, | |
| action_semantics='absolute native joint position commands; radians and metres as named') | |
| def close(self): | |
| for entry in self.cache.values():entry[2].close() | |
| self.cache.clear() | |
| if __name__=='__main__': | |
| import argparse | |
| parser=argparse.ArgumentParser();parser.add_argument('index');args=parser.parse_args() | |
| dataset=TrainingDataset(args.index) | |
| for index in (0,len(dataset)//2,len(dataset)-1): | |
| row=dataset[index];print(row['task'],row['frame'],{name:r['state'].shape for name,r in row['robots'].items()},len(row['images'])) | |
| print(len(dataset.rows),'accepted episodes',len(dataset),'aligned transitions');dataset.close() | |