cluster.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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.87
  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 embeddings enabled) → title → jaccard → consensus.
  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. return False, "none", 0.0
  133. # ---------------------------------------------------------------------------
  134. # Stable cluster ID
  135. # ---------------------------------------------------------------------------
  136. def _stable_cluster_id(topic: str, articles: List[Dict[str, Any]]) -> str:
  137. """Deterministic cluster ID derived from the sorted set of article keys.
  138. The topic is intentionally excluded from the hash: the same article may be
  139. classified under different topics across cycles (heuristic vs LLM-enriched),
  140. but it must always map to the same cluster_id so that ON CONFLICT DO UPDATE
  141. in upsert_clusters correctly merges them instead of creating duplicates."""
  142. keys = sorted(_article_key(a) for a in articles if _article_key(a))
  143. if not keys:
  144. # Degenerate fallback — single article with empty url and title
  145. return hashlib.sha1(topic.encode("utf-8")).hexdigest()
  146. seed = keys[0]
  147. return hashlib.sha1(seed.encode("utf-8")).hexdigest()
  148. # ---------------------------------------------------------------------------
  149. # Temporal gating
  150. # ---------------------------------------------------------------------------
  151. def _parse_ts(ts_str: str) -> datetime | None:
  152. if not ts_str:
  153. return None
  154. try:
  155. s = str(ts_str).replace("Z", "+00:00")
  156. dt = datetime.fromisoformat(s)
  157. if dt.tzinfo is None:
  158. dt = dt.replace(tzinfo=timezone.utc)
  159. return dt.astimezone(timezone.utc)
  160. except Exception:
  161. pass
  162. try:
  163. from email.utils import parsedate_to_datetime
  164. dt = parsedate_to_datetime(str(ts_str))
  165. if dt.tzinfo is None:
  166. dt = dt.replace(tzinfo=timezone.utc)
  167. return dt.astimezone(timezone.utc)
  168. except Exception:
  169. return None
  170. def _cluster_is_within_age_window(cluster: Dict[str, Any], *, max_age_hours: float) -> bool:
  171. """Return True if the cluster's last_updated is within the merge window."""
  172. if max_age_hours <= 0:
  173. return True # 0 = no limit
  174. ts_str = cluster.get("last_updated") or cluster.get("timestamp") or ""
  175. dt = _parse_ts(ts_str)
  176. if dt is None:
  177. return True # be lenient with unparseable timestamps
  178. cutoff = datetime.now(timezone.utc) - timedelta(hours=max_age_hours)
  179. return dt >= cutoff
  180. # ---------------------------------------------------------------------------
  181. # Embedding pre-computation (async internally)
  182. # ---------------------------------------------------------------------------
  183. async def _compute_embeddings_concurrently(
  184. articles: List[Dict[str, Any]],
  185. ) -> Dict[str, list[float] | None]:
  186. """Compute embeddings for unique article texts concurrently.
  187. Returns a cache dict: text -> embedding vector or None.
  188. """
  189. unique_texts: list[str] = []
  190. seen: set[str] = set()
  191. for a in articles:
  192. text = _cluster_text(a)
  193. if text and text not in seen:
  194. seen.add(text)
  195. unique_texts.append(text)
  196. emb_tasks = [ollama_embed(text) for text in unique_texts]
  197. emb_results = await asyncio.gather(*emb_tasks, return_exceptions=True)
  198. cache: Dict[str, list[float] | None] = {}
  199. for text, result in zip(unique_texts, emb_results):
  200. if isinstance(result, list):
  201. cache[text] = result
  202. else:
  203. cache[text] = None
  204. return cache
  205. def _compute_embeddings_sync(
  206. articles: List[Dict[str, Any]],
  207. ) -> Dict[str, list[float] | None]:
  208. """Synchronous wrapper that runs the async embedding computation.
  209. Handles three cases:
  210. 1. Already inside an async event loop (called from poller) -> schedule
  211. as a task and run it to completion on the running loop.
  212. 2. No event loop at all (plain sync caller) -> use asyncio.run().
  213. """
  214. try:
  215. loop = asyncio.get_running_loop()
  216. except RuntimeError:
  217. # No running loop — safe to use asyncio.run()
  218. return asyncio.run(_compute_embeddings_concurrently(articles))
  219. # We're inside a running event loop (e.g. the poller). Create a new loop
  220. # in a thread to avoid blocking.
  221. import concurrent.futures
  222. with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
  223. future = pool.submit(
  224. asyncio.run, _compute_embeddings_concurrently(articles)
  225. )
  226. return future.result()
  227. # ---------------------------------------------------------------------------
  228. # Orphan merge: detect clusters sharing articles and merge them
  229. # ---------------------------------------------------------------------------
  230. def _merge_orphan_clusters(
  231. clusters: List[Dict[str, Any]],
  232. ) -> List[Dict[str, Any]]:
  233. """Post-clustering pass: merge clusters that share article keys.
  234. This handles the case where two articles about the same event didn't match
  235. during the main loop (e.g. embeddings were temporarily unavailable) and
  236. ended up in separate clusters. If two clusters share >= 1 article key, we
  237. merge them into one (keeping the earlier first_seen, recompute the stable
  238. ID from the union of articles).
  239. """
  240. if len(clusters) <= 1:
  241. return clusters
  242. # Build index: article_key -> list of cluster indices
  243. key_to_indices: dict[str, list[int]] = {}
  244. for idx, c in enumerate(clusters):
  245. for a in c.get("articles", []) or []:
  246. ak = _article_key(a)
  247. if ak:
  248. key_to_indices.setdefault(ak, []).append(idx)
  249. # Find connected components via Union-Find
  250. parent = list(range(len(clusters)))
  251. def find(x: int) -> int:
  252. while parent[x] != x:
  253. parent[x] = parent[parent[x]]
  254. x = parent[x]
  255. return x
  256. def union(a: int, b: int) -> None:
  257. ra, rb = find(a), find(b)
  258. if ra != rb:
  259. parent[ra] = rb
  260. for indices in key_to_indices.values():
  261. for i in range(1, len(indices)):
  262. union(indices[0], indices[i])
  263. # Group clusters by component
  264. components: dict[int, list[int]] = {}
  265. for idx in range(len(clusters)):
  266. root = find(idx)
  267. components.setdefault(root, []).append(idx)
  268. merged: List[Dict[str, Any]] = []
  269. for root, members in components.items():
  270. if len(members) == 1:
  271. merged.append(clusters[members[0]])
  272. continue
  273. # Merge all clusters in this component
  274. base = dict(clusters[members[0]])
  275. all_articles: list[dict] = list(base.get("articles", []) or [])
  276. all_sources: list[str] = list(base.get("sources", []) or [])
  277. first_seen = base.get("first_seen", "")
  278. last_updated = base.get("last_updated", "")
  279. for m_idx in members[1:]:
  280. other = clusters[m_idx]
  281. existing_keys = {_article_key(a) for a in all_articles}
  282. for a in other.get("articles", []) or []:
  283. ak = _article_key(a)
  284. if ak not in existing_keys:
  285. all_articles.append(a)
  286. existing_keys.add(ak)
  287. for s in other.get("sources", []) or []:
  288. if s not in all_sources:
  289. all_sources.append(s)
  290. fs = other.get("first_seen", "")
  291. if fs and (not first_seen or fs < first_seen):
  292. first_seen = fs
  293. lu = other.get("last_updated", "")
  294. if lu and (not last_updated or lu > last_updated):
  295. last_updated = lu
  296. base["articles"] = all_articles
  297. base["sources"] = all_sources
  298. base["first_seen"] = first_seen
  299. base["last_updated"] = last_updated
  300. base["cluster_id"] = _stable_cluster_id(base.get("topic", "other"), all_articles)
  301. merged.append(base)
  302. return merged
  303. # ---------------------------------------------------------------------------
  304. # Public API (sync — backward compatible with tests)
  305. # ---------------------------------------------------------------------------
  306. def dedup_and_cluster_articles(
  307. articles: List[Dict[str, Any]],
  308. similarity_threshold: float | None = None,
  309. *,
  310. existing_clusters: List[Dict[str, Any]] | None = None,
  311. max_age_hours: float = 0,
  312. ) -> Dict[str, List[Dict[str, Any]]]:
  313. """Deduplicate raw articles into clusters keyed by topic.
  314. v1.3: stable cluster IDs, temporal gating, and orphan merge.
  315. Args:
  316. articles: new articles to cluster.
  317. similarity_threshold: override for the title-similarity threshold.
  318. existing_clusters: optional list of recent clusters from the DB to
  319. merge against (cross-cycle merge). When provided, temporal
  320. gating via max_age_hours is applied to filter these.
  321. max_age_hours: only compare against existing_clusters updated within
  322. this many hours. 0 = no limit (compare against all provided).
  323. """
  324. title_threshold = similarity_threshold if similarity_threshold is not None else DEFAULT_TITLE_THRESHOLD
  325. # Pre-compute embeddings concurrently (sync boundary handles async internally)
  326. embedding_cache: Dict[str, list[float] | None] = {}
  327. if NEWS_EMBEDDINGS_ENABLED:
  328. embedding_cache = _compute_embeddings_sync(articles)
  329. by_topic: Dict[str, List[Dict[str, Any]]] = {}
  330. # Seed with existing clusters (filtered by age window).
  331. # Re-derive the topic via the same heuristic (normalize_topic_from_title)
  332. # that new articles use, so that existing and new clusters with the same
  333. # headline land in the same by_topic bucket regardless of what LLM
  334. # enrichment previously stored on the cluster.
  335. if existing_clusters:
  336. for c in existing_clusters:
  337. if not _cluster_is_within_age_window(c, max_age_hours=max_age_hours):
  338. continue
  339. seed_title = c.get("headline") or ""
  340. topic = normalize_topic_from_title(seed_title) if seed_title else (c.get("topic", "other") or "other")
  341. by_topic.setdefault(topic, []).append(dict(c))
  342. for a in articles:
  343. title = a.get("title") or ""
  344. if not title:
  345. continue
  346. topic = normalize_topic_from_title(title)
  347. article_text = _cluster_text(a)
  348. article_embedding = embedding_cache.get(article_text) if NEWS_EMBEDDINGS_ENABLED else None
  349. a_with_emb = dict(a)
  350. if article_embedding is not None:
  351. a_with_emb["_embedding"] = article_embedding
  352. by_topic.setdefault(topic, [])
  353. clusters = by_topic[topic]
  354. best_idx: int | None = None
  355. best_signal_name = "none"
  356. best_signal_value = 0.0
  357. for idx, c in enumerate(clusters):
  358. sigs = _signals(a_with_emb, c)
  359. matched, signal_name, signal_value = _is_match(
  360. sigs,
  361. embeddings_enabled=NEWS_EMBEDDINGS_ENABLED,
  362. title_threshold=title_threshold,
  363. )
  364. if matched and signal_value > best_signal_value:
  365. best_idx = idx
  366. best_signal_name = signal_name
  367. best_signal_value = signal_value
  368. if best_idx is not None:
  369. c = clusters[best_idx]
  370. existing_keys = {_article_key(x) for x in c.get("articles", []) or []}
  371. if _article_key(a) not in existing_keys:
  372. c["articles"].append(a)
  373. if a.get("source") and a["source"] not in c["sources"]:
  374. c["sources"].append(a["source"])
  375. c["last_updated"] = max(str(c.get("last_updated", "")), str(a.get("timestamp", "")))
  376. # Update cluster embedding to the new article's embedding so later
  377. # comparisons can match against the most recently added content.
  378. if NEWS_EMBEDDINGS_ENABLED and article_embedding is not None:
  379. c["embedding"] = article_embedding
  380. c["embedding_model"] = "ollama:nomic-embed-text"
  381. c.setdefault("_merge_signals", []).append(
  382. {"signal": best_signal_name, "value": round(best_signal_value, 3)}
  383. )
  384. else:
  385. cid = _stable_cluster_id(topic, [a])
  386. cluster_embedding = article_embedding if NEWS_EMBEDDINGS_ENABLED else None
  387. clusters.append(
  388. {
  389. "cluster_id": cid,
  390. "headline": title,
  391. "summary": a.get("summary", ""),
  392. "topic": topic,
  393. "entities": [],
  394. "sentiment": "neutral",
  395. "importance": 0.0,
  396. "sources": [a["source"]] if a.get("source") else [],
  397. "timestamp": a.get("timestamp"),
  398. "articles": [a],
  399. "first_seen": a.get("timestamp"),
  400. "last_updated": a.get("timestamp"),
  401. "embedding": cluster_embedding,
  402. "embedding_model": "ollama:nomic-embed-text" if cluster_embedding else None,
  403. }
  404. )
  405. # Post-clustering passes per topic
  406. for topic, clusters in by_topic.items():
  407. # Merge orphans (clusters that share articles)
  408. clusters = _merge_orphan_clusters(clusters)
  409. # Recompute stable IDs from the final article sets
  410. for c in clusters:
  411. c["cluster_id"] = _stable_cluster_id(topic, c.get("articles", []) or [])
  412. by_topic[topic] = clusters
  413. # Cross-topic dedup: merge clusters with overlapping headlines and entities
  414. by_topic = _merge_duplicate_clusters(by_topic)
  415. # Strip the internal merge audit trail before returning
  416. for clusters in by_topic.values():
  417. for c in clusters:
  418. c.pop("_merge_signals", None)
  419. return {topic: clusters for topic, clusters in by_topic.items()}
  420. def _merge_duplicate_clusters(
  421. by_topic: Dict[str, List[Dict[str, Any]]],
  422. ) -> Dict[str, List[Dict[str, Any]]]:
  423. """Cross-topic dedup: merge clusters whose headlines and entities overlap.
  424. Catches the case where the same event arrives from different feeds with
  425. different article keys, lands in separate clusters with different stable
  426. IDs, but has nearly identical headlines and shared entities.
  427. Merge criteria: title_similarity >= 0.90 AND at least one shared entity.
  428. This is intentionally conservative to avoid merging distinct events.
  429. """
  430. # Flatten all clusters with their topic
  431. all_clusters: list[tuple[str, dict]] = []
  432. for topic, clusters in by_topic.items():
  433. for c in clusters:
  434. all_clusters.append((topic, c))
  435. n = len(all_clusters)
  436. if n <= 1:
  437. return by_topic
  438. # Union-Find
  439. parent = list(range(n))
  440. def find(x: int) -> int:
  441. while parent[x] != x:
  442. parent[x] = parent[parent[x]]
  443. x = parent[x]
  444. return x
  445. def union(a: int, b: int) -> None:
  446. ra, rb = find(a), find(b)
  447. if ra != rb:
  448. parent[ra] = rb
  449. # Pre-extract normalized entity sets for each cluster
  450. cluster_ent_sets: list[set[str]] = []
  451. cluster_heads: list[str] = []
  452. for _, c in all_clusters:
  453. ents = {str(e).strip().lower() for e in (c.get("entities", []) or []) if str(e).strip()}
  454. cluster_ent_sets.append(ents)
  455. cluster_heads.append(str(c.get("headline", "") or ""))
  456. # Compare pairs — O(n^2) but n is small (clusters per cycle, not articles)
  457. TITLE_THRESHOLD = 0.90
  458. for i in range(n):
  459. for j in range(i + 1, n):
  460. # Quick skip: if headlines are completely different, no need for entity check
  461. if _title_similarity(cluster_heads[i], cluster_heads[j]) < TITLE_THRESHOLD:
  462. continue
  463. # Check entity overlap (at least one shared entity)
  464. if not (cluster_ent_sets[i] & cluster_ent_sets[j]):
  465. continue
  466. union(i, j)
  467. # Group by component
  468. components: dict[int, list[int]] = {}
  469. for idx in range(n):
  470. root = find(idx)
  471. components.setdefault(root, []).append(idx)
  472. # Merge each component
  473. merged_by_topic: Dict[str, List[Dict[str, Any]]] = {}
  474. for root, members in components.items():
  475. # Pick the base cluster (the one with the most sources, then most articles)
  476. best_idx = max(members, key=lambda i: (
  477. len(all_clusters[i][1].get("sources", []) or []),
  478. len(all_clusters[i][1].get("articles", []) or []),
  479. ))
  480. base_topic, base = all_clusters[best_idx]
  481. if len(members) == 1:
  482. merged_by_topic.setdefault(base_topic, []).append(base)
  483. continue
  484. # Merge all clusters in this component into base
  485. all_articles: list[dict] = list(base.get("articles", []) or [])
  486. all_sources: list[str] = list(base.get("sources", []) or [])
  487. all_entities: list[str] = list(base.get("entities", []) or [])
  488. all_keywords: list[str] = list(base.get("keywords", []) or [])
  489. first_seen = base.get("first_seen", "")
  490. last_updated = base.get("last_updated", "")
  491. existing_article_keys = {_article_key(a) for a in all_articles}
  492. existing_ent_lower = {str(e).strip().lower() for e in all_entities}
  493. existing_kw_lower = {str(k).strip().lower() for k in all_keywords}
  494. for m_idx in members:
  495. if m_idx == best_idx:
  496. continue
  497. other = all_clusters[m_idx][1]
  498. # Merge articles (dedup by key)
  499. for a in other.get("articles", []) or []:
  500. ak = _article_key(a)
  501. if ak not in existing_article_keys:
  502. all_articles.append(a)
  503. existing_article_keys.add(ak)
  504. # Merge sources
  505. for s in other.get("sources", []) or []:
  506. if s not in all_sources:
  507. all_sources.append(s)
  508. # Merge entities (dedup case-insensitive)
  509. for e in other.get("entities", []) or []:
  510. el = str(e).strip().lower()
  511. if el not in existing_ent_lower:
  512. all_entities.append(e)
  513. existing_ent_lower.add(el)
  514. # Merge keywords (dedup case-insensitive)
  515. for k in other.get("keywords", []) or []:
  516. kl = str(k).strip().lower()
  517. if kl not in existing_kw_lower:
  518. all_keywords.append(k)
  519. existing_kw_lower.add(kl)
  520. # Timestamps
  521. fs = other.get("first_seen", "")
  522. if fs and (not first_seen or fs < first_seen):
  523. first_seen = fs
  524. lu = other.get("last_updated", "")
  525. if lu and (not last_updated or lu > last_updated):
  526. last_updated = lu
  527. base["articles"] = all_articles
  528. base["sources"] = all_sources
  529. base["entities"] = all_entities
  530. base["keywords"] = all_keywords
  531. base["first_seen"] = first_seen
  532. base["last_updated"] = last_updated
  533. base["cluster_id"] = _stable_cluster_id(base.get("topic", "other"), all_articles)
  534. merged_by_topic.setdefault(base_topic, []).append(base)
  535. return merged_by_topic