File size: 5,185 Bytes
1689e06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""Semantic encoder with a graceful offline fallback.

Preferred path: sentence-transformers (all-MiniLM-L6-v2, 384-dim).
  - First attempts local-files-only to honour the "no network during ranking"
    constraint.
  - If the model is not cached yet, allows a one-time download (first run).

Fallback path: TF-IDF + truncated SVD (pure scikit-learn, no downloads).
  - Engages automatically when sentence-transformers is not installed.
  - Produces up to 384 SVD components, L2-normalised — same dot-product API.

Either way, ``encode`` returns L2-normalised vectors so a dot product equals
cosine similarity, and ``cosine_similarity`` is a thin helper.
"""
from __future__ import annotations

import numpy as np


class SemanticEncoder:
    """Wraps sentence-transformers with an automatic scikit-learn fallback."""

    def __init__(self, model_name: str = "all-MiniLM-L6-v2") -> None:
        self.model_name = model_name
        self._backend: str | None = None
        self._st_model = None
        self._tfidf    = None
        self._svd      = None

    # ------------------------------------------------------------------
    # Backend detection
    # ------------------------------------------------------------------

    def _try_load_sentence_transformer(self) -> bool:
        """Try to load the ST model; allow download on first run."""
        try:
            from sentence_transformers import SentenceTransformer

            # First attempt: local cache only (fast, honours offline constraint).
            try:
                self._st_model = SentenceTransformer(
                    self.model_name, local_files_only=True
                )
                self._backend = "sentence_transformer"
                print(f"      [encoder] sentence-transformers (cached)", flush=True)
                return True
            except Exception:
                pass

            # Second attempt: allow download (first-time setup).
            print(
                f"      [encoder] Downloading {self.model_name} …"
                " (one-time; cached for future runs)",
                flush=True,
            )
            self._st_model = SentenceTransformer(self.model_name)
            self._backend = "sentence_transformer"
            print(f"      [encoder] sentence-transformers ready", flush=True)
            return True

        except Exception:
            return False

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def fit(self, corpus: list[str]) -> "SemanticEncoder":
        """Prepare the encoder.  ``corpus`` is used to train the TF-IDF fallback."""
        if self._try_load_sentence_transformer():
            return self

        # Fallback: TF-IDF + truncated SVD
        print("      [encoder] sentence-transformers unavailable → TF-IDF+SVD fallback",
              flush=True)
        from sklearn.decomposition import TruncatedSVD
        from sklearn.feature_extraction.text import TfidfVectorizer

        self._tfidf = TfidfVectorizer(
            lowercase=True,
            ngram_range=(1, 2),
            min_df=1,           # min_df=1 so tiny corpora (sample) still work
            max_features=60_000,
            sublinear_tf=True,
            stop_words="english",
        )
        matrix = self._tfidf.fit_transform(corpus)
        n_comp = min(384, matrix.shape[0] - 1, matrix.shape[1] - 1)
        n_comp = max(2, n_comp)
        self._svd = TruncatedSVD(n_components=n_comp, random_state=42)
        self._svd.fit(matrix)
        self._backend = "tfidf_svd"
        print(f"      [encoder] TF-IDF+SVD ({n_comp} components)", flush=True)
        return self

    def encode(self, texts: list[str]) -> np.ndarray:
        if self._backend == "sentence_transformer":
            vecs = self._st_model.encode(
                texts,
                batch_size=64,
                show_progress_bar=False,
                convert_to_numpy=True,
                normalize_embeddings=True,
            )
            return vecs.astype(np.float32)

        if self._backend == "tfidf_svd":
            matrix = self._tfidf.transform(texts)
            vecs   = self._svd.transform(matrix).astype(np.float32)
            return _l2_normalize(vecs)

        raise RuntimeError("Encoder not fitted. Call fit() first.")

    @property
    def backend(self) -> str:
        return self._backend or "uninitialized"


# ---------------------------------------------------------------------------
# Utilities
# ---------------------------------------------------------------------------

def _l2_normalize(vecs: np.ndarray) -> np.ndarray:
    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    norms[norms == 0] = 1.0
    return vecs / norms


def cosine_similarity(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
    """Compute cosine similarity between a single query vector and a matrix.

    Args:
        query:  shape (d,), must be L2-normalised.
        matrix: shape (n, d), must be L2-normalised.

    Returns:
        shape (n,) of similarities in [-1, 1].
    """
    return matrix @ query