#!/usr/bin/env python3 """ Download and unpack experiment data from archives. Downloads per-experiment .tar.gz archives into data/archives/, extracts them into data/{experiment}/, and verifies file integrity against manifest.json checksums. Usage: python data/unpack.py # unpack all from data/archives/ python data/unpack.py card lottery # unpack specific experiments python data/unpack.py --source /path/to/archives # unpack from local directory python data/unpack.py --source https://... # download from URL python data/unpack.py --verify # verify existing files only """ import argparse import hashlib import json import shutil import tarfile import urllib.request from pathlib import Path from typing import Dict, Optional EXPERIMENTS = ['card', 'cardd', 'cards', 'rv', 'rvq', 'location', 'lottery', 'users'] DATA_DIR = Path(__file__).parent ARCHIVES_DIR = DATA_DIR / 'archives' def md5_file(path: Path) -> str: h = hashlib.md5() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(8192), b''): h.update(chunk) return h.hexdigest() def verify_experiment(experiment_dir: Path) -> Dict: """ Verify files on disk against manifest.json checksums. Returns dict with: verified, missing, corrupt counts. """ manifest_path = experiment_dir / 'manifest.json' if not manifest_path.exists(): return {'verified': 0, 'missing': 0, 'corrupt': 0, 'error': 'no manifest'} manifest = json.loads(manifest_path.read_text()) verified = missing = corrupt = 0 for entry in manifest.get('files', []): file_path = experiment_dir / entry['filename'] if not file_path.exists(): missing += 1 elif md5_file(file_path) != entry['md5_hash']: corrupt += 1 else: verified += 1 return {'verified': verified, 'missing': missing, 'corrupt': corrupt} def _fetch_archive(url_or_path: str, dest: Path) -> Path: """Download or copy archive to dest. Returns path to local archive.""" if url_or_path.startswith(('http://', 'https://')): print(f" Downloading {url_or_path}...") urllib.request.urlretrieve(url_or_path, dest) else: src = Path(url_or_path) if src != dest: shutil.copy2(src, dest) return dest def unpack_experiment( experiment_dir: Path, source: Optional[str] = None, ) -> Dict: """ Extract and verify one experiment from its archive. Archives are stored in data/archives/ and extracted into data/{experiment}/. Args: experiment_dir: Path to experiment directory (e.g. data/card/) source: Base URL or local directory containing archives. If None, uses data/archives/ then falls back to download_url in manifest. Returns: Dict with status ('ok' or 'error'), message, and counts. """ manifest_path = experiment_dir / 'manifest.json' if not manifest_path.exists(): return {'status': 'error', 'message': f"No manifest.json in {experiment_dir}"} manifest = json.loads(manifest_path.read_text()) dataset = manifest['dataset'] exp_name = experiment_dir.name # Archive lives in /archives/ (sibling of the experiment dir) archives_dir = experiment_dir.parent / 'archives' archives_dir.mkdir(exist_ok=True) archive_dest = archives_dir / f"{exp_name}.tar.gz" expected_md5 = manifest.get('archive_md5') # Fetch only if the archive isn't already on disk. A present-but-md5-mismatched # archive is NOT rejected here: archive_md5 goes stale whenever the archive is # re-packed (gzip embeds an mtime), so per-file md5 verification after extraction # (verify_experiment) is the authoritative integrity check. if not archive_dest.exists(): if source: source_path = source.rstrip('/') if source_path.startswith(('http://', 'https://')): archive_url = f"{source_path}/{exp_name}.tar.gz" else: archive_url = str(Path(source_path) / f"{exp_name}.tar.gz") elif manifest.get('download_url'): archive_url = manifest['download_url'] else: return { 'status': 'error', 'message': f"No archive in {archives_dir}/ and no download source for {dataset} — " f"place {exp_name}.tar.gz in {archives_dir}/ or provide --source" } try: _fetch_archive(archive_url, archive_dest) except Exception as e: return {'status': 'error', 'message': f"Download failed: {e}"} if expected_md5 and md5_file(archive_dest) != expected_md5: print(f" WARNING: archive_md5 mismatch for {exp_name} " f"(manifest may be stale) — relying on per-file verification") else: print(f" Archive present in {archives_dir}/, extracting...") # Extract into the data dir (archives stay put) experiment_dir.mkdir(parents=True, exist_ok=True) try: with tarfile.open(archive_dest, 'r:gz') as tf: tf.extractall(experiment_dir.parent) except Exception as e: return {'status': 'error', 'message': f"Extract failed for {exp_name} (archive may be corrupt): {e}"} # Per-file md5 verification is authoritative result = verify_experiment(experiment_dir) result['status'] = 'ok' if result['missing'] == 0 and result['corrupt'] == 0 else 'error' return result def main(): parser = argparse.ArgumentParser(description='Download and unpack experiment data') parser.add_argument('experiments', nargs='*', help='Experiments to unpack (default: all)') parser.add_argument('--source', help='Base URL or local path to archives') parser.add_argument('--verify', action='store_true', help='Verify existing files only') parser.add_argument('--data-dir', default=str(DATA_DIR), help='Path to data directory (default: data/)') args = parser.parse_args() experiments = args.experiments or EXPERIMENTS data_dir = Path(args.data_dir) failed = [] for exp in experiments: exp_dir = data_dir / exp if not (exp_dir / 'manifest.json').exists(): print(f" {exp}: no manifest.json, skipping") continue manifest = json.loads((exp_dir / 'manifest.json').read_text()) print(f" {exp} ({manifest['file_count']} files):") if args.verify: result = verify_experiment(exp_dir) status = "OK" if result['missing'] == 0 and result['corrupt'] == 0 else "ISSUES" print(f" {status} — verified={result['verified']}, " f"missing={result['missing']}, corrupt={result['corrupt']}") if result['missing'] or result['corrupt']: failed.append(exp) else: result = unpack_experiment(exp_dir, source=args.source) if result['status'] == 'ok': print(f" OK — verified={result['verified']} files") else: print(f" ERROR — {result.get('message', 'unknown')}") failed.append(exp) if failed: print(f"\nFailed: {', '.join(failed)}") return 1 print("\nDone.") return 0 if __name__ == '__main__': exit(main())