syntax-video-infer / engine /weights.py
MesserMMP's picture
Rebuild CardioSyntax with custom bilingual UI and verified inference
1024e04 verified
Raw History Blame Contribute Delete
2.77 kB
"""Download only pinned tensor-only checkpoints and verify every checksum."""
import hashlib
import json
import os
from pathlib import Path
from .dicom import InferenceError
MANIFEST = json.loads(Path(__file__).with_name("manifest.json").read_text())
_verified = {}
def cache_root():
return Path(os.environ.get("SYNTAX_MODEL_CACHE", str(Path.home() / ".cache" / "syntax-space" / MANIFEST["revision"])))
def status():
files = MANIFEST["score_weights"] + [MANIFEST["classifier"]]
root = cache_root()
cached = sum((root / f["path"]).is_file() and (root / f["path"]).stat().st_size == f["size"] for f in files)
return {
"repo_id": MANIFEST["repo_id"], "revision": MANIFEST["revision"],
"models": 10, "classifier": True, "cached_files": cached,
"total_files": len(files), "cached": cached == len(files),
"device": os.environ.get("SYNTAX_DEVICE", "cpu"),
"loaded": False, "lazy": True,
"classifier_preprocessing": MANIFEST["preprocessing"]["classifier"],
}
def weight_file(record, progress=None):
path = cache_root() / record["path"]
if not path.is_file():
if progress:
progress("download", {"file": record["path"], "message": "Downloading a verified model checkpoint"})
from huggingface_hub import hf_hub_download
try:
path = Path(hf_hub_download(
repo_id=MANIFEST["repo_id"], filename=record["path"],
revision=MANIFEST["revision"], local_dir=str(cache_root()), token=False,
))
except Exception as exc:
raise InferenceError("A required model checkpoint could not be downloaded. Please retry.") from exc
stat = path.stat()
if "size" in record and stat.st_size != record["size"]:
raise InferenceError(f"Model checkpoint is incomplete: {record['path']}.")
key = (str(path.resolve()), stat.st_size, stat.st_mtime_ns, stat.st_ino)
if _verified.get(key) != record["sha256"]:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
digest.update(chunk)
if digest.hexdigest() != record["sha256"]:
raise InferenceError(f"Model checksum mismatch: {record['path']}. The checkpoint was not used.")
_verified[key] = record["sha256"]
return path
def calibration(progress=None):
record = MANIFEST["calibration"]
source = json.loads(weight_file(record, progress).read_text())
folds = [{"a": source[f"fold{i}"]["a"], "b": source[f"fold{i}"]["b"]} for i in range(5)]
if folds != record["folds"]:
raise InferenceError("Calibration coefficients do not match the pinned model release.")
return folds