File size: 3,038 Bytes
5c09236 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """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()
|