返回 last30days-skill
cluster.py
根目录 / skills / last30days / scripts / lib / cluster.py
1 """Candidate clustering and representative selection."""
2
3 from __future__ import annotations
4
5 from . import cjk, dedupe, entity_extract, rust_accel, schema
6
7
8 def _cluster_score(group: list[schema.Candidate]) -> float:
9 """Highest score among in-window members, falling back to all members when all are stale."""
10 if not group:
11 return 0.0
12 in_window = [c for c in group if not schema.candidate_out_of_window(c)]
13 return max(c.final_score for c in (in_window or group))
14
15
16 def _cluster_out_of_window(
17 cluster: schema.Cluster,
18 candidate_by_id: dict[str, schema.Candidate],
19 ) -> bool:
20 """True when every known member of the cluster is out of the requested window."""
21 members = [
22 candidate_by_id[cid]
23 for cid in cluster.candidate_ids
24 if cid in candidate_by_id
25 ]
26 return bool(members) and all(schema.candidate_out_of_window(c) for c in members)
27
28
29 def _cluster_sort_key(candidate: schema.Candidate) -> tuple:
30 """Sort key that partitions stale candidates below fresh ones.
31
32 Stale items (all dated source_items outside the window) must never lead
33 cluster representatives or render as the cluster title.
34 """
35 return (
36 1 if schema.candidate_out_of_window(candidate) else 0,
37 -candidate.final_score,
38 )
39
40 CLUSTERABLE_INTENTS = {"breaking_news", "opinion", "comparison", "prediction"}
41
42 def _candidate_text(candidate: schema.Candidate) -> str:
43 return " ".join(part for part in [candidate.title, candidate.snippet] if part).strip()
44
45 def _mmr_representatives(
46 candidates: list[schema.Candidate],
47 text_cache: dict[str, dedupe._PreparedText],
48 limit: int = 3,
49 diversity_lambda: float = 0.75,
50 ) -> list[str]:
51 selected: list[schema.Candidate] = []
52 remaining_set = {c.candidate_id for c in candidates}
53 remaining = list(candidates)
54 while remaining and len(selected) < limit:
55 if not selected:
56 best = min(remaining, key=_cluster_sort_key)
57 selected.append(best)
58 remaining_set.discard(best.candidate_id)
59 remaining = [c for c in remaining if c.candidate_id in remaining_set]
60 continue
61
62 selected_preps = [text_cache[c.candidate_id] for c in selected]
63
64 def score(candidate: schema.Candidate) -> tuple:
65 prep = text_cache[candidate.candidate_id]
66 diversity_penalty = max(
67 dedupe.prepared_similarity(prep, sp) for sp in selected_preps
68 )
69 base_score = (diversity_lambda * candidate.final_score) - ((1 - diversity_lambda) * diversity_penalty * 100)
70 return (
71 0 if schema.candidate_out_of_window(candidate) else 1,
72 base_score,
73 )
74
75 best = max(remaining, key=score)
76 selected.append(best)
77 remaining_set.discard(best.candidate_id)
78 remaining = [c for c in remaining if c.candidate_id in remaining_set]
79 return [candidate.candidate_id for candidate in selected]
80
81
82 def cluster_candidates(
83 candidates: list[schema.Candidate],
84 plan: schema.QueryPlan,
85 ) -> list[schema.Cluster]:
86 """Greedy clustering around high-ranked leaders."""
87 if plan.intent not in CLUSTERABLE_INTENTS or plan.cluster_mode == "none":
88 clusters = []
89 for index, candidate in enumerate(candidates, start=1):
90 cluster_id = f"cluster-{index}"
91 candidate.cluster_id = cluster_id
92 clusters.append(
93 schema.Cluster(
94 cluster_id=cluster_id,
95 title=candidate.title,
96 candidate_ids=[candidate.candidate_id],
97 representative_ids=[candidate.candidate_id],
98 sources=sorted(schema.candidate_sources(candidate)),
99 score=candidate.final_score,
100 uncertainty=None,
101 )
102 )
103 return clusters
104
105 mode = rust_accel.engine_mode()
106 if (mode == "rust" and candidates) or (mode == "auto" and len(candidates) >= 8):
107 jieba_active = cjk._jieba is not None
108 has_jieba_cjk = jieba_active and (
109 cjk.has_cjk(plan.raw_topic)
110 or any(cjk.has_cjk(_candidate_text(c)) for c in candidates)
111 )
112 if not has_jieba_cjk:
113 payload_candidates = [
114 {
115 "candidate_id": c.candidate_id,
116 "title": c.title,
117 "snippet": c.snippet,
118 "sources": sorted(schema.candidate_sources(c)),
119 "final_score": float(c.final_score),
120 "window_state": (
121 "out_of_window" if schema.candidate_out_of_window(c) else "in_window"
122 ),
123 }
124 for c in candidates
125 ]
126 payload_plan = {
127 "intent": plan.intent,
128 "cluster_mode": plan.cluster_mode,
129 "raw_topic": plan.raw_topic,
130 }
131 rust_clusters = rust_accel.cluster_candidates(payload_candidates, payload_plan)
132 if rust_clusters is not None:
133 candidate_by_id = {c.candidate_id: c for c in candidates}
134 result_clusters: list[schema.Cluster] = []
135 for rc in rust_clusters:
136 cluster_id = rc["cluster_id"]
137 for cid in rc["candidate_ids"]:
138 cand = candidate_by_id.get(cid)
139 if cand is not None:
140 cand.cluster_id = cluster_id
141 result_clusters.append(
142 schema.Cluster(
143 cluster_id=cluster_id,
144 title=rc["title"],
145 candidate_ids=list(rc["candidate_ids"]),
146 representative_ids=list(rc["representative_ids"]),
147 sources=list(rc["sources"]),
148 score=float(rc["score"]),
149 uncertainty=rc.get("uncertainty"),
150 )
151 )
152 return result_clusters
153
154 text_cache: dict[str, dedupe._PreparedText] = {
155 c.candidate_id: dedupe._PreparedText(_candidate_text(c))
156 for c in candidates
157 }
158
159 groups: list[list[schema.Candidate]] = []
160 # Lower threshold for breaking_news: related articles share fewer exact
161 # words but cover the same event.
162 threshold = 0.42 if plan.intent == "breaking_news" else 0.48
163 for candidate in candidates:
164 assigned = False
165 cand_prep = text_cache[candidate.candidate_id]
166 for group in groups:
167 leader = group[0]
168 similarity = dedupe.prepared_similarity(cand_prep, text_cache[leader.candidate_id])
169 if similarity >= threshold:
170 group.append(candidate)
171 assigned = True
172 break
173 if not assigned:
174 groups.append([candidate])
175
176 clusters: list[schema.Cluster] = []
177 for index, group in enumerate(groups, start=1):
178 group.sort(key=_cluster_sort_key)
179 cluster_id = f"cluster-{index}"
180 representatives = _mmr_representatives(group, text_cache)
181 for candidate in group:
182 candidate.cluster_id = cluster_id
183 clusters.append(
184 schema.Cluster(
185 cluster_id=cluster_id,
186 title=group[0].title,
187 candidate_ids=[candidate.candidate_id for candidate in group],
188 representative_ids=representatives,
189 sources=sorted({source for candidate in group for source in schema.candidate_sources(candidate)}),
190 score=_cluster_score(group),
191 uncertainty=_cluster_uncertainty(group),
192 )
193 )
194
195 # Second pass: merge small clusters that share entities across sources.
196 clusters = _merge_entity_clusters(
197 clusters,
198 candidates,
199 min_shared_entities=2,
200 topic_entities=entity_extract.extract_text_entities(plan.raw_topic),
201 )
202
203 candidate_by_id = {c.candidate_id: c for c in candidates}
204 return sorted(
205 clusters,
206 key=lambda cluster: (
207 1 if _cluster_out_of_window(cluster, candidate_by_id) else 0,
208 -cluster.score,
209 ),
210 )
211
212
213 def _merge_entity_clusters(
214 clusters: list[schema.Cluster],
215 all_candidates: list[schema.Candidate],
216 *,
217 min_shared_entities: int = 2,
218 topic_entities: set[str] | frozenset[str] = frozenset(),
219 max_cluster_size: int = 3,
220 ) -> list[schema.Cluster]:
221 """Merge small clusters that cover the same story across different sources.
222
223 The initial greedy pass uses text similarity which misses cross-source
224 matches where phrasing differs. This second pass looks at entity overlap
225 (proper nouns, names, numbers) to catch cases like:
226 - Reddit: "Kanye West to headline all three nights of Wireless Festival 2026"
227 - X: "BREAKING: Kanye West (Ye) is making his massive UK comeback!"
228 """
229 if len(clusters) < 2:
230 return clusters
231
232 candidate_map = {c.candidate_id: c for c in all_candidates}
233
234 # Build entity sets per cluster
235 cluster_entities: list[set[str]] = []
236 for cl in clusters:
237 entities: set[str] = set()
238 for cid in cl.candidate_ids:
239 cand = candidate_map.get(cid)
240 if cand:
241 entities |= entity_extract.extract_text_entities(_candidate_text(cand))
242 cluster_entities.append(entities)
243
244 # Track running merged cluster sizes so a small cluster cannot absorb
245 # unbounded unrelated stories past max_cluster_size.
246 merged_into: dict[int, int] = {} # index -> merge target index
247 cluster_sizes = [len(cl.candidate_ids) for cl in clusters]
248 for i in range(len(clusters)):
249 if i in merged_into or cluster_sizes[i] >= max_cluster_size:
250 continue
251 sources_i = set(clusters[i].sources)
252 for j in range(i + 1, len(clusters)):
253 if j in merged_into or cluster_sizes[i] + cluster_sizes[j] > max_cluster_size:
254 continue
255 # Require different sources to merge (same-source should already be grouped)
256 sources_j = set(clusters[j].sources)
257 if sources_i == sources_j and len(sources_i) == 1:
258 continue
259 # Prevent Polymarket clusters from merging with non-Polymarket
260 # clusters. Prediction markets about "Sam Altman equity" should not
261 # merge into a news cluster about "Sam Altman rivalry" just because
262 # both mention the same entity.
263 poly_i = "polymarket" in sources_i
264 poly_j = "polymarket" in sources_j
265 if poly_i != poly_j:
266 continue
267
268 shared_entities = cluster_entities[i] & cluster_entities[j]
269 if len(shared_entities) < min_shared_entities:
270 continue
271 if topic_entities:
272 non_topic_i = cluster_entities[i] - topic_entities
273 non_topic_j = cluster_entities[j] - topic_entities
274 if (non_topic_i or non_topic_j) and not (shared_entities - topic_entities):
275 continue
276 overlap = entity_extract.entity_overlap(cluster_entities[i], cluster_entities[j])
277 if overlap >= 0.45:
278 merged_into[j] = i
279 cluster_sizes[i] += cluster_sizes[j]
280 sources_i |= sources_j
281 if cluster_sizes[i] >= max_cluster_size:
282 break
283
284 if not merged_into:
285 return clusters
286
287 # Build merged cluster list
288 result: list[schema.Cluster] = []
289 for i, cl in enumerate(clusters):
290 if i in merged_into:
291 continue
292 # Collect all clusters merged into this one
293 merge_sources = [i] + [j for j, target in merged_into.items() if target == i]
294 if len(merge_sources) == 1:
295 result.append(cl)
296 continue
297
298 # Combine candidates from all merged clusters
299 combined_cids: list[str] = []
300 combined_sources: set[str] = set()
301 best_score = 0.0
302 for idx in merge_sources:
303 combined_cids.extend(clusters[idx].candidate_ids)
304 combined_sources.update(clusters[idx].sources)
305 best_score = max(best_score, clusters[idx].score)
306
307 # Pick representatives from combined pool
308 combined_candidates = [candidate_map[cid] for cid in combined_cids if cid in candidate_map]
309 combined_candidates.sort(key=_cluster_sort_key)
310 ordered_cids = [c.candidate_id for c in combined_candidates]
311 known_cids = set(ordered_cids)
312 ordered_cids.extend(cid for cid in combined_cids if cid not in known_cids)
313 merge_text_cache = {
314 c.candidate_id: dedupe._PreparedText(_candidate_text(c))
315 for c in combined_candidates
316 }
317 reps = _mmr_representatives(combined_candidates, merge_text_cache)
318
319 cluster_id = cl.cluster_id
320 for cid in combined_cids:
321 cand = candidate_map.get(cid)
322 if cand:
323 cand.cluster_id = cluster_id
324
325 result.append(schema.Cluster(
326 cluster_id=cluster_id,
327 title=combined_candidates[0].title if combined_candidates else cl.title,
328 candidate_ids=ordered_cids,
329 representative_ids=reps,
330 sources=sorted(combined_sources),
331 score=_cluster_score(combined_candidates) if combined_candidates else best_score,
332 uncertainty=_cluster_uncertainty(combined_candidates),
333 ))
334
335 return result
336
337
338 def _cluster_uncertainty(group: list[schema.Candidate]) -> str | None:
339 if not group:
340 return "thin-evidence"
341 sources = {source for candidate in group for source in schema.candidate_sources(candidate)}
342 if len(sources) == 1:
343 return "single-source"
344 if _cluster_score(group) < 55:
345 return "thin-evidence"
346 return None
347
347 lines PYTHON