File size: 5,657 Bytes
580f513 | 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 | #!/usr/bin/env python3
"""Augment a pinned Hub repository inventory with Xet file identities.
The ordinary Hub repository response contains file paths, sizes, and
LFS-compatible SHA-256 values. A non-following request to each resolve URL also
returns the Xet file ID used by this dataset's ``hub_xet_hash`` field. Only
response headers are requested; file payloads are not intentionally fetched.
"""
from __future__ import annotations
import argparse
import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import HTTPRedirectHandler, Request, build_opener
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001
return None
def clean_etag(value: str | None) -> str:
return (value or "").strip().strip('"')
def read_identity(url: str, timeout: int, retries: int) -> dict[str, object]:
opener = build_opener(NoRedirect)
last_error: Exception | None = None
for attempt in range(retries + 1):
request = Request(url, method="HEAD")
try:
response = opener.open(request, timeout=timeout)
headers = response.headers
except HTTPError as exc:
if exc.code not in {301, 302, 303, 307, 308}:
last_error = exc
headers = None
else:
headers = exc.headers
except URLError as exc:
last_error = exc
headers = None
if headers is not None:
xet_hash = headers.get("X-Xet-Hash")
linked_size = headers.get("X-Linked-Size")
linked_etag = clean_etag(headers.get("X-Linked-ETag"))
repo_commit = headers.get("X-Repo-Commit")
if xet_hash and linked_size and linked_etag and repo_commit:
return {
"xetHash": xet_hash.lower(),
"linkedSize": int(linked_size),
"linkedEtag": linked_etag.lower(),
"repoCommit": repo_commit,
}
last_error = ValueError("resolve headers omitted an identity field")
if attempt < retries:
time.sleep(0.5 * (attempt + 1))
raise RuntimeError(str(last_error or "unable to read resolve headers"))
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--repo-json", type=Path, required=True)
parser.add_argument("--repo-id", default="maxwellinked/time-lapse-artifacts")
parser.add_argument("--revision", required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--suffix", default=".mp4")
parser.add_argument("--workers", type=int, default=12)
parser.add_argument("--timeout", type=int, default=30)
parser.add_argument("--retries", type=int, default=2)
args = parser.parse_args()
inventory = json.loads(args.repo_json.read_text(encoding="utf-8"))
siblings = inventory.get("siblings") if isinstance(inventory, dict) else None
if not isinstance(siblings, list):
raise SystemExit("repository JSON must contain a siblings list")
targets: list[tuple[dict[str, object], str, str]] = []
for item in siblings:
if not isinstance(item, dict) or not isinstance(item.get("rfilename"), str):
continue
path = item["rfilename"]
if not path.lower().endswith(args.suffix.lower()):
continue
encoded_path = quote(path, safe="/")
url = (
f"https://huggingface.co/datasets/{args.repo_id}/"
f"resolve/{args.revision}/{encoded_path}"
)
targets.append((item, path, url))
failures: list[dict[str, str]] = []
completed = 0
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = {
executor.submit(read_identity, url, args.timeout, args.retries): (item, path)
for item, path, url in targets
}
for future in as_completed(futures):
item, path = futures[future]
try:
identity = future.result()
lfs = item.get("lfs")
expected_etag = lfs.get("sha256") if isinstance(lfs, dict) else None
expected_size = item.get("size")
if expected_etag and identity["linkedEtag"] != str(expected_etag).lower():
raise ValueError("resolve LFS identity differs from repository inventory")
if expected_size is not None and identity["linkedSize"] != int(expected_size):
raise ValueError("resolve size differs from repository inventory")
if identity["repoCommit"] != args.revision:
raise ValueError("resolve response came from a different revision")
item.update(identity)
except Exception as exc: # noqa: BLE001
failures.append({"path": path, "error": str(exc)})
completed += 1
if completed % 25 == 0 or completed == len(targets):
print(f"resolved {completed}/{len(targets)}", flush=True)
if failures:
print(json.dumps({"failures": failures}, indent=2))
raise SystemExit(1)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(inventory, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
print(json.dumps({"resolved_files": len(targets), "output": str(args.output)}, indent=2))
if __name__ == "__main__":
main()
|