Download restore.py from data-loader/simlingo-posttrain-buckets: direct link, hf CLI and curl.
- Browser
- Download file 5.67 kB
-
https://huggingface.co/datasets/data-loader/simlingo-posttrain-buckets/resolve/main/restore.py
- Command line
-
hf download hf://datasets/data-loader/simlingo-posttrain-buckets/restore.py
-
curl -L -o restore.py https://huggingface.co/datasets/data-loader/simlingo-posttrain-buckets/resolve/main/restore.py
5.67 kB
| #!/usr/bin/env python3 | |
| """Restore the trusted SimLingo bucket snapshot for a new data location (Python >=3.8).""" | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import json | |
| import os | |
| import pickle | |
| import shutil | |
| import tarfile | |
| import tempfile | |
| from pathlib import Path | |
| TOKEN = '__SIMLINGO_DATA_ROOT__' | |
| CACHE = 'BUCKET2DATA_remove_missing_dream_jianing.pkl' | |
| INDEX = 'bucketsv2_simlingo/buckets_paths.pkl' | |
| FIELDS = ('images', 'boxes', 'measurements', 'alternative_trajectories') | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with Path(path).open('rb') as f: | |
| for block in iter(lambda: f.read(8 * 1024 * 1024), b''): | |
| h.update(block) | |
| return h.hexdigest() | |
| def rewrite_cache(cache, old, new): | |
| """Rewrite path leaves only; keep scalar values, container types and aliasing.""" | |
| memo = {} | |
| count = 0 | |
| def walk(value): | |
| nonlocal count | |
| ident = id(value) | |
| if ident in memo: | |
| return memo[ident][1] | |
| if type(value) is str: | |
| if not value.startswith(old + '/'): | |
| raise ValueError('Unexpected cache path prefix; refusing a partial rewrite') | |
| out = new + value[len(old):] | |
| count += 1 | |
| elif type(value) is list: | |
| out = [] | |
| memo[ident] = (value, out) | |
| out.extend(walk(x) for x in value) | |
| elif type(value) is tuple: | |
| out = tuple(walk(x) for x in value) | |
| else: | |
| raise TypeError('Unexpected path container: ' + type(value).__name__) | |
| memo[ident] = (value, out) | |
| return out | |
| for buckets in cache.values(): | |
| for bucket in buckets.values(): | |
| for field in FIELDS: | |
| if field in bucket: | |
| bucket[field] = walk(bucket[field]) | |
| return count | |
| def check_data(root, probes): | |
| from PIL import Image | |
| for item in probes: | |
| path = root / item['path'] | |
| if not path.is_file(): | |
| raise FileNotFoundError(str(path)) | |
| if item['kind'] == 'image': | |
| with Image.open(str(path)) as im: | |
| im.verify() | |
| else: | |
| with gzip.open(str(path), 'rt') as f: | |
| data = json.load(f) | |
| if item['kind'] == 'commentary': | |
| assert 'commentary' in data | |
| elif item['kind'] == 'vqa': | |
| assert data.get('QA') | |
| elif item['kind'] == 'dreamer': | |
| assert any(v for k, v in data.items() if 'factor' not in k) | |
| return len(probes) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--database-root', type=Path, required=True, | |
| help='Resource directory containing simlingo_v2_2025_01_10/') | |
| parser.add_argument('--bundle-dir', type=Path, default=Path(__file__).resolve().parent) | |
| parser.add_argument('--check-data', action='store_true', help='Decode representative real samples before writing') | |
| args = parser.parse_args() | |
| bundle = args.bundle_dir.resolve() | |
| db = args.database_root.resolve() | |
| data = (db / 'simlingo_v2_2025_01_10').resolve() | |
| if args.check_data: | |
| probes = json.loads((bundle / 'sample-probes.json').read_text()) | |
| print('Verified real data files:', check_data(data, probes), flush=True) | |
| targets = (db / CACHE, db / INDEX) | |
| for target in targets: | |
| if target.exists() or target.is_symlink(): | |
| raise FileExistsError('Refusing to overwrite ' + str(target)) | |
| manifest = json.loads((bundle / 'manifest.json').read_text()) | |
| archive = bundle / manifest['archive']['path'] | |
| assert archive.stat().st_size == manifest['archive']['bytes'] | |
| assert sha256(archive) == manifest['archive']['sha256'], 'Archive checksum mismatch' | |
| db.mkdir(parents=True, exist_ok=True) | |
| with tempfile.TemporaryDirectory(prefix='.restore-buckets-', dir=str(db)) as temp: | |
| temp = Path(temp) | |
| expected = {x['path']: x for x in manifest['payload']} | |
| with tarfile.open(str(archive), 'r:gz') as tar: | |
| members = tar.getmembers() | |
| assert len(members) == len(expected) | |
| assert {x.name for x in members} == set(expected) | |
| for member in members: | |
| assert member.isfile() and member.size == expected[member.name]['bytes'] | |
| target = temp / member.name | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| with tar.extractfile(member) as src, target.open('wb') as dst: | |
| shutil.copyfileobj(src, dst, 8 * 1024 * 1024) | |
| assert sha256(target) == expected[member.name]['sha256'] | |
| print('Loading portable cache; this may take a few minutes.', flush=True) | |
| with (temp / 'BUCKET2DATA.portable.pkl').open('rb') as f: | |
| cache = pickle.load(f) | |
| rewritten = rewrite_cache(cache, TOKEN, str(data)) | |
| staged_cache = temp / CACHE | |
| with staged_cache.open('wb') as f: | |
| pickle.dump(cache, f, protocol=4) | |
| targets[1].parent.mkdir(parents=True, exist_ok=True) | |
| # Hard links fail atomically if another process has created either target. | |
| os.link(str(staged_cache), str(targets[0])) | |
| try: | |
| os.link(str(temp / INDEX), str(targets[1])) | |
| except BaseException: | |
| targets[0].unlink() | |
| raise | |
| report = {'ok': True, 'data_root': str(data), 'rewritten_unique_path_objects': rewritten, | |
| 'cache': str(targets[0]), 'bucket_index': str(targets[1]), | |
| 'sample_counts': manifest['sample_counts'], 'real_samples_checked': args.check_data} | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |