hetchyy's picture
deploy qua@32f334a1
3d6ae90 verified
Raw History Blame Contribute Delete
2.52 kB
"""Fetch, verify and select the prebuilt SDK cache named by ``deploy.json``.
``qua-deploy`` builds the chapter refs, anchor indexes and word forms once per
SDK/phonemizer content key, and the native word-form table timing reads under its
own key, and stores both in the private bucket. A deployed Space downloads them
into one directory before the SDK is imported, checks each sha256 and the
phonemizer version, and points ``QUA_SDK_CACHE_DIR`` at it. Local development lets
the SDK build its own cache.
"""
from __future__ import annotations
import hashlib
import importlib.metadata
import os
from pathlib import Path
from src.core.install_sdk import PRIVATE_BUILD_ROOT, bucket_fs, load_deploy
CACHE_ROOT = PRIVATE_BUILD_ROOT / "sdk-cache"
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def configure_bundled_sdk_cache() -> Path | None:
"""Fail closed on a stale or corrupt cache, then point the SDK at it."""
deploy = load_deploy()
if deploy is None:
return None
cache = deploy["sdk_cache"]
phonemizer = importlib.metadata.version("quranic-phonemizer")
if cache["phonemizer_version"] != phonemizer:
raise RuntimeError(
f"SDK cache was built with quranic-phonemizer {cache['phonemizer_version']}, "
f"the Space runs {phonemizer}"
)
cache_dir = CACHE_ROOT / cache["key"]
cache_dir.mkdir(parents=True, exist_ok=True)
parts = [cache, cache.get("forms") or {"prefix": "", "files": {}}]
for part in parts:
_fetch(deploy["bucket"], part["prefix"], part["files"], cache_dir)
os.environ["QUA_SDK_CACHE_DIR"] = str(cache_dir)
count = sum(len(part["files"]) for part in parts)
print(f"[SDK] Using {count} verified prebuilt cache files from {cache_dir}")
return cache_dir
def _fetch(bucket: str, prefix: str, files: dict[str, str], cache_dir: Path) -> None:
fs = None
for name, expected in files.items():
path = cache_dir / name
if path.is_file() and _sha256(path) == expected:
continue
fs = fs or bucket_fs()
fs.get_file(f"hf://buckets/{bucket}/{prefix}/{name}", str(path))
actual = _sha256(path)
if actual != expected:
raise RuntimeError(
f"SDK cache failed integrity check: {name} (expected {expected}, got {actual})"
)