| |
| """ |
| Download selected PhysInOne case zip files from Hugging Face shard repositories. |
| |
| Input: |
| selected_cases.json produced by filter_cases.py |
| repo_map.json mapping part IDs to Hugging Face repo IDs |
| |
| Recommended repo_map.json format: |
| { |
| "physinone_part1": "PhysInOneP01/PhysInOneP01", |
| "physinone_part2": "PhysInOneP02/PhysInOneP02" |
| } |
| |
| The script downloads each selected case zip using huggingface_hub.hf_hub_download. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import shutil |
| from pathlib import Path |
| from urllib.parse import urlparse |
|
|
| from huggingface_hub import hf_hub_download |
| from tqdm import tqdm |
|
|
|
|
| DEFAULT_SELECTION_FILE = Path("selected_cases.json") |
| DEFAULT_REPO_MAP_FILE = Path("metadata/repo_map.json") |
|
|
|
|
| def normalize_repo_id(value: str) -> str: |
| """Accept either a repo id or a Hugging Face URL and return repo id.""" |
| value = value.strip().rstrip("/") |
| if value.startswith("http://") or value.startswith("https://"): |
| parsed = urlparse(value) |
| |
| parts = [p for p in parsed.path.split("/") if p] |
| if len(parts) >= 3 and parts[0] == "datasets": |
| return f"{parts[1]}/{parts[2]}" |
| raise ValueError(f"Cannot parse Hugging Face dataset repo URL: {value}") |
| return value |
|
|
|
|
| def load_json(path: Path) -> dict: |
| if not path.exists(): |
| raise FileNotFoundError(f"File not found: {path}") |
| return json.loads(path.read_text(encoding="utf-8")) |
|
|
|
|
| def load_repo_map(path: Path) -> dict[str, str]: |
| data = load_json(path) |
| if not isinstance(data, dict): |
| raise ValueError("repo_map.json must be a dictionary: part_id -> repo_id") |
| return {str(k): normalize_repo_id(str(v)) for k, v in data.items()} |
|
|
|
|
| def safe_output_path(output_dir: Path, case: dict, keep_shard_structure: bool) -> Path: |
| filename = Path(case["hf_zip_path"]).name |
| if keep_shard_structure: |
| |
| return output_dir / case["part_id"] / case["split"] / case["activity_type"] / filename |
| return output_dir / filename |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description="Download PhysInOne selected case zips.") |
| parser.add_argument( |
| "--selection", |
| type=Path, |
| default=DEFAULT_SELECTION_FILE, |
| help=f"selected_cases.json from filter_cases.py. Default: {DEFAULT_SELECTION_FILE}", |
| ) |
| parser.add_argument( |
| "--repo_map", |
| type=Path, |
| default=DEFAULT_REPO_MAP_FILE, |
| help=f"JSON mapping part_id to HF repo id. Default: {DEFAULT_REPO_MAP_FILE}", |
| ) |
| parser.add_argument( |
| "--output_dir", |
| type=Path, |
| default=Path("./PhysInOne"), |
| help="Local output directory. Default: ./PhysInOne", |
| ) |
| parser.add_argument( |
| "--repo_type", |
| type=str, |
| default="dataset", |
| help="Hugging Face repo type. Default: dataset", |
| ) |
| parser.add_argument( |
| "--revision", |
| type=str, |
| default="main", |
| help="Hugging Face revision/branch. Default: main", |
| ) |
| parser.add_argument( |
| "--token", |
| type=str, |
| default=None, |
| help="Optional Hugging Face token for gated/private repos.", |
| ) |
| parser.add_argument( |
| "--keep_shard_structure", |
| action="store_true", |
| help="Save as output_dir/part_id/Split/ActivityType/*.zip instead of a flat folder.", |
| ) |
| parser.add_argument( |
| "--dry_run", |
| action="store_true", |
| help="Print planned downloads without downloading.", |
| ) |
| parser.add_argument( |
| "--overwrite", |
| action="store_true", |
| help="Overwrite local files if they already exist.", |
| ) |
|
|
| args = parser.parse_args() |
|
|
| selection = load_json(args.selection) |
| repo_map = load_repo_map(args.repo_map) |
| cases = selection.get("cases", []) |
| if not isinstance(cases, list): |
| raise ValueError("selection JSON must contain a list field named 'cases'.") |
|
|
| args.output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| missing_parts = sorted({case["part_id"] for case in cases if case["part_id"] not in repo_map}) |
| if missing_parts: |
| raise KeyError( |
| "The following part IDs are missing from repo_map.json: " |
| + ", ".join(missing_parts) |
| ) |
|
|
| print(f"Cases to download: {len(cases)}") |
| if args.dry_run: |
| for case in cases[:20]: |
| repo_id = repo_map[case["part_id"]] |
| out_path = safe_output_path(args.output_dir, case, args.keep_shard_structure) |
| print(f"{repo_id} :: {case['hf_zip_path']} -> {out_path}") |
| if len(cases) > 20: |
| print(f"... and {len(cases) - 20} more") |
| return |
|
|
| failures = [] |
| for case in tqdm(cases, desc="Downloading cases"): |
| repo_id = repo_map[case["part_id"]] |
| filename = case["hf_zip_path"] |
| out_path = safe_output_path(args.output_dir, case, args.keep_shard_structure) |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
|
|
| if out_path.exists() and not args.overwrite: |
| continue |
|
|
| try: |
| cached_file = hf_hub_download( |
| repo_id=repo_id, |
| filename=filename, |
| repo_type=args.repo_type, |
| revision=args.revision, |
| token=args.token, |
| ) |
| shutil.copy2(cached_file, out_path) |
| except Exception as exc: |
| failures.append( |
| { |
| "case_id": case.get("case_id"), |
| "part_id": case.get("part_id"), |
| "repo_id": repo_id, |
| "hf_zip_path": filename, |
| "error": repr(exc), |
| } |
| ) |
|
|
| if failures: |
| failure_path = args.output_dir / "download_failures.json" |
| failure_path.write_text(json.dumps(failures, indent=2, ensure_ascii=False), encoding="utf-8") |
| print(f"Finished with {len(failures)} failures. See: {failure_path}") |
| else: |
| print("All downloads completed successfully.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|