Download FreiHAND/shared-v1.1/script/fetch_shared_subset.py from ParityLab/Hand-Datasets-Raw: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/FreiHAND/shared-v1.1/script/fetch_shared_subset.py
- Command line
-
hf download hf://datasets/ParityLab/Hand-Datasets-Raw/FreiHAND/shared-v1.1/script/fetch_shared_subset.py
-
curl -L -o fetch_shared_subset.py https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/FreiHAND/shared-v1.1/script/fetch_shared_subset.py
7.69 kB
| #!/usr/bin/env python3 | |
| """Fetch only non-media FreiHAND shared files at one immutable HF revision. | |
| No raw, RGB, depth, mask video, or preview image is downloaded. The manifest | |
| also lists omitted files for later unchanged-file reuse by the publisher. | |
| """ | |
| import argparse | |
| from concurrent.futures import ThreadPoolExecutor | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import shutil | |
| import subprocess | |
| import threading | |
| import time | |
| REPO = "ParityLab/Hand-Datasets-Raw" | |
| REVISION = "4b8768b9abfe60408d26f7893e771cd7f5a94613" | |
| PREFIX = "FreiHAND/shared-v1.0/" | |
| MEDIA = {".mkv", ".mp4", ".avi", ".mov", ".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff", ".bmp", ".gif"} | |
| PILOT = {"training_00000000", "evaluation_00000000"} | |
| HTTP = threading.local() | |
| def get(url, **kwargs): | |
| import requests | |
| if not hasattr(HTTP, "session"): | |
| HTTP.session = requests.Session() | |
| for attempt in range(3): | |
| try: | |
| response = HTTP.session.get(url, timeout=(30, 90), **kwargs) | |
| except (requests.Timeout, requests.ConnectionError): | |
| if attempt == 2: | |
| raise | |
| time.sleep(2 ** attempt) | |
| continue | |
| if response.status_code not in {429, 500, 502, 503, 504} or attempt == 2: | |
| response.raise_for_status() | |
| return response | |
| delay = max(2 ** attempt, float(response.headers.get("Retry-After", "0"))) | |
| response.close() | |
| if delay > 60: | |
| raise RuntimeError("Server requests a long pause; stop and resume later.") | |
| time.sleep(delay) | |
| def json_write(path, obj): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + "\n") | |
| temporary.replace(path) | |
| def file_digests(path): | |
| size = path.stat().st_size | |
| sha256 = hashlib.sha256() | |
| git = hashlib.sha1(f"blob {size}\0".encode()) | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| sha256.update(chunk) | |
| git.update(chunk) | |
| return {"size": size, "sha256": sha256.hexdigest(), "git_blob_sha1": git.hexdigest()} | |
| def verified(path, entry): | |
| result = file_digests(path) | |
| algorithm = entry["digest_algorithm"] | |
| if result["size"] != entry["size"] or result[algorithm] != entry["digest"]: | |
| raise ValueError(f"Source size/hash mismatch: {entry['path']}") | |
| return result | |
| def inventory(workspace): | |
| path = workspace / "tmp/source-manifest.json" | |
| if path.exists(): | |
| manifest = json.loads(path.read_text()) | |
| if manifest["revision"] != REVISION or manifest["repo"] != REPO: | |
| raise ValueError("Existing manifest is for a different source.") | |
| return manifest | |
| files = [] | |
| url = f"https://huggingface.co/api/datasets/{REPO}/tree/{REVISION}/{PREFIX.rstrip('/')}?recursive=true&expand=false&limit=1000" | |
| while url: | |
| response = get(url) | |
| for entry in response.json(): | |
| if entry["type"] != "file": | |
| continue | |
| relative = entry["path"].removeprefix(PREFIX) | |
| if relative == entry["path"] or ".." in Path(relative).parts: | |
| raise ValueError("Unexpected source path") | |
| lfs = entry.get("lfs") | |
| files.append({"path": entry["path"], "relative_path": relative, | |
| "size": entry["size"], "digest_algorithm": "sha256" if lfs else "git_blob_sha1", | |
| "digest": lfs["oid"] if lfs else entry["oid"], | |
| "download": Path(relative).suffix.lower() not in MEDIA}) | |
| url = response.links.get("next", {}).get("url") | |
| sizes = {} | |
| for name in ["FreiHAND", "HOT3D", "OakInk-v1", "OakInk-v2"]: | |
| sizes[name] = get(f"https://huggingface.co/api/datasets/{REPO}/treesize/{REVISION}/{name}/shared-v1.0").json()["size"] | |
| if sum(item["size"] for item in files) != sizes["FreiHAND"]: | |
| raise ValueError("Tree listing does not account for the complete source size") | |
| manifest = {"repo": REPO, "revision": REVISION, "source_prefix": PREFIX.rstrip("/"), | |
| "mode": "non_media_subset_not_complete_release", "dataset_full_sizes": sizes, | |
| "files": sorted(files, key=lambda item: item["path"])} | |
| json_write(path, manifest) | |
| return manifest | |
| def fetch_one(workspace, entry): | |
| path = workspace / "source/FreiHAND/shared-v1.0" / entry["relative_path"] | |
| if path.exists(): | |
| return {"path": entry["relative_path"], **verified(path, entry), "reused": True} | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(path.suffix + ".part") | |
| # curl IPv4 avoids repeated TLS handshakes seen on the Python/CDN route. | |
| # Retry only transport here; a failed content hash below is never retried. | |
| url = f"https://huggingface.co/datasets/{REPO}/resolve/{REVISION}/{entry['path']}?download=true" | |
| subprocess.run(["curl", "--ipv4", "--fail", "--location", "--silent", "--show-error", | |
| "--connect-timeout", "15", "--max-time", "120", "--retry", "6", | |
| "--retry-all-errors", "--retry-max-time", "300", "--output", str(temporary), url], | |
| check=True) | |
| result = verified(temporary, entry) | |
| temporary.replace(path) | |
| return {"path": entry["relative_path"], **result, "reused": False} | |
| def fetch_group(workspace, group): | |
| source = workspace / "source/FreiHAND/shared-v1.0" | |
| primary = next((entry for entry in group if (source / entry["relative_path"]).is_file()), group[0]) | |
| result = fetch_one(workspace, primary) | |
| results = [result] | |
| for entry in group: | |
| if entry is primary: | |
| continue | |
| path = source / entry["relative_path"] | |
| if not path.exists(): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(source / primary["relative_path"], path) | |
| results.append({"path": entry["relative_path"], **verified(path, entry), "reused": True}) | |
| return results | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--workspace", type=Path, required=True) | |
| parser.add_argument("--scope", choices=["inventory", "pilot", "all"], default="inventory") | |
| parser.add_argument("--workers", type=int, default=4) | |
| args = parser.parse_args() | |
| manifest = inventory(args.workspace) | |
| selected = [item for item in manifest["files"] if item["download"]] | |
| if args.scope == "pilot": | |
| selected = [item for item in selected if not item["relative_path"].startswith("data/") or Path(item["relative_path"]).parts[1] in PILOT] | |
| print(json.dumps({"scope": args.scope, "files": len(selected), "bytes": sum(item["size"] for item in selected), "revision": REVISION}), flush=True) | |
| if args.scope == "inventory": | |
| return | |
| groups = {} | |
| for entry in selected: | |
| groups.setdefault((entry["digest_algorithm"], entry["digest"]), []).append(entry) | |
| print(f"{len(groups)} distinct source blobs; identical hashes reused locally", flush=True) | |
| results = [] | |
| with ThreadPoolExecutor(max_workers=args.workers) as executor: | |
| for index, group_results in enumerate(executor.map(lambda group: fetch_group(args.workspace, group), groups.values()), 1): | |
| results.extend(group_results) | |
| if index % 25 == 0 or len(results) == len(selected): | |
| print(f"verified {len(results)}/{len(selected)}", flush=True) | |
| json_write(args.workspace / f"tmp/download-{args.scope}.json", {"revision": REVISION, "files": results, "total_bytes": sum(item["size"] for item in results)}) | |
| if __name__ == "__main__": | |
| main() | |