Spaces:
Sleeping

File size: 3,159 Bytes
6444a02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""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"