|
| 1 | +"""Model index resolution + cached downloads (the dynamic-fetch layer). |
| 2 | +
|
| 3 | +Implements the models.yaml contract shared by the Ruby and TypeScript |
| 4 | +runtimes: resolve an id, reuse a verified cache copy, or download + |
| 5 | +sha256-verify + atomically install into the cache. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import hashlib |
| 11 | +import os |
| 12 | +import shutil |
| 13 | +import tempfile |
| 14 | +import urllib.request |
| 15 | +from dataclasses import dataclass |
| 16 | +from pathlib import Path |
| 17 | +from urllib.parse import urlparse |
| 18 | + |
| 19 | +import yaml |
| 20 | + |
| 21 | +DEFAULT_INDEX_URL = ( |
| 22 | + "https://raw.githubusercontent.com/interscript/ml-models/main/models.yaml" |
| 23 | +) |
| 24 | +ENV_INDEX = "INTERSCRIPT_ML_INDEX" |
| 25 | +ENV_CACHE = "INTERSCRIPT_ML_CACHE" |
| 26 | + |
| 27 | + |
| 28 | +class RegistryError(ValueError): |
| 29 | + """The index cannot be fetched/parsed, or the id is unknown.""" |
| 30 | + |
| 31 | + |
| 32 | +@dataclass(frozen=True) |
| 33 | +class IndexEntry: |
| 34 | + id: str |
| 35 | + filename: str |
| 36 | + url: str |
| 37 | + sha256: str |
| 38 | + size: int |
| 39 | + precision: str |
| 40 | + task: str |
| 41 | + |
| 42 | + |
| 43 | +def cache_dir() -> Path: |
| 44 | + if os.environ.get(ENV_CACHE): |
| 45 | + return Path(os.environ[ENV_CACHE]) |
| 46 | + return Path.home() / ".cache" / "interscript" |
| 47 | + |
| 48 | + |
| 49 | +def load_index(index_url: str | None = None) -> dict[str, IndexEntry]: |
| 50 | + source = index_url or os.environ.get(ENV_INDEX) or DEFAULT_INDEX_URL |
| 51 | + if source.startswith(("http://", "https://")): |
| 52 | + with urllib.request.urlopen(source) as response: |
| 53 | + text = response.read().decode("utf-8") |
| 54 | + else: |
| 55 | + text = Path(source).read_text(encoding="utf-8") |
| 56 | + raw = yaml.safe_load(text) |
| 57 | + if not isinstance(raw, dict) or raw.get("version") != 1: |
| 58 | + raise RegistryError("index must be a mapping with version: 1") |
| 59 | + entries: dict[str, IndexEntry] = {} |
| 60 | + for model_id, spec in raw.get("models", {}).items(): |
| 61 | + entries[model_id] = IndexEntry( |
| 62 | + id=model_id, |
| 63 | + filename=spec["filename"], |
| 64 | + url=spec["url"], |
| 65 | + sha256=spec["sha256"], |
| 66 | + size=int(spec.get("size", 0)), |
| 67 | + precision=spec.get("precision", "fp32"), |
| 68 | + task=spec.get("task", ""), |
| 69 | + ) |
| 70 | + return entries |
| 71 | + |
| 72 | + |
| 73 | +def _sha256_file(path: Path) -> str: |
| 74 | + digest = hashlib.sha256() |
| 75 | + with path.open("rb") as fh: |
| 76 | + while chunk := fh.read(1024 * 1024): |
| 77 | + digest.update(chunk) |
| 78 | + return digest.hexdigest() |
| 79 | + |
| 80 | + |
| 81 | +def resolve(model_id: str, index_url: str | None = None) -> Path: |
| 82 | + """Return a verified local zip path for `model_id`, downloading and |
| 83 | + installing into the cache when needed. Never returns an unverified |
| 84 | + file: cache hits are re-verified against the index sha256.""" |
| 85 | + entries = load_index(index_url) |
| 86 | + if model_id not in entries: |
| 87 | + raise RegistryError( |
| 88 | + f"unknown model id {model_id!r} (known: {sorted(entries)})" |
| 89 | + ) |
| 90 | + entry = entries[model_id] |
| 91 | + target = cache_dir() / "models" / model_id / entry.filename |
| 92 | + if target.is_file() and _sha256_file(target) == entry.sha256: |
| 93 | + return target |
| 94 | + |
| 95 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 96 | + fd, tmp_name = tempfile.mkstemp(dir=target.parent, suffix=".part") |
| 97 | + os.close(fd) |
| 98 | + downloaded = Path(tmp_name) |
| 99 | + if entry.url.startswith("file://"): |
| 100 | + source = Path(urlparse(entry.url).path) |
| 101 | + if not source.is_file(): |
| 102 | + raise RegistryError(f"channel file missing: {source}") |
| 103 | + shutil.copyfile(source, downloaded) # file:// is a mirror, not a move |
| 104 | + else: |
| 105 | + urllib.request.urlretrieve(entry.url, downloaded) |
| 106 | + try: |
| 107 | + actual = _sha256_file(downloaded) |
| 108 | + if actual != entry.sha256: |
| 109 | + raise RegistryError( |
| 110 | + f"downloaded {entry.filename} sha256 mismatch: got {actual}, " |
| 111 | + f"index says {entry.sha256}" |
| 112 | + ) |
| 113 | + if downloaded != target: |
| 114 | + os.replace(downloaded, target) |
| 115 | + finally: |
| 116 | + if downloaded != target and downloaded.exists(): |
| 117 | + downloaded.unlink() |
| 118 | + return target |
0 commit comments