"""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