emeans-haystack 0.1.2__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,166 @@
1
+ # SPDX-FileCopyrightText: 2026-present ogaude <ogaude.code@proton.me>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import math
6
+ from typing import Any, Literal
7
+
8
+ import numpy as np
9
+ from haystack import Document, component, default_from_dict, default_to_dict, logging
10
+
11
+ from haystack_integrations.components.preprocessors.emeans._backend import cpu_assigner
12
+ from haystack_integrations.components.preprocessors.emeans._model import ModelCache, load_model
13
+ from haystack_integrations.components.preprocessors.emeans._utils import (
14
+ check_positive_int,
15
+ extract_embeddings,
16
+ normalize_rows,
17
+ optional_int,
18
+ )
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _cluster_id_of(doc: Document) -> int | None:
24
+ """Return the document's usable integer `cluster_id`, or `None` when absent or not an integer."""
25
+ value = doc.meta.get("cluster_id")
26
+ if isinstance(value, bool):
27
+ return None
28
+ if isinstance(value, (int, np.integer)):
29
+ return int(value)
30
+ if isinstance(value, (float, np.floating)) and float(value).is_integer():
31
+ return int(value)
32
+ return None
33
+
34
+
35
+ @component
36
+ class EmeansClusterRanker:
37
+ """
38
+ Keeps the best-scored document of each cluster among retrieved documents.
39
+
40
+ The ranker never clusters: it reads the `meta["cluster_id"]` written at indexing time by
41
+ `EmeansDocumentClusterer`.
42
+
43
+ ### Usage example
44
+
45
+ ```python
46
+ from haystack_integrations.components.rankers.emeans import EmeansClusterRanker
47
+
48
+ ranker = EmeansClusterRanker(top_k=5)
49
+ diverse = ranker.run(documents=retrieved_documents)["documents"]
50
+ ```
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ top_k: int | None = 10,
56
+ model_path: str | None = None,
57
+ missing_cluster: Literal["keep", "drop"] = "keep",
58
+ ) -> None:
59
+ """
60
+ Create an EmeansClusterRanker.
61
+
62
+ :param top_k: Maximum documents returned. `None` returns one document per cluster present.
63
+ :param model_path: Optional model used to assign documents that have no `cluster_id` but have an embedding.
64
+ :param missing_cluster: What to do with documents that have no `cluster_id` and cannot be assigned:
65
+ `"keep"` treats each as its own cluster, `"drop"` removes them.
66
+ """
67
+ check_positive_int("top_k", top_k, allow_none=True)
68
+ if missing_cluster not in ("keep", "drop"):
69
+ msg = f"missing_cluster must be 'keep' or 'drop', got {missing_cluster!r}"
70
+ raise ValueError(msg)
71
+ self.top_k = optional_int(top_k)
72
+ self.model_path = model_path
73
+ self.missing_cluster = missing_cluster
74
+ self._models = ModelCache()
75
+
76
+ def to_dict(self) -> dict[str, Any]:
77
+ """
78
+ Serialize the component to a dictionary.
79
+
80
+ :returns: Dictionary with all init parameters.
81
+ """
82
+ return default_to_dict(self, top_k=self.top_k, model_path=self.model_path, missing_cluster=self.missing_cluster)
83
+
84
+ @classmethod
85
+ def from_dict(cls, data: dict[str, Any]) -> "EmeansClusterRanker":
86
+ """
87
+ Deserialize the component from a dictionary.
88
+
89
+ :param data: Dictionary produced by `to_dict`.
90
+ :returns: The deserialized component.
91
+ """
92
+ return default_from_dict(cls, data)
93
+
94
+ @component.output_types(documents=list[Document])
95
+ def run(self, documents: list[Document], top_k: int | None = None, model_path: str | None = None) -> dict[str, Any]:
96
+ """
97
+ Return the best-scored document of each cluster, best first.
98
+
99
+ :param documents: Retrieved documents with `meta["cluster_id"]`.
100
+ :param top_k: Maximum documents returned; replaces the init value.
101
+ :param model_path: Model used to assign documents without `cluster_id`; replaces the init value.
102
+ :returns: A dictionary with the kept input `documents`, unchanged.
103
+ """
104
+ check_positive_int("top_k", top_k, allow_none=True)
105
+ limit = optional_int(top_k) if top_k is not None else self.top_k
106
+ if not documents:
107
+ return {"documents": []}
108
+
109
+ # A NaN score compares false against everything, which would make the winner depend on input order, so
110
+ # non-finite scores rank like missing ones.
111
+ usable = [doc.score is not None and math.isfinite(doc.score) for doc in documents]
112
+
113
+ def key(i: int) -> tuple[bool, float, int]:
114
+ score = documents[i].score
115
+ return (not usable[i], -score if usable[i] and score is not None else 0.0, i)
116
+
117
+ n_unscored = usable.count(False)
118
+ if n_unscored:
119
+ logger.warning(
120
+ "{n} documents have no score (or a non-finite one); they rank after scored documents.",
121
+ n=n_unscored,
122
+ )
123
+
124
+ cluster_ids = [_cluster_id_of(doc) for doc in documents]
125
+ n_assigned = 0
126
+ path = model_path if model_path is not None else self.model_path
127
+ if path is not None:
128
+ todo = [i for i, c in enumerate(cluster_ids) if c is None and documents[i].embedding is not None]
129
+ if todo:
130
+ model = self._models.get(path, load_model)
131
+ subset = [documents[i] for i in todo]
132
+ positions, x = extract_embeddings(subset, expected_dim=model.d)
133
+ if model.spherical:
134
+ x = normalize_rows(x, [subset[p].id for p in positions])
135
+ _, labels = cpu_assigner(model.centroids, spherical=model.spherical).assign(x)
136
+ for p, label in zip(positions, labels, strict=True):
137
+ cluster_ids[todo[p]] = int(label)
138
+ n_assigned = len(positions)
139
+
140
+ groups: dict[tuple[str, int], int] = {}
141
+ n_missing = 0
142
+ for i in range(len(documents)):
143
+ cluster = cluster_ids[i]
144
+ if cluster is None:
145
+ n_missing += 1
146
+ if self.missing_cluster == "drop":
147
+ continue
148
+ group = ("m", i)
149
+ else:
150
+ group = ("c", cluster)
151
+ if group not in groups or key(i) < key(groups[group]):
152
+ groups[group] = i
153
+ if n_missing or n_assigned:
154
+ kept = n_missing if self.missing_cluster == "keep" else 0
155
+ logger.warning(
156
+ "{n} documents have no usable cluster_id (assigned {assigned}, kept {kept}, dropped {dropped}).",
157
+ n=n_missing + n_assigned,
158
+ assigned=n_assigned,
159
+ kept=kept,
160
+ dropped=n_missing - kept,
161
+ )
162
+
163
+ ordered = sorted(groups.values(), key=key)
164
+ if limit is not None:
165
+ ordered = ordered[:limit]
166
+ return {"documents": [documents[i] for i in ordered]}
File without changes