Spaces:
Running on Zero
Running on Zero
File size: 2,524 Bytes
003b05a 3d6ae90 003b05a 35d8fb6 003b05a 35d8fb6 003b05a 35d8fb6 003b05a 3d6ae90 003b05a 3d6ae90 003b05a 3d6ae90 003b05a 35d8fb6 003b05a 35d8fb6 | 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 | """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})"
)
|