tacitus-source-lab / toolkit /research /fetch_models.py
Giuliocc's picture
Finalize Source Lab input, review, and export workflows
c95195c verified
Raw History Blame Contribute Delete
2.39 kB
"""Download and verify the browser-compatible weights from an immutable Hub revision."""
import argparse
import hashlib
import json
import os
import tempfile
from pathlib import Path
from urllib.request import urlopen
ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / "contracts/models.lock.json"
def verify(raw, artifact):
if len(raw) != artifact["bytes"] or hashlib.sha256(raw).hexdigest() != artifact["sha256"]:
return False
try:
record = json.loads(raw)
except (UnicodeError, json.JSONDecodeError):
return False
return (
isinstance(record, dict)
and record.get("model_id") == artifact["model_id"]
and record.get("model_revision") == artifact["model_revision"]
)
def fetch(directory, check_only):
lock = json.loads(MANIFEST.read_text())
base = f"https://huggingface.co/spaces/{lock['space']}/resolve/{lock['revision']}/"
for task, artifact in lock["models"].items():
destination = directory / artifact["file"]
if destination.is_file():
with destination.open("rb") as handle:
raw = handle.read(artifact["bytes"] + 1)
if verify(raw, artifact):
print(f"{task}: verified")
continue
if check_only:
raise SystemExit(f"{task}: missing file or model integrity mismatch")
with urlopen(base + artifact["path"], timeout=45) as response:
raw = response.read(artifact["bytes"] + 1)
if not verify(raw, artifact):
raise SystemExit(f"{task}: downloaded file failed integrity verification")
directory.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=directory, delete=False) as handle:
handle.write(raw)
temporary = Path(handle.name)
try:
os.replace(temporary, destination)
finally:
temporary.unlink(missing_ok=True)
print(f"{task}: downloaded and verified")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--directory", type=Path, default=ROOT / "space/models")
parser.add_argument(
"--check", action="store_true", help="Verify existing files without network access."
)
args = parser.parse_args()
fetch(args.directory, args.check)
if __name__ == "__main__":
main()