File size: 6,199 Bytes
ae0621a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/usr/bin/env python3
"""
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)
        # Expected: /datasets/PhysInOneP01/PhysInOneP01[/tree/main]
        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:
        # Preserve Split/ActivityType layout.
        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:  # Keep going and summarize failures.
            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()