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.
@@ -0,0 +1,165 @@
1
+ """ChromaStore: keep the fingerprint in a Chroma collection's metadata (extra ``chroma``).
2
+
3
+ Notes verified against chromadb 1.5.9: ``collection.modify(metadata=...)`` *replaces* the whole
4
+ metadata dict and refuses to receive ``hnsw:*`` keys again (the distance function lives in the
5
+ collection configuration and is kept). So ``save`` merges the existing non-``hnsw`` keys itself.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from collections.abc import Iterator, Sequence
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ from ..errors import FingerprintTooLargeError, missing_extra_error
17
+ from ..fingerprint import Fingerprint
18
+ from . import Doc, blue_name
19
+
20
+ METADATA_KEY = "embedstamp"
21
+
22
+
23
+ def _import_chromadb() -> Any:
24
+ try:
25
+ import chromadb
26
+ except ImportError as exc:
27
+ raise missing_extra_error("ChromaStore", "chromadb", "chroma") from exc
28
+ return chromadb
29
+
30
+
31
+ class ChromaStore:
32
+ """Adapter for a ``chromadb`` collection (vectors added directly, ``embedding_function=None``)."""
33
+
34
+ def __init__(self, collection: Any, client: Any | None = None) -> None:
35
+ self._collection = collection
36
+ self._client = client if client is not None else getattr(collection, "_client", None)
37
+
38
+ @classmethod
39
+ def open(cls, db_dir: str, name: str) -> "ChromaStore":
40
+ """Open an existing collection of a persistent Chroma database directory."""
41
+ chromadb = _import_chromadb()
42
+ from chromadb.config import Settings
43
+
44
+ # PersistentClient would silently create the directory; reads must not write.
45
+ if not os.path.isdir(db_dir):
46
+ raise ValueError(f"Chroma database directory not found: {db_dir}")
47
+
48
+ client = chromadb.PersistentClient(path=db_dir, settings=Settings(anonymized_telemetry=False))
49
+ try:
50
+ collection = client.get_collection(name, embedding_function=None)
51
+ except Exception as exc:
52
+ raise ValueError(f"collection {name!r} not found in {db_dir!r}: {exc}") from exc
53
+ return cls(collection, client)
54
+
55
+ @property
56
+ def name(self) -> str:
57
+ return str(self._collection.name)
58
+
59
+ @property
60
+ def collection(self) -> Any:
61
+ return self._collection
62
+
63
+ # ---- fingerprint -------------------------------------------------
64
+ def load(self) -> Fingerprint | None:
65
+ raw = (self._collection.metadata or {}).get(METADATA_KEY)
66
+ if raw is None:
67
+ return None
68
+ return Fingerprint.from_json(str(raw))
69
+
70
+ def save(self, fp: Fingerprint) -> None:
71
+ merged = {
72
+ k: v for k, v in (self._collection.metadata or {}).items() if not k.startswith("hnsw:")
73
+ }
74
+ merged[METADATA_KEY] = fp.to_json()
75
+ try:
76
+ self._collection.modify(metadata=merged)
77
+ except Exception as exc:
78
+ if any(word in str(exc).lower() for word in ("large", "size", "length", "limit")):
79
+ raise FingerprintTooLargeError(
80
+ f"Chroma refused the fingerprint metadata ({exc}); "
81
+ "use stamp(..., compact=True) or a SidecarStore"
82
+ ) from exc
83
+ raise
84
+
85
+ # ---- index API ---------------------------------------------------
86
+ def count(self) -> int:
87
+ return int(self._collection.count())
88
+
89
+ def existing_ids(self) -> set[str]:
90
+ return set(self._collection.get(include=[])["ids"])
91
+
92
+ def add(
93
+ self,
94
+ ids: Sequence[str],
95
+ texts: Sequence[str],
96
+ vectors: np.ndarray,
97
+ metadatas: Sequence[dict[str, Any]] | None = None,
98
+ ) -> None:
99
+ """Upsert documents with precomputed vectors (safe to repeat when resuming)."""
100
+ metas: list[dict[str, Any] | None] | None = None
101
+ if metadatas is not None and any(metadatas):
102
+ metas = [dict(m) if m else None for m in metadatas]
103
+ self._collection.upsert(
104
+ ids=list(ids),
105
+ embeddings=np.asarray(vectors, dtype=np.float32).tolist(),
106
+ documents=list(texts),
107
+ metadatas=metas,
108
+ )
109
+
110
+ def query(self, vector: np.ndarray, k: int = 10) -> list[str]:
111
+ n = self.count()
112
+ if n == 0:
113
+ return []
114
+ res = self._collection.query(
115
+ query_embeddings=[np.asarray(vector, dtype=np.float32).tolist()], n_results=min(k, n)
116
+ )
117
+ return list(res["ids"][0])
118
+
119
+ def iter_documents(self, batch_size: int = 64) -> Iterator[list[Doc]]:
120
+ offset = 0
121
+ while True:
122
+ res = self._collection.get(
123
+ limit=batch_size, offset=offset, include=["documents", "metadatas"]
124
+ )
125
+ ids = res["ids"]
126
+ if not ids:
127
+ return
128
+ docs = res["documents"] or [""] * len(ids)
129
+ metas = res["metadatas"] or [None] * len(ids)
130
+ yield [Doc(i, d or "", dict(m or {})) for i, d, m in zip(ids, docs, metas)]
131
+ offset += len(ids)
132
+
133
+ # ---- blue/green --------------------------------------------------
134
+ def create_sibling(self, name: str) -> "ChromaStore":
135
+ """Get or create an empty collection with the same distance function and extra metadata."""
136
+ meta = {
137
+ k: v
138
+ for k, v in (self._collection.metadata or {}).items()
139
+ if not k.startswith("hnsw:") and k != METADATA_KEY
140
+ }
141
+ kwargs: dict[str, Any] = {"metadata": meta or None, "embedding_function": None}
142
+ try:
143
+ space = self._collection.configuration["hnsw"]["space"]
144
+ kwargs["configuration"] = {"hnsw": {"space": space}}
145
+ except (KeyError, TypeError, AttributeError):
146
+ pass
147
+ return ChromaStore(self._client.get_or_create_collection(name, **kwargs), self._client)
148
+
149
+ def switch_to(self, sibling: "ChromaStore") -> str:
150
+ """Rename: this collection becomes ``<name>__blue_<date>``, ``sibling`` takes the old name.
151
+
152
+ Chroma has no aliases, so this is two renames and not atomic. If the second rename
153
+ fails the first is undone.
154
+ """
155
+ original = self.name
156
+ taken = {c.name for c in self._client.list_collections()}
157
+ blue_label = blue_name(original, taken)
158
+ self._collection.modify(name=blue_label)
159
+ try:
160
+ sibling._collection.modify(name=original)
161
+ except Exception as exc:
162
+ self._collection.modify(name=original)
163
+ raise RuntimeError(f"switch failed and was rolled back: {exc}") from exc
164
+ self._collection = sibling._collection
165
+ return blue_label
@@ -0,0 +1,158 @@
1
+ """LocalIndex: a tiny brute-force cosine index kept in a directory (docs, vectors, fingerprint).
2
+
3
+ Meant for demos, tests and small corpora. Layout: ``docs.jsonl``, ``vectors.npy``,
4
+ ``embedstamp.json``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from collections.abc import Iterator, Sequence
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+
17
+ from .._vectors import unit_rows
18
+ from ..fingerprint import Fingerprint
19
+ from . import Doc, blue_name
20
+ from .sidecar import atomic_write
21
+
22
+
23
+ class LocalIndex:
24
+ """Directory-backed vector index with cosine search."""
25
+
26
+ def __init__(self, path: str | os.PathLike[str]) -> None:
27
+ self.path = Path(path)
28
+ self._ids: list[str] = []
29
+ self._texts: list[str] = []
30
+ self._metas: list[dict[str, Any]] = []
31
+ self._vecs = np.zeros((0, 0), dtype=np.float32)
32
+ self._reload()
33
+
34
+ @property
35
+ def name(self) -> str:
36
+ return self.path.name
37
+
38
+ # ---- fingerprint -------------------------------------------------
39
+ def load(self) -> Fingerprint | None:
40
+ file = self.path / "embedstamp.json"
41
+ if not file.exists():
42
+ return None
43
+ return Fingerprint.from_file(file)
44
+
45
+ def save(self, fp: Fingerprint) -> None:
46
+ atomic_write(self.path / "embedstamp.json", fp.to_json())
47
+
48
+ # ---- persistence -------------------------------------------------
49
+ def _reload(self) -> None:
50
+ docs, vecs = self.path / "docs.jsonl", self.path / "vectors.npy"
51
+ self._ids, self._texts, self._metas = [], [], []
52
+ self._vecs = np.zeros((0, 0), dtype=np.float32)
53
+ if not (docs.exists() and vecs.exists()):
54
+ return
55
+ rows = [json.loads(line) for line in docs.read_text(encoding="utf-8").splitlines() if line]
56
+ matrix = np.load(vecs)
57
+ n = min(len(rows), matrix.shape[0]) # tolerate a crash between the two writes
58
+ self._ids = [r["id"] for r in rows[:n]]
59
+ self._texts = [r["text"] for r in rows[:n]]
60
+ self._metas = [r.get("metadata", {}) for r in rows[:n]]
61
+ self._vecs = matrix[:n].astype(np.float32)
62
+
63
+ def _persist(self) -> None:
64
+ self.path.mkdir(parents=True, exist_ok=True)
65
+ tmp = self.path / "vectors.npy.tmp"
66
+ with open(tmp, "wb") as fh:
67
+ np.save(fh, self._vecs)
68
+ os.replace(tmp, self.path / "vectors.npy")
69
+ lines = [
70
+ json.dumps({"id": i, "text": t, "metadata": m}, ensure_ascii=False)
71
+ for i, t, m in zip(self._ids, self._texts, self._metas)
72
+ ]
73
+ atomic_write(self.path / "docs.jsonl", "\n".join(lines) + ("\n" if lines else ""))
74
+
75
+ # ---- index API ---------------------------------------------------
76
+ def count(self) -> int:
77
+ return len(self._ids)
78
+
79
+ def existing_ids(self) -> set[str]:
80
+ return set(self._ids)
81
+
82
+ def add(
83
+ self,
84
+ ids: Sequence[str],
85
+ texts: Sequence[str],
86
+ vectors: np.ndarray,
87
+ metadatas: Sequence[dict[str, Any]] | None = None,
88
+ ) -> None:
89
+ """Insert or replace documents together with their vectors."""
90
+ vecs = np.asarray(vectors, dtype=np.float32)
91
+ if vecs.ndim != 2 or not (len(ids) == len(texts) == vecs.shape[0]):
92
+ raise ValueError("ids, texts and vectors must have the same length; vectors must be 2-D")
93
+ if self._vecs.shape[0] and vecs.shape[1] != self._vecs.shape[1]:
94
+ raise ValueError(
95
+ f"vector dimension {vecs.shape[1]} does not match the index dimension "
96
+ f"{self._vecs.shape[1]}; the index was built with a different embedding model"
97
+ )
98
+ if len(set(ids)) != len(ids):
99
+ raise ValueError("ids must be unique within one add() call")
100
+ metas = list(metadatas) if metadatas is not None else [{} for _ in ids]
101
+ position = {doc_id: i for i, doc_id in enumerate(self._ids)}
102
+ fresh_rows: list[np.ndarray] = []
103
+ for doc_id, text, meta, vec in zip(ids, texts, metas, vecs):
104
+ if doc_id in position:
105
+ i = position[doc_id]
106
+ self._texts[i], self._metas[i], self._vecs[i] = text, dict(meta), vec
107
+ else:
108
+ position[doc_id] = len(self._ids) + len(fresh_rows)
109
+ self._ids.append(doc_id)
110
+ self._texts.append(text)
111
+ self._metas.append(dict(meta))
112
+ fresh_rows.append(vec)
113
+ if fresh_rows:
114
+ stack = np.stack(fresh_rows)
115
+ self._vecs = stack if self._vecs.shape[0] == 0 else np.vstack([self._vecs, stack])
116
+ self._persist()
117
+
118
+ def query(self, vector: np.ndarray, k: int = 10) -> list[str]:
119
+ """Ids of the ``k`` most cosine-similar documents. Wrong dimensions raise ValueError."""
120
+ if not self._ids:
121
+ return []
122
+ vec = np.asarray(vector, dtype=np.float32).reshape(1, -1)
123
+ if vec.shape[1] != self._vecs.shape[1]:
124
+ raise ValueError(
125
+ f"query dimension {vec.shape[1]} does not match the index dimension {self._vecs.shape[1]}"
126
+ )
127
+ scores = (unit_rows(self._vecs) @ unit_rows(vec).T).ravel()
128
+ order = np.argsort(-scores, kind="stable")[:k]
129
+ return [self._ids[i] for i in order]
130
+
131
+ def iter_documents(self, batch_size: int = 64) -> Iterator[list[Doc]]:
132
+ for start in range(0, len(self._ids), batch_size):
133
+ end = start + batch_size
134
+ yield [
135
+ Doc(i, t, dict(m))
136
+ for i, t, m in zip(self._ids[start:end], self._texts[start:end], self._metas[start:end])
137
+ ]
138
+
139
+ # ---- blue/green --------------------------------------------------
140
+ def create_sibling(self, name: str) -> "LocalIndex":
141
+ """Open (or start) an empty index next to this one; an existing one is reused to resume."""
142
+ return LocalIndex(self.path.with_name(name))
143
+
144
+ def switch_to(self, sibling: "LocalIndex") -> str:
145
+ """Keep this index as ``<name>__blue_<date>`` and make ``sibling``'s data live under the
146
+ original name. Returns the blue name."""
147
+ taken = {p.name for p in self.path.parent.iterdir()}
148
+ blue_label = blue_name(self.name, taken)
149
+ blue = self.path.with_name(blue_label)
150
+ os.replace(self.path, blue)
151
+ try:
152
+ os.replace(sibling.path, self.path)
153
+ except OSError as exc:
154
+ os.replace(blue, self.path) # roll back so the live index is untouched
155
+ raise OSError(f"switch failed and was rolled back: {exc}") from exc
156
+ sibling.path = self.path
157
+ self._reload()
158
+ return blue_label
@@ -0,0 +1,31 @@
1
+ """SidecarStore: keep the fingerprint in a JSON file next to any index."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from ..fingerprint import Fingerprint
9
+
10
+
11
+ def atomic_write(path: Path, text: str) -> None:
12
+ """Write ``text`` to ``path`` without leaving a half-written file behind."""
13
+ path.parent.mkdir(parents=True, exist_ok=True)
14
+ tmp = path.with_name(path.name + ".tmp")
15
+ tmp.write_text(text, encoding="utf-8")
16
+ os.replace(tmp, path)
17
+
18
+
19
+ class SidecarStore:
20
+ """Fingerprint in a standalone JSON file, e.g. ``index.embedstamp.json``."""
21
+
22
+ def __init__(self, path: str | os.PathLike[str]) -> None:
23
+ self.path = Path(path)
24
+
25
+ def load(self) -> Fingerprint | None:
26
+ if not self.path.exists():
27
+ return None
28
+ return Fingerprint.from_file(self.path)
29
+
30
+ def save(self, fp: Fingerprint) -> None:
31
+ atomic_write(self.path, fp.to_json())
embedstamp/verify.py ADDED
@@ -0,0 +1,119 @@
1
+ """Compare the current embedder with a stored fingerprint: same, drift or different."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Literal
8
+
9
+ import numpy as np
10
+
11
+ from ._vectors import Embedder, row_cosines
12
+ from .fingerprint import Fingerprint, build_fingerprint, measure, project
13
+ from .probes import probe_set_id
14
+
15
+ Status = Literal["same", "drift", "different"]
16
+ _RANK = {"same": 0, "drift": 1, "different": 2}
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Thresholds:
21
+ """Cut-offs for the minimum probe cosine and the allowed relative norm change."""
22
+
23
+ same: float = 0.999
24
+ drift: float = 0.9
25
+ norm_rel_tol: float = 0.01
26
+
27
+ def __post_init__(self) -> None:
28
+ if not (0.0 <= self.drift <= self.same <= 1.0):
29
+ raise ValueError("thresholds must satisfy 0 <= drift <= same <= 1")
30
+ if self.norm_rel_tol < 0:
31
+ raise ValueError("norm_rel_tol must be >= 0")
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Verdict:
36
+ """Result of :func:`verify`.
37
+
38
+ ``reasons`` holds codes such as ``dim_changed``, ``model_name_changed``,
39
+ ``doc_prefix_changed``, ``query_prefix_changed``, ``norm_changed``,
40
+ ``normalization_changed``, ``probe_cosine_low``, ``probe_cosine_drift`` and
41
+ ``probe_set_changed``.
42
+ """
43
+
44
+ status: Status
45
+ min_cos: float | None
46
+ mean_cos: float | None
47
+ reasons: tuple[str, ...]
48
+ stored: Fingerprint
49
+ current: Fingerprint
50
+
51
+ @property
52
+ def compatible(self) -> bool:
53
+ """True unless the model is different (drift still counts as compatible)."""
54
+ return self.status != "different"
55
+
56
+
57
+ def verify(
58
+ stored: Fingerprint,
59
+ embed: Embedder,
60
+ *,
61
+ model: str,
62
+ doc_prefix: str = "",
63
+ query_prefix: str = "",
64
+ thresholds: Thresholds = Thresholds(),
65
+ probes: Sequence[str] | None = None,
66
+ ) -> Verdict:
67
+ """Embed the probe sentences with ``embed`` and judge them against ``stored``.
68
+
69
+ Order of checks: static fields (dimension, probe set, names, prefixes, norms), then the
70
+ cosine between stored and fresh probe vectors (minimum over probes).
71
+ """
72
+ vectors, dtype = measure(embed, probes, doc_prefix)
73
+ current = build_fingerprint(
74
+ vectors, model=model, dtype=dtype, doc_prefix=doc_prefix, query_prefix=query_prefix,
75
+ probe_set=probe_set_id(probes), compact=stored.probes_fp16 is None,
76
+ )
77
+ reasons: list[str] = []
78
+ status: Status = "same"
79
+
80
+ def raise_to(level: Status) -> None:
81
+ nonlocal status
82
+ if _RANK[level] > _RANK[status]:
83
+ status = level
84
+
85
+ if current.dim != stored.dim:
86
+ return Verdict("different", None, None, ("dim_changed",), stored, current)
87
+ if current.probe_set != stored.probe_set or vectors.shape[0] != stored.n_probes:
88
+ return Verdict("different", None, None, ("probe_set_changed",), stored, current)
89
+
90
+ if current.model != stored.model:
91
+ reasons.append("model_name_changed")
92
+ raise_to("drift")
93
+ if current.doc_prefix != stored.doc_prefix:
94
+ reasons.append("doc_prefix_changed")
95
+ raise_to("drift")
96
+ if current.query_prefix != stored.query_prefix:
97
+ reasons.append("query_prefix_changed")
98
+ raise_to("drift")
99
+ if abs(current.norm_mean - stored.norm_mean) > thresholds.norm_rel_tol * max(stored.norm_mean, 1e-9):
100
+ reasons.append("norm_changed")
101
+ raise_to("drift")
102
+ if current.normalized != stored.normalized:
103
+ reasons.append("normalization_changed")
104
+ raise_to("drift")
105
+
106
+ stored_vectors = stored.probe_vectors()
107
+ if stored_vectors is not None:
108
+ cos = row_cosines(stored_vectors, vectors)
109
+ else: # compact fingerprint: compare the 32-dimensional projections
110
+ cos = row_cosines(stored.projection_matrix(), project(vectors))
111
+ min_cos = float(np.min(cos))
112
+ mean_cos = float(np.mean(cos))
113
+ if min_cos < thresholds.drift:
114
+ reasons.append("probe_cosine_low")
115
+ raise_to("different")
116
+ elif min_cos < thresholds.same:
117
+ reasons.append("probe_cosine_drift")
118
+ raise_to("drift")
119
+ return Verdict(status, min_cos, mean_cos, tuple(reasons), stored, current)