File size: 2,387 Bytes
8608670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c95195c
 
 
 
 
 
 
 
 
 
 
8608670
 
 
 
 
 
 
c95195c
 
 
 
 
 
8608670
c95195c
8608670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()