Reference-Update-Benchmark / tools /check_dependencies.py
leoncca's picture
Add files using upload-large-folder tool
c8beaf3 verified
Raw
History Blame Contribute Delete
5.42 kB
#!/usr/bin/env python3
"""Read-only verification of fixed Hugging Face dependency objects."""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path
def read_tsv(path: Path) -> list[dict[str, str]]:
with path.open("r", encoding="utf-8", newline="") as handle:
return list(csv.DictReader(handle, delimiter="\t"))
def fetch_tree(repo: str, revision: str) -> dict[str, dict[str, object]]:
encoded = urllib.parse.quote(repo, safe="/")
rev = urllib.parse.quote(revision, safe="")
url = f"https://huggingface.co/api/datasets/{encoded}/tree/{rev}?recursive=true&expand=true"
with urllib.request.urlopen(url, timeout=60) as response:
rows = json.load(response)
return {str(row["path"]): row for row in rows if row.get("type") == "file"}
def full_remote_sha(repo: str, revision: str, path: str) -> str:
url = (
f"https://huggingface.co/datasets/{repo}/resolve/{revision}/"
f"{urllib.parse.quote(path)}?download=true"
)
digest = hashlib.sha256()
with urllib.request.urlopen(url, timeout=60) as response:
while True:
chunk = response.read(8 * 1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def range_remote_sha(repo: str, revision: str, path: str, start: int, end: int) -> str:
url = (
f"https://huggingface.co/datasets/{repo}/resolve/{revision}/"
f"{urllib.parse.quote(path)}?download=true"
)
request = urllib.request.Request(url, headers={"Range": f"bytes={start}-{end}"})
with urllib.request.urlopen(request, timeout=60) as response:
if response.status != 206:
raise ValueError(f"server did not honor byte range: HTTP {response.status}")
payload = response.read()
if len(payload) != end - start + 1:
raise ValueError(f"range length mismatch: {len(payload)} != {end - start + 1}")
return hashlib.sha256(payload).hexdigest()
def main() -> int:
default = Path(__file__).resolve().parents[1] / "dependencies" / "DEPENDENCIES.tsv"
parser = argparse.ArgumentParser()
parser.add_argument("--dependencies", type=Path, default=default)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
rows = read_tsv(args.dependencies)
trees: dict[tuple[str, str], dict[str, dict[str, object]]] = {}
results: list[dict[str, object]] = []
failed = 0
for row in rows:
key = (row["source_repo"], row["source_revision"])
if key not in trees:
trees[key] = fetch_tree(*key)
remote = trees[key].get(row["repository_path"])
status = "PASS"
method = "lfs_oid"
detail = ""
if remote is None:
status, detail = "FAIL", "path missing"
elif int(remote.get("size", -1)) != int(row["bytes"]):
status, detail = "FAIL", f"size {remote.get('size')} != {row['bytes']}"
elif remote.get("lfs"):
oid = str(remote["lfs"].get("oid", ""))
if oid != row["sha256"]:
status, detail = "FAIL", f"LFS oid {oid} != expected SHA-256"
elif int(row["bytes"]) <= 20_000_000:
method = "full_download_sha256"
actual = full_remote_sha(row["source_repo"], row["source_revision"], row["repository_path"])
if actual != row["sha256"]:
status, detail = "FAIL", f"SHA-256 {actual} != expected"
elif row.get("range_bytes") and row.get("range_first_sha256") and row.get("range_last_sha256"):
method = "fixed_range_sha256"
width = int(row["range_bytes"])
total = int(row["bytes"])
try:
first = range_remote_sha(
row["source_repo"], row["source_revision"], row["repository_path"], 0, width - 1
)
last = range_remote_sha(
row["source_repo"],
row["source_revision"],
row["repository_path"],
total - width,
total - 1,
)
if first != row["range_first_sha256"] or last != row["range_last_sha256"]:
status, detail = "FAIL", "fixed-range SHA-256 mismatch"
except Exception as exc:
status, detail = "UNRESOLVED", str(exc)
else:
method = "metadata_only"
status, detail = "UNRESOLVED", "no LFS oid and no fixed-range receipt"
if status == "FAIL":
failed += 1
results.append(
{
"component": row["component"],
"path": row["repository_path"],
"status": status,
"method": method,
"detail": detail,
}
)
receipt = {
"status": "PASS" if failed == 0 else "FAIL",
"checked": len(results),
"failed": failed,
"results": results,
"service_commitment": "none; this is a manually runnable verification capability",
}
text = json.dumps(receipt, indent=2, sort_keys=True) + "\n"
if args.output:
args.output.write_text(text, encoding="utf-8")
print(text, end="")
return 0 if failed == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())