DexX-Force / read_dataset.py
Ruoqu's picture
Dex-X Force: Hand-Arm Grasp & Lift-10K
38dcc02
Raw History Blame Contribute Delete
6.32 kB
"""Read the packaged FR3 + Sharpa strict-grasp dataset without extracting tar files.
Only NumPy is required for local reads. Install huggingface_hub for download().
Create one Dataset per process/worker; instances hold file handles, not shared state.
"""
import io
import json
import tarfile
from collections import OrderedDict
from pathlib import Path
import numpy as np
REPO_ID = 'Ruoqu/DexX-Force'
SOURCES = ('dexonomy', 'dexycb')
def download(local_dir=None, source=None, include_context=False, include_assets=False):
"""Download trajectories; optionally add references and bundled assets.
Dexonomy object meshes are prepared separately with prepare_assets.py.
Downloads resume through the Hugging Face cache; no previews are fetched.
"""
from huggingface_hub import snapshot_download
if source is not None and source not in SOURCES:
raise ValueError(f'Unknown source: {source}')
patterns = ['read_dataset.py', 'manifest.jsonl', 'context_files.jsonl',
'asset_recipes.jsonl', 'joint_order.json', 'dataset.json',
'manifests/*.jsonl', f'episodes/{source or "*"}/*.tar']
if include_context:
patterns.append('context/*.tar')
if include_assets:
patterns += ['asset_shards/*.tar', 'assets/robot/**', 'licenses/**',
'prepare_assets.py', 'robot_files.json']
return Path(snapshot_download(REPO_ID, repo_type='dataset', local_dir=local_dir,
endpoint='https://huggingface.co', allow_patterns=patterns))
class Dataset:
"""Archive reader with a bounded LRU of open tar files (default four)."""
def __init__(self, root, max_open_archives=4):
if max_open_archives < 1:
raise ValueError('max_open_archives must be positive')
self.root = Path(root)
self.max_open_archives = max_open_archives
self.context = {
row['path']: row['archive']
for row in map(json.loads, (self.root / 'context_files.jsonl').read_text().splitlines())
}
self._archives = OrderedDict()
def rows(self, source=None, *, object_id=None, reference_id=None, checkpoint=None):
"""Iterate metadata only; filters are exact matches and do not read NPZs."""
if source is not None and source not in SOURCES:
raise ValueError(f'Unknown source: {source}')
filters = {'object_id': object_id, 'reference_id': reference_id,
'checkpoint_label': checkpoint}
for name in ([source] if source else SOURCES):
with (self.root / 'manifests' / f'{name}.jsonl').open() as stream:
for line in stream:
if not line.strip():
continue
row = json.loads(line)
if all(value is None or row.get(key) == value for key, value in filters.items()):
yield row
def read_bytes(self, path, archive=None):
"""Read an archive member; context members resolve via context_files.jsonl."""
local_member = self.root / path
if local_member.is_file():
return local_member.read_bytes()
if archive is None and path not in self.context:
raise FileNotFoundError(
f'{path} is an external asset. Run prepare_assets.py for Dexonomy objects; '
'see LOADING.md for source downloads.')
archive = archive or self.context[path]
if archive not in self._archives:
local = self.root / archive
if not local.is_file():
raise FileNotFoundError(f'Missing shard {local}; download it before reading this member.')
self._archives[archive] = tarfile.open(local, 'r')
if len(self._archives) > self.max_open_archives:
_, old = self._archives.popitem(last=False)
old.close()
self._archives.move_to_end(archive)
member = self._archives[archive].extractfile(path)
if member is None:
raise FileNotFoundError(path)
with member:
return member.read()
def _npz(self, path, archive=None, fields=None):
with np.load(io.BytesIO(self.read_bytes(path, archive)), allow_pickle=False) as arrays:
selected = arrays.files if fields is None else ([fields] if isinstance(fields, str) else fields)
return {key: arrays[key] for key in selected}
def rollout(self, row, fields=None):
"""Load all or selected arrays. Missing fields raise KeyError, never zero-fill."""
return self._npz(row['rollout_path'], row['episode_archive'], fields)
def metadata(self, row):
"""Read episode JSON, including coordinate and joint-index semantics."""
return json.loads(self.read_bytes(row['metadata_path'], row['episode_archive']))
def reference(self, row, fields=None):
"""Return source metadata and the source-specific compact ICL reference."""
metadata = json.loads(self.read_bytes(row['reference_metadata']))
return metadata, self._npz(row['icl_context'], fields=fields)
def iter_rollouts(self, source=None, *, fields=None, **filters):
"""Yield (metadata row, arrays), holding only one episode's arrays at a time."""
for row in self.rows(source, **filters):
yield row, self.rollout(row, fields)
def close(self):
for archive in self._archives.values():
archive.close()
self._archives.clear()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('root', type=Path)
parser.add_argument('--source', choices=SOURCES, default='dexonomy')
parser.add_argument('--limit', type=int, default=1)
args = parser.parse_args()
if args.limit < 1:
parser.error('--limit must be positive')
from itertools import islice
with Dataset(args.root) as dataset:
for row, arrays in islice(dataset.iter_rollouts(args.source), args.limit):
print(row['episode_id'])
for key, value in arrays.items():
print(f' {key}: shape={value.shape}, dtype={value.dtype}')