Spaces:
Sleeping

clair / app /models.py
MVPRM's picture
Deploy 67f193d from GitHub
6444a02 verified
Raw History Blame Contribute Delete
3.16 kB
"""Model / index registry and loading of persisted artifacts."""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
from app.data import SentenceGroup
from app.retrieval import BM25Backend, DenseBackend, MeanPoolingEncoder
ARTIFACTS_DIR = Path(__file__).resolve().parent.parent / "artifacts"
# Pinned Hugging Face revisions (commit SHAs) so builds are reproducible.
DENSE_MODELS = {
"minilm": {
"hf_id": "sentence-transformers/all-MiniLM-L6-v2",
"revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
"max_length": 256,
},
"contracts_bert": {
"hf_id": "nlpaueb/bert-base-uncased-contracts",
"revision": "f918d2e0cf491ba2c5fcf9f82d5e9603b8c5f3ea",
"max_length": 256,
},
}
METHODS = ["bm25", *DENSE_MODELS]
def model_dir(method: str, artifacts_dir: Path = ARTIFACTS_DIR) -> Path:
return artifacts_dir / "models" / method
def embeddings_path(method: str, artifacts_dir: Path = ARTIFACTS_DIR) -> Path:
return artifacts_dir / f"embeddings_{method}.npy"
def download_model(method: str, artifacts_dir: Path = ARTIFACTS_DIR) -> Path:
from huggingface_hub import snapshot_download
spec = DENSE_MODELS[method]
target = model_dir(method, artifacts_dir)
snapshot_download(
spec["hf_id"], revision=spec["revision"], local_dir=target,
allow_patterns=["*.json", "vocab.txt", "model.safetensors", "pytorch_model.bin"]
if method == "contracts_bert" else ["*.json", "vocab.txt", "model.safetensors"],
)
return target
def load_encoder(method: str, artifacts_dir: Path = ARTIFACTS_DIR) -> MeanPoolingEncoder:
path = model_dir(method, artifacts_dir)
if not path.exists():
raise FileNotFoundError(f"Model for {method!r} not found at {path}; run scripts/build_index.py")
return MeanPoolingEncoder(str(path), max_length=DENSE_MODELS[method]["max_length"])
def load_corpus(artifacts_dir: Path = ARTIFACTS_DIR) -> list[SentenceGroup]:
data = json.loads((artifacts_dir / "corpus.json").read_text(encoding="utf-8"))
return [SentenceGroup.from_dict(d) for d in data]
def load_backend(method: str, groups: list[SentenceGroup], artifacts_dir: Path = ARTIFACTS_DIR):
texts = [g.text for g in groups]
if method == "bm25":
# Term statistics are rebuilt deterministically from the persisted corpus (<1 s).
return BM25Backend(texts)
if method not in DENSE_MODELS:
raise ValueError(f"Unknown method {method!r}; expected one of {METHODS}")
embeddings = np.load(embeddings_path(method, artifacts_dir))
if embeddings.shape[0] != len(groups):
raise ValueError(f"{method} embeddings have {embeddings.shape[0]} rows, corpus has {len(groups)}")
return DenseBackend(method, load_encoder(method, artifacts_dir), embeddings)
def selected_method(artifacts_dir: Path = ARTIFACTS_DIR) -> str:
"""Backend frozen by the development evaluation (falls back to BM25 before selection)."""
path = artifacts_dir / "selection.json"
if path.exists():
return json.loads(path.read_text(encoding="utf-8"))["selected"]
return "bm25"