Download reader.py from YuMoool/astra-robodojo-rollouts: direct link, hf CLI and curl.
- Browser
- Download file 6.26 kB
-
https://huggingface.co/datasets/YuMoool/astra-robodojo-rollouts/resolve/main/reader.py
- Command line
-
hf download hf://datasets/YuMoool/astra-robodojo-rollouts/reader.py
-
curl -L -o reader.py https://huggingface.co/datasets/YuMoool/astra-robodojo-rollouts/resolve/main/reader.py
6.26 kB
| """Read Astra/RoboDojo releases without a simulator, GPU, pickle, or ZIP extraction.""" | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import hashlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import zipfile | |
| import numpy as np | |
| CAMERAS = ('cam_high', 'cam_left_wrist', 'cam_right_wrist') | |
| def sha256(path): | |
| digest = hashlib.sha256() | |
| with Path(path).open('rb') as stream: | |
| for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b''): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def arrays(data): | |
| with np.load(io.BytesIO(data), allow_pickle=False) as archive: | |
| return {name: archive[name] for name in archive.files} | |
| def safe_path(root, relative): | |
| path = (root / relative).resolve() | |
| if Path(relative).is_absolute() or not path.is_relative_to(root.resolve()): | |
| raise ValueError('Dataset path escapes root') | |
| return path | |
| class Dataset: | |
| def __init__(self, directory): | |
| self.root = Path(directory).resolve() | |
| self.manifest = json.loads((self.root / 'manifest.json').read_text()) | |
| if self.manifest['schema'] != 'astra.robodojo.dataset.v1': | |
| raise ValueError('Unsupported release schema') | |
| self.episodes = self.manifest['episodes'] | |
| if len({r['episode_id'] for r in self.episodes}) != len(self.episodes): | |
| raise ValueError('Duplicate episode identifiers') | |
| def select(self, method=None, task=None): | |
| return [r for r in self.episodes if (method is None or r['method'] == method) | |
| and (task is None or r['task'] == task)] | |
| def open(self, episode_id, verify=False): | |
| record = next(r for r in self.episodes if r['episode_id'] == episode_id) | |
| return Episode(self.root, record, verify=verify) | |
| def verify_files(self, include_observations=False): | |
| for record in self.episodes: | |
| for name, info in record['files'].items(): | |
| if name == 'observations' and not include_observations: | |
| continue | |
| path = safe_path(self.root, info['path']) | |
| if path.stat().st_size != info['bytes'] or sha256(path) != info['sha256']: | |
| raise ValueError('File checksum mismatch: ' + info['path']) | |
| class Decision: | |
| episode: 'Episode' | |
| record: dict | |
| def index(self): | |
| return self.record['decision'] | |
| def executed_actions(self): | |
| return self.episode.trajectory['actions'][self.record['start_tick']:self.record['end_tick']] | |
| def pi05_proposal(self): | |
| """Both raw_actions and gripper-clipped actions; None for direct control.""" | |
| member = self.record.get('proposal_member') | |
| return arrays(self.episode.core.read(member)) if member else None | |
| def eef_targets(self): | |
| """Per-step targets actually attempted, including IK diagnostics; [] for student.""" | |
| return self.record.get('correction_trace', []) | |
| def requested_response(self): | |
| return self.record['response'] | |
| def observation(self, images='preview'): | |
| return self.episode.observation(self.record['start_tick'], images=images, | |
| observation_index=self.record['observation_index']) | |
| class Episode: | |
| def __init__(self, root, record, verify=False): | |
| self.root, self.record = Path(root), record | |
| info = record['files']['core'] | |
| path = safe_path(self.root, info['path']) | |
| if verify and (path.stat().st_size != info['bytes'] or sha256(path) != info['sha256']): | |
| raise ValueError('Core checksum mismatch') | |
| self.core = zipfile.ZipFile(path) | |
| self.metadata = self.read_json('episode.json') | |
| self.trajectory = arrays(self.core.read('trajectory.npz')) | |
| self.observation_index = self.read_json('observation_index.json') | |
| self._decisions = self.read_jsonl('decisions.jsonl') | |
| self._raw = None | |
| def read_json(self, member): | |
| return json.loads(self.core.read(member)) | |
| def read_jsonl(self, member): | |
| return [json.loads(line) for line in self.core.read(member).splitlines() if line.strip()] | |
| def decisions(self): | |
| return [Decision(self, row) for row in self._decisions] | |
| def observation(self, step, images='none', observation_index=None): | |
| """s[t] is before action[t]. Raw camera arrays require the optional full ZIP.""" | |
| if not 0 <= step <= self.metadata['control_steps']: | |
| raise IndexError(step) | |
| if images == 'raw': | |
| return self.raw_observation(step) | |
| if images not in {'none', 'preview'}: | |
| raise ValueError('images must be none, preview, or raw') | |
| result = {k: v[step] for k, v in self.trajectory.items() | |
| if k in ('states', 'eef_positions', 'eef_quaternions_wxyz', 'remaining_steps', 'instruction')} | |
| if images == 'preview': | |
| from PIL import Image | |
| matches = [r for r in self.observation_index if r['step_id'] == step | |
| and (observation_index is None or r['index'] == observation_index)] | |
| if not matches: | |
| raise ValueError('No decision-time preview at this control step; use images="raw"') | |
| for camera, member in matches[0]['preview_members'].items(): | |
| with Image.open(io.BytesIO(self.core.read(member))) as img: | |
| result[camera] = np.asarray(img.convert('RGB')).copy() | |
| return result | |
| def raw_observation(self, step): | |
| if not 0 <= step <= self.metadata['control_steps']: | |
| raise IndexError(step) | |
| if self._raw is None: | |
| info = self.record['files'].get('observations') | |
| if info is None: | |
| raise FileNotFoundError('This export has no full-resolution observation bundle') | |
| self._raw = zipfile.ZipFile(safe_path(self.root, info['path'])) | |
| return arrays(self._raw.read(f'observations/{step:06d}.npz')) | |
| def close(self): | |
| self.core.close() | |
| if self._raw is not None: | |
| self._raw.close() | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, *args): | |
| self.close() | |