embedstamp 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
embedstamp/demo.py ADDED
@@ -0,0 +1,103 @@
1
+ """Offline practice demo: the silent same-dimension model swap, caught and repaired.
2
+
3
+ Read top to bottom: build an index with model A, swap in model B, watch results change without
4
+ an error, let the fingerprint catch it, migrate, switch. Uses the fake embedder only.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import tempfile
10
+ from collections.abc import Callable
11
+ from importlib import resources
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ from ._vectors import Embedder
17
+ from .embedders import FakeEmbedder
18
+ from .fingerprint import stamp
19
+ from .i18n import Translator
20
+ from .migrate import migrate, overlap_at_k
21
+ from .stores.local import LocalIndex
22
+ from .verify import verify
23
+
24
+ K = 10
25
+
26
+
27
+ def load_lines(name: str) -> list[str]:
28
+ """Read a bundled data file (one entry per line)."""
29
+ text = resources.files("embedstamp").joinpath("data", name).read_text(encoding="utf-8")
30
+ return [line for line in text.splitlines() if line.strip()]
31
+
32
+
33
+ def build_index(path: Path, embed: Embedder, model: str) -> LocalIndex:
34
+ """Index the demo corpus with ``embed`` and stamp it with ``model``'s fingerprint."""
35
+ docs = load_lines("demo_corpus.txt")
36
+ index = LocalIndex(path)
37
+ index.add([f"doc-{i:03d}" for i in range(len(docs))], docs, np.asarray(embed(docs)))
38
+ index.save(stamp(embed, model=model))
39
+ return index
40
+
41
+
42
+ def mean_overlap_at_k(
43
+ index: LocalIndex, queries: list[str], reference: Embedder, current: Embedder, k: int = K
44
+ ) -> float:
45
+ """Average top-k overlap between results found with ``reference`` and with ``current``."""
46
+ scores = [
47
+ overlap_at_k(
48
+ index.query(np.asarray(reference([q]))[0], k), index.query(np.asarray(current([q]))[0], k), k
49
+ )
50
+ for q in queries
51
+ ]
52
+ return float(np.mean(scores))
53
+
54
+
55
+ def run_demo(tr: Translator, emit: Callable[[str], None] = print) -> int:
56
+ """Run the five-step story, writing lines through ``emit``. Returns an exit code (0)."""
57
+ queries = load_lines("demo_queries.txt")
58
+ model_a, model_b = "fake:a", "fake:b"
59
+ embed_a, embed_b = FakeEmbedder(model_a), FakeEmbedder(model_b)
60
+
61
+ emit(tr("mock.banner"))
62
+ with tempfile.TemporaryDirectory(prefix="embedstamp-demo-") as tmp:
63
+ # 1) 모델 A 로 인덱스를 만들고 지문을 찍는다
64
+ emit(tr("demo.step1", n=len(load_lines("demo_corpus.txt")), model=model_a, dim=embed_a.dim))
65
+ index = build_index(Path(tmp) / "demo", embed_a, model_a)
66
+ fp = index.load()
67
+ assert fp is not None
68
+ emit(tr("demo.stamped", model=fp.model, dim=fp.dim, digest=fp.digest[:12]))
69
+
70
+ # 2) 같은 차원의 모델 B 로 바꿔 질의한다 - 예외가 없고 결과만 조용히 바뀐다
71
+ emit(tr("demo.step2", model=model_b, dim=embed_b.dim, n=len(queries)))
72
+ baseline = mean_overlap_at_k(index, queries, embed_a, embed_a)
73
+ swapped = mean_overlap_at_k(index, queries, embed_a, embed_b)
74
+ emit(tr("demo.noerror"))
75
+ emit(tr("demo.overlap", k=K, value=f"{swapped:.2f}", baseline=f"{baseline:.2f}"))
76
+
77
+ # 3) 지문으로 불일치를 판정한다
78
+ emit(tr("demo.step3"))
79
+ verdict = verify(fp, embed_b, model=model_b)
80
+ emit(" " + tr("check.status", status=verdict.status, min_cos=f"{verdict.min_cos:.2f}",
81
+ mean_cos=f"{verdict.mean_cos:.2f}"))
82
+ emit(" " + tr("check.reasons") + " " + ", ".join(verdict.reasons))
83
+ emit(tr("demo.guard"))
84
+
85
+ # 4) green 컬렉션에 새 모델로 다시 임베딩한다
86
+ emit(tr("demo.step4", model=model_b))
87
+ report = migrate(index, embed_b, new_model=model_b, old_embed=embed_a, queries=queries, k=K)
88
+ emit(" " + tr("migrate.report", n_docs=report.n_docs, n_embedded=report.n_embedded,
89
+ n_skipped=report.n_skipped, green=report.green_name))
90
+ emit(" " + tr("migrate.self_recall", k=K, value=f"{report.self_recall_at_k:.2f}"))
91
+ emit(" " + tr("migrate.overlap", k=K, value=f"{report.overlap_at_k:.2f}"))
92
+
93
+ # 5) 이름을 전환하고 새 지문이 일치하는지 다시 확인한다
94
+ emit(tr("demo.step5"))
95
+ report = migrate(index, embed_b, new_model=model_b, switch=True)
96
+ emit(" " + tr("migrate.switched", store=index.name, model=model_b, blue=report.blue_name))
97
+ live = index.load()
98
+ assert live is not None
99
+ after = verify(live, embed_b, model=model_b)
100
+ emit(" " + tr("check.status", status=after.status, min_cos=f"{after.min_cos:.2f}",
101
+ mean_cos=f"{after.mean_cos:.2f}"))
102
+ emit(tr("demo.done"))
103
+ return 0
@@ -0,0 +1,48 @@
1
+ """Embedder adapters and the ``resolve_embedder`` spec parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import parse_qs
6
+
7
+ from .._vectors import Embedder
8
+ from .fake import FakeEmbedder
9
+
10
+ __all__ = ["Embedder", "FakeEmbedder", "resolve_embedder"]
11
+
12
+
13
+ def resolve_embedder(spec: str) -> tuple[Embedder, str]:
14
+ """Turn a spec string into ``(embedder, model_name)``.
15
+
16
+ * ``fake:<name>[?noise=0.05&scale=1.0&prefix=...&dim=384]`` - practice mock
17
+ * ``fastembed:<model>`` - real model, e.g. ``fastembed:BAAI/bge-small-en-v1.5``
18
+ """
19
+ kind, sep, rest = spec.partition(":")
20
+ if not sep or not rest:
21
+ raise ValueError(
22
+ f"invalid embedder spec {spec!r}; use fake:<name>[?noise=..] or fastembed:<model>"
23
+ )
24
+ if kind == "fake":
25
+ name, _, query = rest.partition("?")
26
+ opts = {k: v[-1] for k, v in parse_qs(query, keep_blank_values=True).items()}
27
+ unknown = set(opts) - {"noise", "scale", "prefix", "dim"}
28
+ if not name or unknown:
29
+ raise ValueError(
30
+ f"invalid fake spec {spec!r}; options are noise, scale, prefix, dim"
31
+ + (f" (unknown: {', '.join(sorted(unknown))})" if unknown else "")
32
+ )
33
+ try:
34
+ emb = FakeEmbedder(
35
+ f"fake:{name}",
36
+ dim=int(opts.get("dim", 384)),
37
+ noise=float(opts.get("noise", 0.0)),
38
+ scale=float(opts.get("scale", 1.0)),
39
+ prefix=opts.get("prefix", ""),
40
+ )
41
+ except ValueError as exc:
42
+ raise ValueError(f"invalid fake spec {spec!r}: {exc}") from exc
43
+ return emb, f"fake:{name}"
44
+ if kind == "fastembed":
45
+ from .fastembed import FastEmbedEmbedder
46
+
47
+ return FastEmbedEmbedder(rest), rest
48
+ raise ValueError(f"unknown embedder kind {kind!r}; use fake or fastembed")
@@ -0,0 +1,83 @@
1
+ """FakeEmbedder: a deterministic practice mock (no model, no network).
2
+
3
+ Each lower-cased word gets a fixed random vector; a sentence is the sum of its words, rotated
4
+ by an orthogonal matrix seeded from the *model name*, then normalised. So:
5
+
6
+ * the same model name always gives the same vectors, and sentences that share words are close
7
+ (search really works inside one model);
8
+ * a different model name gives the same dimension but a rotated coordinate system, so vectors
9
+ from two "models" are unrelated and nothing raises an error. This reproduces the silent
10
+ same-dimension swap, computed fresh every time.
11
+
12
+ The numbers are not those of real models. Real measurements are in the README.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import re
19
+ from collections.abc import Sequence
20
+ from functools import lru_cache
21
+
22
+ import numpy as np
23
+
24
+ _WORD = re.compile(r"\w+", re.UNICODE)
25
+
26
+
27
+ def _seed(*parts: str) -> int:
28
+ return int.from_bytes(hashlib.sha256("\x1f".join(parts).encode("utf-8")).digest()[:8], "big")
29
+
30
+
31
+ @lru_cache(maxsize=65536)
32
+ def _token_vector(token: str, dim: int) -> np.ndarray:
33
+ return np.random.default_rng(_seed("token", token, str(dim))).standard_normal(dim)
34
+
35
+
36
+ @lru_cache(maxsize=16)
37
+ def _rotation(model: str, dim: int) -> np.ndarray:
38
+ gauss = np.random.default_rng(_seed("rotation", model, str(dim))).standard_normal((dim, dim))
39
+ q, r = np.linalg.qr(gauss)
40
+ return q * np.sign(np.diag(r))
41
+
42
+
43
+ class FakeEmbedder:
44
+ """Callable ``list[str] -> (n, dim)`` float32 array.
45
+
46
+ ``noise`` adds a text-seeded perturbation of relative size ``2 * noise`` (``noise=0.05``
47
+ gives probe cosines near 0.995, the *drift* band). ``scale`` multiplies the normalised
48
+ vectors (cosine stays the same, the norm changes). ``prefix`` is prepended to every text,
49
+ modelling a changed prompt prefix. ``calls`` and ``texts_embedded`` count usage for tests.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ model: str,
55
+ dim: int = 384,
56
+ noise: float = 0.0,
57
+ scale: float = 1.0,
58
+ prefix: str = "",
59
+ ) -> None:
60
+ if dim < 2:
61
+ raise ValueError("dim must be >= 2")
62
+ if noise < 0 or scale <= 0:
63
+ raise ValueError("noise must be >= 0 and scale must be > 0")
64
+ self.model, self.dim, self.noise, self.scale, self.prefix = model, dim, noise, scale, prefix
65
+ self.calls = 0
66
+ self.texts_embedded = 0
67
+
68
+ def __call__(self, texts: Sequence[str]) -> np.ndarray:
69
+ self.calls += 1
70
+ self.texts_embedded += len(texts)
71
+ rows = np.stack([self._one(self.prefix + t) for t in texts]) if len(texts) else np.zeros((0, self.dim))
72
+ return rows.astype(np.float32)
73
+
74
+ def _one(self, text: str) -> np.ndarray:
75
+ tokens = _WORD.findall(text.lower()) or [text]
76
+ vec = np.sum([_token_vector(tok, self.dim) for tok in tokens], axis=0)
77
+ vec = vec @ _rotation(self.model, self.dim)
78
+ vec = vec / np.linalg.norm(vec)
79
+ if self.noise:
80
+ gen = np.random.default_rng(_seed("noise", self.model, text))
81
+ vec = vec + 2.0 * self.noise * gen.standard_normal(self.dim) / np.sqrt(self.dim)
82
+ vec = vec / np.linalg.norm(vec)
83
+ return vec * self.scale
@@ -0,0 +1,28 @@
1
+ """FastEmbedEmbedder: real local embeddings through fastembed (extra ``fastembed``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import numpy as np
8
+
9
+ from ..errors import missing_extra_error
10
+
11
+
12
+ class FastEmbedEmbedder:
13
+ """Callable wrapper around ``fastembed.TextEmbedding``.
14
+
15
+ The first use downloads the model (set ``FASTEMBED_CACHE_PATH`` to choose where; after that
16
+ ``HF_HUB_OFFLINE=1`` works offline). Slow first runs are normal.
17
+ """
18
+
19
+ def __init__(self, model: str, **kwargs: object) -> None:
20
+ try:
21
+ from fastembed import TextEmbedding
22
+ except ImportError as exc:
23
+ raise missing_extra_error("FastEmbedEmbedder", "fastembed", "fastembed") from exc
24
+ self.model = model
25
+ self._model = TextEmbedding(model_name=model, **kwargs) # type: ignore[arg-type]
26
+
27
+ def __call__(self, texts: Sequence[str]) -> np.ndarray:
28
+ return np.asarray(list(self._model.embed(list(texts))), dtype=np.float32)
embedstamp/errors.py ADDED
@@ -0,0 +1,65 @@
1
+ """Exception types raised by embedstamp. Messages are English and say how to fix the problem."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING: # pragma: no cover - import only for type checkers
8
+ from .verify import Verdict
9
+
10
+
11
+ def missing_extra_error(name: str, package: str, extra: str) -> ImportError:
12
+ """The ImportError for a feature whose optional dependency (extra) is not installed.
13
+
14
+ One message for every place that needs an extra (top-level lazy import, ChromaStore,
15
+ FastEmbedEmbedder), so the README troubleshooting table matches all of them.
16
+ """
17
+ # 설치 방법 두 가지(내 프로젝트·clone 한 레포)를 모두 알려 준다
18
+ return ImportError(
19
+ f"{name} needs the optional dependency {package!r}; install it with "
20
+ f"pip install \"embedstamp[{extra}]\" (in a clone: uv sync --extra {extra})",
21
+ name=package,
22
+ )
23
+
24
+
25
+ class EmbedstampError(Exception):
26
+ """Base class for every error embedstamp raises on purpose."""
27
+
28
+
29
+ class EmbeddingMismatchError(EmbedstampError):
30
+ """The current embedder does not produce the vectors the index was built with."""
31
+
32
+ def __init__(self, verdict: "Verdict") -> None:
33
+ self.verdict = verdict
34
+ cos = "n/a" if verdict.min_cos is None else f"{verdict.min_cos:.4f}"
35
+ super().__init__(
36
+ f"embedding model mismatch: status={verdict.status}, min_cos={cos}, "
37
+ f"reasons={', '.join(verdict.reasons) or '-'}; "
38
+ f"stored model={verdict.stored.model!r}, current model={verdict.current.model!r}. "
39
+ "Use the embedder the index was built with, or re-embed with embedstamp.migrate()."
40
+ )
41
+
42
+
43
+ class FingerprintNotFoundError(EmbedstampError):
44
+ """The store has no fingerprint yet."""
45
+
46
+ def __init__(self, where: str = "the store") -> None:
47
+ super().__init__(
48
+ f"no fingerprint found in {where}; run embedstamp.stamp(...) and store.save(...) "
49
+ "(or `embedstamp stamp`) while the index is still built with a known model."
50
+ )
51
+
52
+
53
+ class FingerprintTooLargeError(EmbedstampError):
54
+ """The fingerprint does not fit the store's metadata limit."""
55
+
56
+
57
+ class SwitchRefusedError(EmbedstampError):
58
+ """migrate(switch=True) was asked to switch, but the new collection failed its quality check.
59
+
60
+ The finished report (green collection kept, nothing switched) is available as ``.report``.
61
+ """
62
+
63
+ def __init__(self, message: str, report: object | None = None) -> None:
64
+ super().__init__(message)
65
+ self.report = report
@@ -0,0 +1,179 @@
1
+ """The fingerprint: what gets stored next to a vector index to identify its embedding model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from collections.abc import Mapping, Sequence
10
+ from dataclasses import asdict, dataclass, field
11
+ from datetime import datetime, timezone
12
+ from functools import lru_cache
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+
17
+ from ._vectors import Embedder, as_matrix, raw_dtype, unit_rows
18
+ from .probes import probe_set_id, resolve_probes
19
+
20
+ SCHEMA_VERSION = 1
21
+ PROJECTION_DIMS = 32
22
+ _PROJECTION_SEED = 20261127
23
+
24
+
25
+ @lru_cache(maxsize=8)
26
+ def _projection_matrix(dim: int) -> np.ndarray:
27
+ """Seeded random projection ``dim -> 32``; identical on every machine for a given dim."""
28
+ rng = np.random.default_rng(_PROJECTION_SEED + dim)
29
+ return (rng.standard_normal((dim, PROJECTION_DIMS)) / np.sqrt(PROJECTION_DIMS)).astype(np.float64)
30
+
31
+
32
+ def project(vectors: np.ndarray) -> np.ndarray:
33
+ """Project unit-length probe vectors to 32 dimensions, shape ``(n, 32)``."""
34
+ return unit_rows(vectors.astype(np.float64)) @ _projection_matrix(vectors.shape[1])
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Fingerprint:
39
+ """Identity card of the embedding model that produced the vectors in an index."""
40
+
41
+ schema: int
42
+ model: str
43
+ dim: int
44
+ dtype: str
45
+ normalized: bool
46
+ norm_mean: float
47
+ doc_prefix: str
48
+ query_prefix: str
49
+ probe_set: str
50
+ probes_fp16: str | None
51
+ projection32: list[float]
52
+ digest: str
53
+ created_at: str
54
+ extra: dict[str, Any] = field(default_factory=dict)
55
+
56
+ @property
57
+ def n_probes(self) -> int:
58
+ return len(self.projection32) // PROJECTION_DIMS
59
+
60
+ def probe_vectors(self) -> np.ndarray | None:
61
+ """Decode the stored probe vectors (float16 precision), or None for compact fingerprints."""
62
+ if self.probes_fp16 is None:
63
+ return None
64
+ raw = base64.b64decode(self.probes_fp16)
65
+ return np.frombuffer(raw, dtype="<f2").astype(np.float32).reshape(self.n_probes, self.dim)
66
+
67
+ def projection_matrix(self) -> np.ndarray:
68
+ return np.asarray(self.projection32, dtype=np.float64).reshape(self.n_probes, PROJECTION_DIMS)
69
+
70
+ def to_json(self) -> str:
71
+ return json.dumps(asdict(self), separators=(",", ":"), ensure_ascii=False)
72
+
73
+ @classmethod
74
+ def from_json(cls, text: str) -> "Fingerprint":
75
+ try:
76
+ data = json.loads(text)
77
+ if not isinstance(data, dict):
78
+ raise ValueError("not a JSON object")
79
+ if data.get("schema") != SCHEMA_VERSION:
80
+ raise ValueError(f"unsupported schema {data.get('schema')!r}")
81
+ return cls(**data)
82
+ except (TypeError, ValueError) as exc:
83
+ raise ValueError(
84
+ f"invalid embedstamp fingerprint ({exc}); re-create it with embedstamp.stamp()"
85
+ ) from exc
86
+
87
+ @classmethod
88
+ def from_file(cls, path: "str | os.PathLike[str]") -> "Fingerprint":
89
+ """Read a fingerprint file; undecodable bytes get the same fix-it message as bad JSON."""
90
+ try:
91
+ with open(path, encoding="utf-8") as fh:
92
+ text = fh.read()
93
+ except UnicodeDecodeError as exc:
94
+ raise ValueError(
95
+ f"invalid embedstamp fingerprint ({exc}); re-create it with embedstamp.stamp()"
96
+ ) from exc
97
+ return cls.from_json(text)
98
+
99
+
100
+ def _digest(
101
+ model: str, dim: int, dtype: str, doc_prefix: str, query_prefix: str, probe_set: str,
102
+ projection: np.ndarray,
103
+ ) -> str:
104
+ """Hash of the static fields plus the sign pattern of the projected probes.
105
+
106
+ Signs (a SimHash) make the digest immune to tiny numeric noise, while a different
107
+ model flips about half of the bits.
108
+ """
109
+ bits = np.packbits((projection >= 0).astype(np.uint8)).tobytes()
110
+ head = "\x1f".join([model, str(dim), dtype, doc_prefix, query_prefix, probe_set])
111
+ return hashlib.sha256(head.encode("utf-8") + b"\x00" + bits).hexdigest()[:32]
112
+
113
+
114
+ def build_fingerprint(
115
+ vectors: np.ndarray,
116
+ *,
117
+ model: str,
118
+ dtype: str,
119
+ doc_prefix: str = "",
120
+ query_prefix: str = "",
121
+ probe_set: str,
122
+ compact: bool = False,
123
+ extra: Mapping[str, Any] | None = None,
124
+ ) -> Fingerprint:
125
+ """Build a fingerprint from already embedded probe vectors."""
126
+ norms = np.linalg.norm(vectors.astype(np.float64), axis=1)
127
+ proj = project(vectors)
128
+ proj_stored = np.round(proj, 3)
129
+ probes_fp16 = None
130
+ if not compact:
131
+ probes_fp16 = base64.b64encode(vectors.astype("<f2").tobytes()).decode("ascii")
132
+ return Fingerprint(
133
+ schema=SCHEMA_VERSION,
134
+ model=model,
135
+ dim=int(vectors.shape[1]),
136
+ dtype=dtype,
137
+ normalized=bool(np.all(np.abs(norms - 1.0) <= 1e-3)),
138
+ norm_mean=round(float(norms.mean()), 4),
139
+ doc_prefix=doc_prefix,
140
+ query_prefix=query_prefix,
141
+ probe_set=probe_set,
142
+ probes_fp16=probes_fp16,
143
+ projection32=[float(x) for x in proj_stored.reshape(-1)],
144
+ digest=_digest(model, int(vectors.shape[1]), dtype, doc_prefix, query_prefix, probe_set, proj_stored),
145
+ created_at=datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
146
+ extra=dict(extra or {}),
147
+ )
148
+
149
+
150
+ def measure(embed: Embedder, probes: Sequence[str] | None, doc_prefix: str) -> tuple[np.ndarray, str]:
151
+ """Embed the probe sentences (with the document prefix) and return ``(vectors, dtype)``."""
152
+ texts = [doc_prefix + p for p in resolve_probes(probes)]
153
+ raw = embed(texts)
154
+ return as_matrix(raw, len(texts)), raw_dtype(raw)
155
+
156
+
157
+ def stamp(
158
+ embed: Embedder,
159
+ *,
160
+ model: str,
161
+ doc_prefix: str = "",
162
+ query_prefix: str = "",
163
+ probes: Sequence[str] | None = None,
164
+ compact: bool = False,
165
+ extra: Mapping[str, Any] | None = None,
166
+ ) -> Fingerprint:
167
+ """Embed the probe sentences with ``embed`` and return the fingerprint to store.
168
+
169
+ ``model`` is the name you want to record (for example ``"BAAI/bge-small-en-v1.5"``).
170
+ ``compact=True`` keeps only a 32-dimensional summary (about 2 KB) for stores with small
171
+ metadata limits; comparisons are then less precise.
172
+ """
173
+ if not model or not isinstance(model, str):
174
+ raise ValueError("model must be a non-empty string, e.g. model='BAAI/bge-small-en-v1.5'")
175
+ vectors, dtype = measure(embed, probes, doc_prefix)
176
+ return build_fingerprint(
177
+ vectors, model=model, dtype=dtype, doc_prefix=doc_prefix, query_prefix=query_prefix,
178
+ probe_set=probe_set_id(probes), compact=compact, extra=extra,
179
+ )
embedstamp/guard.py ADDED
@@ -0,0 +1,83 @@
1
+ """Guard: check the embedder against the stored fingerprint once, then embed safely."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Sequence
7
+ from typing import Literal
8
+
9
+ import numpy as np
10
+
11
+ from ._vectors import Embedder, as_matrix
12
+ from .errors import EmbeddingMismatchError, FingerprintNotFoundError
13
+ from .stores import FingerprintStore
14
+ from .verify import Thresholds, Verdict, verify
15
+
16
+
17
+ class Guard:
18
+ """Wrap an embedder so that queries and inserts first prove it matches the index.
19
+
20
+ The check embeds the probe sentences once and caches the verdict, so later calls cost
21
+ nothing. ``on_mismatch="raise"`` raises :class:`EmbeddingMismatchError` for a different
22
+ model; ``"warn"`` only emits a :class:`UserWarning`. A ``drift`` verdict warns when
23
+ ``allow_drift`` is true and raises otherwise.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ store: FingerprintStore,
29
+ embed: Embedder,
30
+ *,
31
+ model: str,
32
+ doc_prefix: str = "",
33
+ query_prefix: str = "",
34
+ on_mismatch: Literal["raise", "warn"] = "raise",
35
+ allow_drift: bool = True,
36
+ thresholds: Thresholds = Thresholds(),
37
+ ) -> None:
38
+ if on_mismatch not in ("raise", "warn"):
39
+ raise ValueError("on_mismatch must be 'raise' or 'warn'")
40
+ self._store = store
41
+ self._embed = embed
42
+ self._model = model
43
+ self._doc_prefix = doc_prefix
44
+ self._query_prefix = query_prefix
45
+ self._on_mismatch = on_mismatch
46
+ self._allow_drift = allow_drift
47
+ self._thresholds = thresholds
48
+ self._verdict: Verdict | None = None
49
+
50
+ def check(self) -> Verdict:
51
+ """Return the verdict (computed on the first call, cached afterwards)."""
52
+ if self._verdict is not None:
53
+ return self._verdict
54
+ stored = self._store.load()
55
+ if stored is None:
56
+ raise FingerprintNotFoundError(type(self._store).__name__)
57
+ verdict = verify(
58
+ stored, self._embed, model=self._model, doc_prefix=self._doc_prefix,
59
+ query_prefix=self._query_prefix, thresholds=self._thresholds,
60
+ )
61
+ blocked = verdict.status == "different" or (verdict.status == "drift" and not self._allow_drift)
62
+ if blocked and self._on_mismatch == "raise":
63
+ raise EmbeddingMismatchError(verdict) # not cached: the next call checks again
64
+ if verdict.status != "same":
65
+ warnings.warn(
66
+ f"embedstamp: index fingerprint check says {verdict.status} "
67
+ f"(min_cos={verdict.min_cos}, reasons={', '.join(verdict.reasons)})",
68
+ UserWarning,
69
+ stacklevel=3,
70
+ )
71
+ self._verdict = verdict
72
+ return verdict
73
+
74
+ def embed_documents(self, texts: Sequence[str]) -> np.ndarray:
75
+ """Check, then embed ``texts`` with the document prefix; returns ``(n, d)``."""
76
+ self.check()
77
+ batch = [self._doc_prefix + t for t in texts]
78
+ return as_matrix(self._embed(batch), len(batch))
79
+
80
+ def embed_query(self, text: str) -> np.ndarray:
81
+ """Check, then embed one query with the query prefix; returns a 1-D vector."""
82
+ self.check()
83
+ return as_matrix(self._embed([self._query_prefix + text]), 1)[0]
embedstamp/i18n.py ADDED
@@ -0,0 +1,54 @@
1
+ """Language choice and message lookup for the CLI (English and Korean)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping
7
+ from functools import lru_cache
8
+ from importlib import resources
9
+
10
+ SUPPORTED = ("en", "ko")
11
+ ENV_ORDER = ("EMBEDSTAMP_LANG", "LC_ALL", "LC_MESSAGES", "LANG")
12
+
13
+
14
+ def _normalise(value: str) -> str:
15
+ """Map a language or locale string such as ``ko_KR.UTF-8`` to ``ko`` or ``en``."""
16
+ return "ko" if value.strip().lower().startswith("ko") else "en"
17
+
18
+
19
+ def resolve_lang(cli_lang: str | None, env: Mapping[str, str]) -> str:
20
+ """Pick the language: ``--lang`` > EMBEDSTAMP_LANG > LC_ALL > LC_MESSAGES > LANG.
21
+
22
+ The first non-empty source wins; anything that does not start with ``ko`` means English.
23
+ """
24
+ if cli_lang:
25
+ return _normalise(cli_lang)
26
+ for var in ENV_ORDER:
27
+ value = env.get(var, "")
28
+ if value.strip():
29
+ return _normalise(value)
30
+ return "en"
31
+
32
+
33
+ @lru_cache(maxsize=4)
34
+ def load_messages(lang: str) -> dict[str, str]:
35
+ """Load ``locales/<lang>.json``."""
36
+ if lang not in SUPPORTED:
37
+ raise ValueError(f"unsupported language {lang!r}; choose one of {', '.join(SUPPORTED)}")
38
+ text = resources.files("embedstamp").joinpath("locales", f"{lang}.json").read_text(encoding="utf-8")
39
+ return json.loads(text)
40
+
41
+
42
+ class Translator:
43
+ """``tr("key", name=value)`` returns the message of the chosen language."""
44
+
45
+ def __init__(self, lang: str) -> None:
46
+ self.lang = lang
47
+ self._messages = load_messages(lang)
48
+
49
+ def __call__(self, key: str, **fields: object) -> str:
50
+ return self._messages[key].format(**fields)
51
+
52
+ def raw(self, key: str) -> str:
53
+ """The message text without ``str.format`` (for %-style argparse templates)."""
54
+ return self._messages[key]