File size: 7,688 Bytes
10ed3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()