cluster.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. from __future__ import annotations
  2. import asyncio
  3. import hashlib
  4. import re
  5. from datetime import datetime, timezone, timedelta
  6. from difflib import SequenceMatcher
  7. from typing import Any, Dict, List
  8. from urllib.parse import urlparse
  9. from news_mcp.config import (
  10. NEWS_EMBEDDINGS_ENABLED,
  11. NEWS_EMBEDDING_SIMILARITY_THRESHOLD,
  12. NEWS_CLUSTER_MAX_AGE_HOURS,
  13. )
  14. from news_mcp.dedup.embedding_support import cosine_similarity, ollama_embed
  15. from news_mcp.sources.news_feeds import normalize_topic_from_title
  16. # ---------------------------------------------------------------------------
  17. # Text helpers
  18. # ---------------------------------------------------------------------------
  19. def _normalize_title(title: str) -> str:
  20. t = title.lower().strip()
  21. t = re.sub(r"[^a-z0-9\s]", " ", t)
  22. t = re.sub(r"\s+", " ", t).strip()
  23. return t
  24. def _title_similarity(a: str, b: str) -> float:
  25. return SequenceMatcher(None, _normalize_title(a), _normalize_title(b)).ratio()
  26. def _article_key(article: Dict[str, Any]) -> str:
  27. url = str(article.get("url") or "").strip()
  28. if not url:
  29. return str(article.get("title") or "")
  30. try:
  31. parsed = urlparse(url)
  32. parts = [p for p in parsed.path.split("/") if p]
  33. if parts:
  34. return parts[-1]
  35. except Exception:
  36. pass
  37. return url
  38. def _cluster_text(a: Dict[str, Any]) -> str:
  39. parts = [a.get("title", ""), a.get("summary", "") or ""]
  40. return "\n".join(p for p in parts if p).strip()
  41. # ---------------------------------------------------------------------------
  42. # Token / Jaccard signal
  43. # ---------------------------------------------------------------------------
  44. _STOPWORDS = frozenset(
  45. {
  46. "a", "an", "the", "of", "to", "in", "on", "at", "for", "by", "with",
  47. "and", "or", "but", "if", "is", "are", "was", "were", "be", "been",
  48. "being", "as", "from", "that", "this", "these", "those", "it", "its",
  49. "into", "over", "under", "than", "then", "so", "such", "no", "not",
  50. "do", "does", "did", "will", "would", "can", "could", "should", "may",
  51. "might", "has", "have", "had", "after", "before", "amid", "vs", "via",
  52. "us", "uk",
  53. }
  54. )
  55. def _tokens(text: str) -> set[str]:
  56. tokens = re.findall(r"[a-z0-9][a-z0-9\-]+", text.lower())
  57. return {t for t in tokens if len(t) >= 3 and t not in _STOPWORDS}
  58. def _jaccard(a: set, b: set) -> float:
  59. if not a or not b:
  60. return 0.0
  61. inter = len(a & b)
  62. if inter == 0:
  63. return 0.0
  64. return inter / len(a | b)
  65. # ---------------------------------------------------------------------------
  66. # Composite similarity
  67. # ---------------------------------------------------------------------------
  68. DEFAULT_TITLE_THRESHOLD = 0.75
  69. DEFAULT_JACCARD_THRESHOLD = 0.55
  70. def _signals(article: Dict[str, Any], cluster: Dict[str, Any]) -> dict:
  71. """Per-pair similarity signals (title, jaccard, embedding cosine).
  72. Compares the article against ALL articles in the cluster and returns the
  73. best (max) signal across all comparisons. The cosine signal uses the
  74. cluster-level embedding; title and jaccard are computed per-article and
  75. the maximum is returned so that a match against any cluster member counts.
  76. """
  77. a_title = str(article.get("title") or "")
  78. c_title = str(cluster.get("headline") or "")
  79. a_emb = article.get("_embedding")
  80. c_emb = cluster.get("embedding")
  81. cosine = cosine_similarity(a_emb, c_emb) if a_emb and c_emb else 0.0
  82. best_title = 0.0
  83. best_jaccard = 0.0
  84. a_text = _cluster_text(article)
  85. a_toks = _tokens(a_text) if a_text else set()
  86. # Compare against every article in the cluster, take the best scores.
  87. cluster_articles = cluster.get("articles") or ([{"title": c_title}] if c_title else [])
  88. for ca in cluster_articles:
  89. if not isinstance(ca, dict):
  90. continue
  91. # title signal
  92. ca_title = str(ca.get("title") or "")
  93. if a_title and ca_title:
  94. t = _title_similarity(a_title, ca_title)
  95. if t > best_title:
  96. best_title = t
  97. # jaccard signal
  98. ca_text = _cluster_text(ca)
  99. if a_text and ca_text:
  100. j = _jaccard(a_toks, _tokens(ca_text))
  101. if j > best_jaccard:
  102. best_jaccard = j
  103. # early exit: if both title and jaccard are already very high
  104. if best_title >= 0.95 and best_jaccard >= 0.80:
  105. break
  106. return {"title": best_title, "jaccard": best_jaccard, "cosine": cosine}
  107. def _is_match(
  108. signals: dict,
  109. *,
  110. embeddings_enabled: bool,
  111. title_threshold: float = DEFAULT_TITLE_THRESHOLD,
  112. jaccard_threshold: float = DEFAULT_JACCARD_THRESHOLD,
  113. ) -> tuple[bool, str, float]:
  114. """Decide whether two items should merge based on the strongest signal.
  115. Cascade: cosine (if enabled) → title → jaccard → consensus → dual.
  116. Returns (matched, signal_name, signal_value).
  117. """
  118. cosine_threshold = NEWS_EMBEDDING_SIMILARITY_THRESHOLD
  119. if embeddings_enabled and signals["cosine"] >= cosine_threshold:
  120. return True, "cosine", signals["cosine"]
  121. if signals["title"] >= title_threshold:
  122. return True, "title", signals["title"]
  123. if signals["jaccard"] >= jaccard_threshold:
  124. return True, "jaccard", signals["jaccard"]
  125. if (
  126. embeddings_enabled
  127. and signals["cosine"] >= 0.80
  128. and (signals["jaccard"] >= 0.30 or signals["title"] >= 0.55)
  129. ):
  130. val = (signals["cosine"] + max(signals["jaccard"], signals["title"])) / 2.0
  131. return True, "consensus", val
  132. # Dual-signal: medium title + medium jaccard → credible match even without
  133. # embeddings. Catches cross-source variants where headlines differ
  134. # editorially (title ~0.55-0.74) but share substantial token overlap
  135. # (jaccard ~0.25-0.54).
  136. if signals["title"] >= 0.55 and signals["jaccard"] >= 0.25:
  137. val = (signals["title"] + signals["jaccard"]) / 2.0
  138. return True, "dual", val
  139. return False, "none", 0.0
  140. # ---------------------------------------------------------------------------
  141. # Stable cluster ID
  142. # ---------------------------------------------------------------------------
  143. def _stable_cluster_id(topic: str, articles: List[Dict[str, Any]]) -> str:
  144. """Deterministic cluster ID derived from the sorted set of article keys.
  145. The topic is intentionally excluded from the hash: the same article may be
  146. classified under different topics across cycles (heuristic vs LLM-enriched),
  147. but it must always map to the same cluster_id so that ON CONFLICT DO UPDATE
  148. in upsert_clusters correctly merges them instead of creating duplicates."""
  149. keys = sorted(_article_key(a) for a in articles if _article_key(a))
  150. if not keys:
  151. # Degenerate fallback — single article with empty url and title
  152. return hashlib.sha1(topic.encode("utf-8")).hexdigest()
  153. seed = keys[0]
  154. return hashlib.sha1(seed.encode("utf-8")).hexdigest()
  155. # ---------------------------------------------------------------------------
  156. # Temporal gating
  157. # ---------------------------------------------------------------------------
  158. def _parse_ts(ts_str: str) -> datetime | None:
  159. if not ts_str:
  160. return None
  161. try:
  162. s = str(ts_str).replace("Z", "+00:00")
  163. dt = datetime.fromisoformat(s)
  164. if dt.tzinfo is None:
  165. dt = dt.replace(tzinfo=timezone.utc)
  166. return dt.astimezone(timezone.utc)
  167. except Exception:
  168. pass
  169. try:
  170. from email.utils import parsedate_to_datetime
  171. dt = parsedate_to_datetime(str(ts_str))
  172. if dt.tzinfo is None:
  173. dt = dt.replace(tzinfo=timezone.utc)
  174. return dt.astimezone(timezone.utc)
  175. except Exception:
  176. return None
  177. def _cluster_is_within_age_window(cluster: Dict[str, Any], *, max_age_hours: float) -> bool:
  178. """Return True if the cluster's last_updated is within the merge window."""
  179. if max_age_hours <= 0:
  180. return True # 0 = no limit
  181. ts_str = cluster.get("last_updated") or cluster.get("timestamp") or ""
  182. dt = _parse_ts(ts_str)
  183. if dt is None:
  184. return True # be lenient with unparseable timestamps
  185. cutoff = datetime.now(timezone.utc) - timedelta(hours=max_age_hours)
  186. return dt >= cutoff
  187. # ---------------------------------------------------------------------------
  188. # Embedding pre-computation (async internally)
  189. # ---------------------------------------------------------------------------
  190. async def _compute_embeddings_concurrently(
  191. articles: List[Dict[str, Any]],
  192. ) -> Dict[str, list[float] | None]:
  193. """Compute embeddings for unique article texts concurrently.
  194. Returns a cache dict: text -> embedding vector or None.
  195. """
  196. unique_texts: list[str] = []
  197. seen: set[str] = set()
  198. for a in articles:
  199. text = _cluster_text(a)
  200. if text and text not in seen:
  201. seen.add(text)
  202. unique_texts.append(text)
  203. emb_tasks = [ollama_embed(text) for text in unique_texts]
  204. emb_results = await asyncio.gather(*emb_tasks, return_exceptions=True)
  205. cache: Dict[str, list[float] | None] = {}
  206. for text, result in zip(unique_texts, emb_results):
  207. if isinstance(result, list):
  208. cache[text] = result
  209. else:
  210. cache[text] = None
  211. return cache
  212. def _compute_embeddings_sync(
  213. articles: List[Dict[str, Any]],
  214. ) -> Dict[str, list[float] | None]:
  215. """Synchronous wrapper that runs the async embedding computation.
  216. Handles three cases:
  217. 1. Already inside an async event loop (called from poller) -> schedule
  218. as a task and run it to completion on the running loop.
  219. 2. No event loop at all (plain sync caller) -> use asyncio.run().
  220. """
  221. try:
  222. loop = asyncio.get_running_loop()
  223. except RuntimeError:
  224. # No running loop — safe to use asyncio.run()
  225. return asyncio.run(_compute_embeddings_concurrently(articles))
  226. # We're inside a running event loop (e.g. the poller). Create a new loop
  227. # in a thread to avoid blocking.
  228. import concurrent.futures
  229. with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
  230. future = pool.submit(
  231. asyncio.run, _compute_embeddings_concurrently(articles)
  232. )
  233. return future.result()
  234. # ---------------------------------------------------------------------------
  235. # Orphan merge: detect clusters sharing articles and merge them
  236. # ---------------------------------------------------------------------------
  237. def _merge_orphan_clusters(
  238. clusters: List[Dict[str, Any]],
  239. ) -> List[Dict[str, Any]]:
  240. """Post-clustering pass: merge clusters that share article keys.
  241. This handles the case where two articles about the same event didn't match
  242. during the main loop (e.g. embeddings were temporarily unavailable) and
  243. ended up in separate clusters. If two clusters share >= 1 article key, we
  244. merge them into one (keeping the earlier first_seen, recompute the stable
  245. ID from the union of articles).
  246. """
  247. if len(clusters) <= 1:
  248. return clusters
  249. # Build index: article_key -> list of cluster indices
  250. key_to_indices: dict[str, list[int]] = {}
  251. for idx, c in enumerate(clusters):
  252. for a in c.get("articles", []) or []:
  253. ak = _article_key(a)
  254. if ak:
  255. key_to_indices.setdefault(ak, []).append(idx)
  256. # Find connected components via Union-Find
  257. parent = list(range(len(clusters)))
  258. def find(x: int) -> int:
  259. while parent[x] != x:
  260. parent[x] = parent[parent[x]]
  261. x = parent[x]
  262. return x
  263. def union(a: int, b: int) -> None:
  264. ra, rb = find(a), find(b)
  265. if ra != rb:
  266. parent[ra] = rb
  267. for indices in key_to_indices.values():
  268. for i in range(1, len(indices)):
  269. union(indices[0], indices[i])
  270. # Group clusters by component
  271. components: dict[int, list[int]] = {}
  272. for idx in range(len(clusters)):
  273. root = find(idx)
  274. components.setdefault(root, []).append(idx)
  275. merged: List[Dict[str, Any]] = []
  276. for root, members in components.items():
  277. if len(members) == 1:
  278. merged.append(clusters[members[0]])
  279. continue
  280. # Merge all clusters in this component
  281. base = dict(clusters[members[0]])
  282. all_articles: list[dict] = list(base.get("articles", []) or [])
  283. all_sources: list[str] = list(base.get("sources", []) or [])
  284. first_seen = base.get("first_seen", "")
  285. last_updated = base.get("last_updated", "")
  286. for m_idx in members[1:]:
  287. other = clusters[m_idx]
  288. existing_keys = {_article_key(a) for a in all_articles}
  289. for a in other.get("articles", []) or []:
  290. ak = _article_key(a)
  291. if ak not in existing_keys:
  292. all_articles.append(a)
  293. existing_keys.add(ak)
  294. for s in other.get("sources", []) or []:
  295. if s not in all_sources:
  296. all_sources.append(s)
  297. fs = other.get("first_seen", "")
  298. if fs and (not first_seen or fs < first_seen):
  299. first_seen = fs
  300. lu = other.get("last_updated", "")
  301. if lu and (not last_updated or lu > last_updated):
  302. last_updated = lu
  303. base["articles"] = all_articles
  304. base["sources"] = all_sources
  305. base["first_seen"] = first_seen
  306. base["last_updated"] = last_updated
  307. # Keep the base cluster's original ID so the enrichment cache
  308. # (keyed by cluster_id) survives the merge.
  309. base.setdefault("cluster_id", _stable_cluster_id(base.get("topic", "other"), all_articles))
  310. merged.append(base)
  311. return merged
  312. # ---------------------------------------------------------------------------
  313. # Public API (sync — backward compatible with tests)
  314. # ---------------------------------------------------------------------------
  315. def dedup_and_cluster_articles(
  316. articles: List[Dict[str, Any]],
  317. similarity_threshold: float | None = None,
  318. *,
  319. existing_clusters: List[Dict[str, Any]] | None = None,
  320. max_age_hours: float = 0,
  321. ) -> Dict[str, List[Dict[str, Any]]]:
  322. """Deduplicate raw articles into clusters keyed by topic.
  323. v1.3: stable cluster IDs, temporal gating, and orphan merge.
  324. Args:
  325. articles: new articles to cluster.
  326. similarity_threshold: override for the title-similarity threshold.
  327. existing_clusters: optional list of recent clusters from the DB to
  328. merge against (cross-cycle merge). When provided, temporal
  329. gating via max_age_hours is applied to filter these.
  330. max_age_hours: only compare against existing_clusters updated within
  331. this many hours. 0 = no limit (compare against all provided).
  332. """
  333. title_threshold = similarity_threshold if similarity_threshold is not None else DEFAULT_TITLE_THRESHOLD
  334. # Pre-compute embeddings concurrently (sync boundary handles async internally)
  335. embedding_cache: Dict[str, list[float] | None] = {}
  336. if NEWS_EMBEDDINGS_ENABLED:
  337. embedding_cache = _compute_embeddings_sync(articles)
  338. by_topic: Dict[str, List[Dict[str, Any]]] = {}
  339. # Seed with existing clusters (filtered by age window).
  340. # Re-derive the topic via the same heuristic (normalize_topic_from_title)
  341. # that new articles use, so that existing and new clusters with the same
  342. # headline land in the same by_topic bucket regardless of what LLM
  343. # enrichment previously stored on the cluster.
  344. if existing_clusters:
  345. for c in existing_clusters:
  346. if not _cluster_is_within_age_window(c, max_age_hours=max_age_hours):
  347. continue
  348. seed_title = c.get("headline") or ""
  349. topic = normalize_topic_from_title(seed_title) if seed_title else (c.get("topic", "other") or "other")
  350. by_topic.setdefault(topic, []).append(dict(c))
  351. for a in articles:
  352. title = a.get("title") or ""
  353. if not title:
  354. continue
  355. topic = normalize_topic_from_title(title)
  356. article_text = _cluster_text(a)
  357. article_embedding = embedding_cache.get(article_text) if NEWS_EMBEDDINGS_ENABLED else None
  358. a_with_emb = dict(a)
  359. if article_embedding is not None:
  360. a_with_emb["_embedding"] = article_embedding
  361. by_topic.setdefault(topic, [])
  362. clusters = by_topic[topic]
  363. best_idx: int | None = None
  364. best_signal_name = "none"
  365. best_signal_value = 0.0
  366. for idx, c in enumerate(clusters):
  367. sigs = _signals(a_with_emb, c)
  368. matched, signal_name, signal_value = _is_match(
  369. sigs,
  370. embeddings_enabled=NEWS_EMBEDDINGS_ENABLED,
  371. title_threshold=title_threshold,
  372. )
  373. if matched and signal_value > best_signal_value:
  374. best_idx = idx
  375. best_signal_name = signal_name
  376. best_signal_value = signal_value
  377. if best_idx is not None:
  378. c = clusters[best_idx]
  379. existing_keys = {_article_key(x) for x in c.get("articles", []) or []}
  380. if _article_key(a) not in existing_keys:
  381. c["articles"].append(a)
  382. if a.get("source") and a["source"] not in c["sources"]:
  383. c["sources"].append(a["source"])
  384. c["last_updated"] = max(str(c.get("last_updated", "")), str(a.get("timestamp", "")))
  385. # Update cluster embedding to the new article's embedding so later
  386. # comparisons can match against the most recently added content.
  387. if NEWS_EMBEDDINGS_ENABLED and article_embedding is not None:
  388. c["embedding"] = article_embedding
  389. c["embedding_model"] = "ollama:nomic-embed-text"
  390. c.setdefault("_merge_signals", []).append(
  391. {"signal": best_signal_name, "value": round(best_signal_value, 3)}
  392. )
  393. else:
  394. cid = _stable_cluster_id(topic, [a])
  395. cluster_embedding = article_embedding if NEWS_EMBEDDINGS_ENABLED else None
  396. clusters.append(
  397. {
  398. "cluster_id": cid,
  399. "headline": title,
  400. "summary": a.get("summary", ""),
  401. "topic": topic,
  402. "entities": [],
  403. "sentiment": "neutral",
  404. "importance": 0.0,
  405. "sources": [a["source"]] if a.get("source") else [],
  406. "timestamp": a.get("timestamp"),
  407. "articles": [a],
  408. "first_seen": a.get("timestamp"),
  409. "last_updated": a.get("timestamp"),
  410. "embedding": cluster_embedding,
  411. "embedding_model": "ollama:nomic-embed-text" if cluster_embedding else None,
  412. }
  413. )
  414. # Post-clustering passes per topic
  415. for topic, clusters in by_topic.items():
  416. # Merge orphans (clusters that share articles)
  417. clusters = _merge_orphan_clusters(clusters)
  418. # Assign stable IDs only to clusters that don't already have one.
  419. # Pre-seeded clusters from the DB carry their original cluster_id —
  420. # keeping it stable across cycles so the enrichment cache (keyed by
  421. # cluster_id) continues to work even after new articles are merged in.
  422. for c in clusters:
  423. if not c.get("cluster_id"):
  424. c["cluster_id"] = _stable_cluster_id(topic, c.get("articles", []) or [])
  425. by_topic[topic] = clusters
  426. # Cross-topic dedup: merge clusters with overlapping headlines and entities
  427. by_topic = _merge_duplicate_clusters(by_topic)
  428. # Strip the internal merge audit trail before returning
  429. for clusters in by_topic.values():
  430. for c in clusters:
  431. c.pop("_merge_signals", None)
  432. return {topic: clusters for topic, clusters in by_topic.items()}
  433. def _merge_duplicate_clusters(
  434. by_topic: Dict[str, List[Dict[str, Any]]],
  435. ) -> Dict[str, List[Dict[str, Any]]]:
  436. """Cross-topic dedup: merge clusters whose headlines and entities overlap.
  437. Catches the case where the same event arrives from different feeds with
  438. different article keys, lands in separate clusters with different stable
  439. IDs, but has nearly identical headlines and shared entities.
  440. Merge criteria: title_similarity >= 0.90 AND at least one shared entity.
  441. This is intentionally conservative to avoid merging distinct events.
  442. """
  443. # Flatten all clusters with their topic
  444. all_clusters: list[tuple[str, dict]] = []
  445. for topic, clusters in by_topic.items():
  446. for c in clusters:
  447. all_clusters.append((topic, c))
  448. n = len(all_clusters)
  449. if n <= 1:
  450. return by_topic
  451. # Union-Find
  452. parent = list(range(n))
  453. def find(x: int) -> int:
  454. while parent[x] != x:
  455. parent[x] = parent[parent[x]]
  456. x = parent[x]
  457. return x
  458. def union(a: int, b: int) -> None:
  459. ra, rb = find(a), find(b)
  460. if ra != rb:
  461. parent[ra] = rb
  462. # Pre-extract normalized entity sets for each cluster
  463. cluster_ent_sets: list[set[str]] = []
  464. cluster_heads: list[str] = []
  465. for _, c in all_clusters:
  466. ents = {str(e).strip().lower() for e in (c.get("entities", []) or []) if str(e).strip()}
  467. cluster_ent_sets.append(ents)
  468. cluster_heads.append(str(c.get("headline", "") or ""))
  469. # Compare pairs — O(n^2) but n is small (clusters per cycle, not articles)
  470. TITLE_THRESHOLD = 0.90
  471. for i in range(n):
  472. for j in range(i + 1, n):
  473. # Quick skip: if headlines are completely different, no need for entity check
  474. if _title_similarity(cluster_heads[i], cluster_heads[j]) < TITLE_THRESHOLD:
  475. continue
  476. # Check entity overlap (at least one shared entity)
  477. if not (cluster_ent_sets[i] & cluster_ent_sets[j]):
  478. continue
  479. union(i, j)
  480. # Group by component
  481. components: dict[int, list[int]] = {}
  482. for idx in range(n):
  483. root = find(idx)
  484. components.setdefault(root, []).append(idx)
  485. # Merge each component
  486. merged_by_topic: Dict[str, List[Dict[str, Any]]] = {}
  487. for root, members in components.items():
  488. # Pick the base cluster (the one with the most sources, then most articles)
  489. best_idx = max(members, key=lambda i: (
  490. len(all_clusters[i][1].get("sources", []) or []),
  491. len(all_clusters[i][1].get("articles", []) or []),
  492. ))
  493. base_topic, base = all_clusters[best_idx]
  494. if len(members) == 1:
  495. merged_by_topic.setdefault(base_topic, []).append(base)
  496. continue
  497. # Merge all clusters in this component into base
  498. all_articles: list[dict] = list(base.get("articles", []) or [])
  499. all_sources: list[str] = list(base.get("sources", []) or [])
  500. all_entities: list[str] = list(base.get("entities", []) or [])
  501. all_keywords: list[str] = list(base.get("keywords", []) or [])
  502. first_seen = base.get("first_seen", "")
  503. last_updated = base.get("last_updated", "")
  504. existing_article_keys = {_article_key(a) for a in all_articles}
  505. existing_ent_lower = {str(e).strip().lower() for e in all_entities}
  506. existing_kw_lower = {str(k).strip().lower() for k in all_keywords}
  507. for m_idx in members:
  508. if m_idx == best_idx:
  509. continue
  510. other = all_clusters[m_idx][1]
  511. # Merge articles (dedup by key)
  512. for a in other.get("articles", []) or []:
  513. ak = _article_key(a)
  514. if ak not in existing_article_keys:
  515. all_articles.append(a)
  516. existing_article_keys.add(ak)
  517. # Merge sources
  518. for s in other.get("sources", []) or []:
  519. if s not in all_sources:
  520. all_sources.append(s)
  521. # Merge entities (dedup case-insensitive)
  522. for e in other.get("entities", []) or []:
  523. el = str(e).strip().lower()
  524. if el not in existing_ent_lower:
  525. all_entities.append(e)
  526. existing_ent_lower.add(el)
  527. # Merge keywords (dedup case-insensitive)
  528. for k in other.get("keywords", []) or []:
  529. kl = str(k).strip().lower()
  530. if kl not in existing_kw_lower:
  531. all_keywords.append(k)
  532. existing_kw_lower.add(kl)
  533. # Timestamps
  534. fs = other.get("first_seen", "")
  535. if fs and (not first_seen or fs < first_seen):
  536. first_seen = fs
  537. lu = other.get("last_updated", "")
  538. if lu and (not last_updated or lu > last_updated):
  539. last_updated = lu
  540. base["articles"] = all_articles
  541. base["sources"] = all_sources
  542. base["entities"] = all_entities
  543. base["keywords"] = all_keywords
  544. base["first_seen"] = first_seen
  545. base["last_updated"] = last_updated
  546. # Keep the base cluster's original ID so the enrichment cache
  547. # (keyed by cluster_id) survives the merge.
  548. base.setdefault("cluster_id", _stable_cluster_id(base.get("topic", "other"), all_articles))
  549. merged_by_topic.setdefault(base_topic, []).append(base)
  550. return merged_by_topic