CryoAtlas / resources /scripts /download.py
markfaa's picture
Group metadata, result previews and documentation for the expanded release
0779e53 verified
Raw History Blame Contribute Delete
3.43 kB
#!/usr/bin/env python3
"""Select CryoAtlas release archives, download them, and verify SHA-256."""
import argparse
import hashlib
import json
from pathlib import Path
from huggingface_hub import HfApi, hf_hub_download
REPO = 'markfaa/CryoAtlas'
def select_archives(manifest, args, entry_map=None):
if args.part:
parts = {f'train_part{n:02d}' for n in args.part}
return [r for r in manifest if r['component'] in parts]
if args.test:
components = {'test_benchmark_618', 'test_remaining_534'} if args.test == 'all' else {
'test_benchmark_618' if args.test == 'benchmark' else 'test_remaining_534'}
return [r for r in manifest if r['component'] in components]
if args.resources:
return [r for r in manifest if r['component'] == 'benchmark_resources']
emd = args.emd.upper()
if not emd.startswith('EMD-'):
emd = 'EMD-' + emd
if emd not in entry_map:
raise ValueError(f'{emd} is not in the fixed v1.0 release.')
return [r for r in manifest if r['path'] == entry_map[emd]]
def main():
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--part', type=int, choices=(1, 2, 3, 4), nargs='+')
group.add_argument('--test', choices=('benchmark', 'remaining', 'all'))
group.add_argument('--resources', action='store_true')
group.add_argument('--emd', help='Find and download the complete archive containing this EMD ID.')
parser.add_argument('--destination', type=Path, default=Path('CryoAtlas-downloads'))
parser.add_argument('--revision', default='main')
parser.add_argument('--dry-run', action='store_true', help='Show selected archives and sizes without downloading them.')
args = parser.parse_args()
# Pin all reads and downloads to one repository revision.
revision = HfApi().dataset_info(REPO, revision=args.revision).sha
def read_json(name):
return json.loads(Path(hf_hub_download(REPO, name, repo_type='dataset', revision=revision)).read_text())
manifest = read_json('resources/metadata/catalog/archives.json')
entry_map = read_json('resources/metadata/catalog/entry_archives.json') if args.emd else None
try:
selected = select_archives(manifest, args, entry_map)
except ValueError as exc:
parser.error(str(exc))
if not selected:
parser.error('No matching archives.')
print(f'Revision: {revision}')
for row in selected:
print(f"{row['bytes']/1e9:8.3f} GB {row['path']}")
print(f"Total: {sum(r['bytes'] for r in selected)/1e9:.3f} GB")
if args.emd:
print('Selection is an entire archive containing this entry, not an individual-entry download.')
if args.dry_run:
return
for row in selected:
path = Path(hf_hub_download(REPO, row['path'], repo_type='dataset', revision=revision, local_dir=args.destination))
if path.stat().st_size != row['bytes']:
raise RuntimeError(f'Size mismatch: {row["path"]}')
sha = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(8 * 1024 * 1024), b''):
sha.update(block)
if sha.hexdigest() != row['sha256']:
raise RuntimeError(f'SHA-256 mismatch: {row["path"]}')
print(f'Verified: {row["path"]}')
if __name__ == '__main__':
main()