"""Verify the downloaded bundle, then restore images and original JSONL files.""" import argparse import hashlib import json import os from pathlib import Path, PurePosixPath import shutil import tarfile def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--bundle', type=Path, default=Path(__file__).resolve().parent) parser.add_argument('--destination', type=Path) parser.add_argument('--verify-only', action='store_true') args = parser.parse_args() root = args.bundle.resolve() if not args.verify_only and args.destination is None: parser.error('--destination is required for extraction') for line in (root / 'SHA256SUMS').read_text().splitlines(): expected, rel = line.split(' ', 1) p = PurePosixPath(rel) assert not p.is_absolute() and '..' not in p.parts h = hashlib.sha256() with (root / rel).open('rb') as file: for block in iter(lambda: file.read(8 * 1024 * 1024), b''): h.update(block) if h.hexdigest() != expected: raise RuntimeError(f'SHA-256 mismatch: {rel}') print(f'Verified {rel}', flush=True) if args.verify_only: return dest = args.destination.resolve() dest.mkdir(parents=True, exist_ok=True) for name in ('images', 'annotations'): if (dest / name).exists(): raise RuntimeError(f'Refusing to overwrite {dest / name}; select an empty destination') expected_images = json.loads((root / 'manifests/package_summary.json').read_text())['image_count'] count = 0 for shard in json.loads((root / 'manifests/shards.json').read_text())['shards']: shard_count = 0 with tarfile.open(root / shard['path'], mode='r|') as archive: for member in archive: p = PurePosixPath(member.name) if not member.isfile() or p.is_absolute() or '..' in p.parts or p.parts[0] != 'images': raise RuntimeError(f'Unsafe archive member: {member.name}') target = dest / member.name target.parent.mkdir(parents=True, exist_ok=True) with archive.extractfile(member) as source, target.open('xb') as out: shutil.copyfileobj(source, out) if target.stat().st_size != member.size: raise RuntimeError(f'Incomplete image: {target}') shard_count += 1 if shard_count != shard['image_count']: raise RuntimeError(f'Image count mismatch: {shard["path"]}') count += shard_count print(f'Extracted {shard["path"]}: {count:,} images', flush=True) if count != expected_images: raise RuntimeError('Total image count mismatch') shutil.copytree(root / 'annotations', dest / 'annotations') shutil.copyfile(root / 'source_roots.yaml', dest / 'source_roots.yaml') print(f'Complete: {count:,} images and three annotation files in {dest}', flush=True) if __name__ == '__main__': main()