Download xfield_sim.py from KAS2003/xfield-sim-core: direct link, hf CLI and curl.
- Browser
- Download file 7.03 kB
-
https://huggingface.co/datasets/KAS2003/xfield-sim-core/resolve/main/xfield_sim.py
- Command line
-
hf download hf://datasets/KAS2003/xfield-sim-core/xfield_sim.py
-
curl -L -o xfield_sim.py https://huggingface.co/datasets/KAS2003/xfield-sim-core/resolve/main/xfield_sim.py
7.03 kB
| """Read XField simulation frames from a downloaded dataset or a pinned public Hub revision.""" | |
| from functools import lru_cache | |
| import gzip | |
| import hashlib | |
| import io | |
| import json | |
| import os | |
| from pathlib import Path | |
| import tarfile | |
| import tempfile | |
| import numpy as np | |
| import zstandard as zstd | |
| from filelock import FileLock | |
| from huggingface_hub import HfApi, hf_hub_download | |
| REPO = 'KAS2003/xfield-sim-core' | |
| SPLITS = ('fit', 'dev', 'paired_eval') | |
| SENSORS = {'image_rgb', 'img', 'cube', 'depth', 'sem', 'K', 'T', 'steer'} | |
| def _tar(path, pid): | |
| return tarfile.open(path, mode='r:') | |
| class XFieldSim: | |
| """New methods get separate input and target dictionaries. The test sensor files contain no GT.""" | |
| def __init__(self, split='fit', *, revision=None, local_dir=None, cache_dir=None): | |
| if split not in SPLITS: | |
| raise ValueError(f'Unknown split {split!r}') | |
| self.split = split | |
| self.local_dir = Path(local_dir).resolve() if local_dir else None | |
| self.cache = Path(cache_dir or os.environ.get('XFIELD_CACHE', Path.home()/'.cache/xfield-sim')) | |
| if self.local_dir is None: | |
| self.revision = HfApi(token=False).dataset_info( | |
| REPO, revision=revision or 'refs/heads/main', expand=['sha']).sha | |
| else: | |
| self.revision = revision | |
| with gzip.open(self.file('catalog/frames.jsonl.gz'), 'rt') as f: | |
| self.rows = [r for line in f if (r := json.loads(line))['split'] == split] | |
| with self.file(f'splits/{split}.txt').open() as f: | |
| keys = [s.rstrip('\n') for s in f] | |
| if keys != [r['key'] for r in self.rows] or len(set(keys)) != len(keys): | |
| raise ValueError('Frame index does not match the split') | |
| self.by_key = {r['key']:i for i,r in enumerate(self.rows)} | |
| def __len__(self): | |
| return len(self.rows) | |
| def file(self, name): | |
| if self.local_dir: | |
| return self.local_dir/name | |
| return Path(hf_hub_download(REPO, name, repo_type='dataset', revision=self.revision, token=False)) | |
| def archive(self, name): | |
| path = self.file(name) | |
| if name.endswith('.tar.zst'): | |
| # A single seekable copy per immutable source file, shared by data-loader workers. | |
| scope = self.revision or 'download-'+hashlib.sha256(str(self.local_dir).encode()).hexdigest()[:16] | |
| unpacked = (self.cache/scope/name).with_suffix('') | |
| unpacked.parent.mkdir(parents=True, exist_ok=True) | |
| with FileLock(str(unpacked)+'.lock'): | |
| if not unpacked.exists(): | |
| with tempfile.NamedTemporaryFile(dir=unpacked.parent, delete=False) as out: | |
| tmp = Path(out.name) | |
| try: | |
| with path.open('rb') as stream: | |
| zstd.ZstdDecompressor().copy_stream(stream, out) | |
| except BaseException: | |
| tmp.unlink(missing_ok=True) | |
| raise | |
| tmp.replace(unpacked) | |
| path = unpacked | |
| return _tar(str(path), os.getpid()) | |
| def read(self, index): | |
| row = self.rows[self.by_key[index] if isinstance(index, str) else index] | |
| ar = self.archive(row['shard']) | |
| with ar.extractfile(row['member']) as member, np.load(io.BytesIO(member.read()), allow_pickle=False) as z: | |
| sample = {k:z[k] for k in z.files} | |
| if str(sample['key']) != row['key']: | |
| raise ValueError('Prepared frame identity mismatch') | |
| if self.split == 'fit': | |
| with self.archive(row['radar']).extractfile(row['radar_member']) as member: | |
| data = zstd.ZstdDecompressor().decompress(member.read()) | |
| sample['cube'] = np.load(io.BytesIO(data), allow_pickle=False) | |
| if 'img' in sample: | |
| sample['image_rgb'] = sample.pop('img') | |
| cube = sample['cube'] | |
| if cube.shape != (512,25,64) or cube.dtype != np.complex64 or sample['image_rgb'].shape != (3,360,640): | |
| raise ValueError('Invalid radar/RGB dimensions') | |
| if self.split == 'fit' and bool(sample['dense_present']) != row['dense']: | |
| raise ValueError('Dense supervision flag mismatch') | |
| inputs = {k:v for k,v in sample.items() if k in SENSORS} | |
| labels = {k:v for k,v in sample.items() if k not in SENSORS|{'key','route'}} | |
| if self.split == 'paired_eval' and labels: | |
| raise ValueError('Unexpected labels in test sensors') | |
| return {'key':row['key'], 'route':str(sample.get('route',row['episode'])), 'inputs':inputs, 'targets':labels} | |
| __getitem__ = read | |
| def available_keys(self): | |
| """Keys whose required shards exist at the selected revision or in the local download.""" | |
| if self.local_dir: | |
| exists = lambda name: (self.local_dir/name).is_file() | |
| else: | |
| files = set(HfApi(token=False).list_repo_files(REPO, repo_type='dataset', revision=self.revision)) | |
| exists = files.__contains__ | |
| return [r['key'] for r in self.rows if exists(r['shard']) and ('radar' not in r or exists(r['radar']))] | |
| def xfield_sample(self,index): | |
| """A fit/dev item accepted by XField_PredCore training.rgb_required.batchify.""" | |
| if self.split == 'paired_eval': | |
| raise ValueError('Use read() for paired test inference') | |
| frame = self.read(index) | |
| item = {**frame['inputs'], **frame['targets'], 'key':frame['key'], 'route':frame['route']} | |
| rgb = item.pop('image_rgb').astype(np.float32)/255 | |
| mean=np.array([.485,.456,.406], dtype=np.float32)[:,None,None] | |
| std=np.array([.229,.224,.225], dtype=np.float32)[:,None,None] | |
| item['image']=(rgb-mean)/std | |
| item['dense'] = tuple(item.pop(n) for n in ('dense_sem','dense_height','dense_lane')) if bool(item.pop('dense_present')) else None | |
| return item | |
| def test_truth(self,index): | |
| """Read the separately stored targets when scoring frozen test predictions.""" | |
| if self.split != 'paired_eval': | |
| raise ValueError('Test truth is available only for paired_eval') | |
| row=self.rows[self.by_key[index] if isinstance(index,str) else index] | |
| if not hasattr(self,'_vehicles'): | |
| with gzip.open(self.file('test_labels/vehicles.jsonl.gz'),'rt') as f: | |
| self._vehicles={r['key']:r for r in map(json.loads,f)} | |
| out={'vehicles':self._vehicles[row['key']]} | |
| if row['present']: | |
| with tarfile.open(self.file('test_labels/scene_occupancy.tar.gz'),'r:gz') as ar: | |
| with np.load(io.BytesIO(ar.extractfile(row['key']+'.npz').read()),allow_pickle=False) as z: | |
| if str(z['key'])!=row['key']:raise ValueError('Test label identity mismatch') | |
| shape=tuple(z['shape']);n=int(np.prod(shape)) | |
| out['occupancy']={k:np.unpackbits(z[k])[:n].reshape(shape).astype(bool) for k in ('obs','any')} | |
| return out | |