poller.py 3.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from __future__ import annotations
  2. import logging
  3. from typing import Any, Dict
  4. from news_mcp.config import CLUSTERS_TTL_HOURS, DB_PATH, NEWS_FEED_URL, NEWS_FEED_URLS
  5. from news_mcp.dedup.cluster import dedup_and_cluster_articles
  6. from news_mcp.enrichment.enrich import enrich_cluster
  7. from news_mcp.enrichment.llm_enrich import classify_cluster_groq
  8. from news_mcp.trends_resolution import resolve_entity_via_trends
  9. from news_mcp.sources.news_feeds import fetch_news_articles
  10. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  11. from news_mcp.config import GROQ_ENRICH_OTHER_ONLY, GROQ_MAX_CLUSTERS_PER_REFRESH
  12. async def refresh_clusters(topic: str | None = None, limit: int = 80) -> None:
  13. logger = logging.getLogger("news_mcp.refresh")
  14. store = SQLiteClusterStore(DB_PATH)
  15. logger.info("refresh start topic=%s limit=%s", topic, limit)
  16. articles = fetch_news_articles(limit=limit)
  17. logger.info("refresh fetched articles=%s", len(articles))
  18. # Skip expensive work if the feed content (titles/urls/timestamps) didn't change.
  19. import hashlib
  20. rss_urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  21. if not rss_urls:
  22. rss_urls = [NEWS_FEED_URL]
  23. feed_key = "newsfeeds:" + hashlib.sha1(",".join(rss_urls).encode("utf-8")).hexdigest()
  24. material = "\n".join(
  25. f"{a.get('title','')}|{a.get('url','')}|{a.get('timestamp','')}"
  26. for a in articles
  27. )
  28. last_hash = hashlib.sha1(material.encode("utf-8")).hexdigest()
  29. prev_hash = store.get_feed_hash(feed_key)
  30. if prev_hash == last_hash:
  31. logger.info("refresh unchanged feed_key=%s topic=%s", feed_key, topic)
  32. return
  33. logger.info("refresh changed feed_key=%s topic=%s", feed_key, topic)
  34. store.set_feed_hash(feed_key, last_hash)
  35. clustered_by_topic = dedup_and_cluster_articles(articles)
  36. logger.info("refresh clustered topics=%s", list(clustered_by_topic.keys()))
  37. for t, clusters in clustered_by_topic.items():
  38. if topic and t != topic:
  39. continue
  40. enriched = []
  41. # Always compute cheap enrichment first.
  42. for idx, c in enumerate(clusters[:GROQ_MAX_CLUSTERS_PER_REFRESH]):
  43. c2 = enrich_cluster(c)
  44. # Groq enrichment only when configured.
  45. if (not GROQ_ENRICH_OTHER_ONLY) or (t == "other"):
  46. # Cache Groq: if we already have entities/sentiment for this cluster, skip.
  47. existing = store.get_cluster_by_id(c2.get("cluster_id"))
  48. if existing and existing.get("entities"):
  49. c2 = dict(c2)
  50. # Keep existing enriched fields.
  51. c2["entities"] = existing.get("entities", [])
  52. # IMPORTANT: entityResolutions must stay consistent with entities.
  53. # Older rows may have entities but missing/malformed resolutions.
  54. existing_resolutions = existing.get("entityResolutions", None)
  55. if isinstance(existing_resolutions, list) and existing_resolutions:
  56. c2["entityResolutions"] = existing_resolutions
  57. else:
  58. # Recompute resolutions deterministically from the stored entities.
  59. c2["entityResolutions"] = [resolve_entity_via_trends(e) for e in c2["entities"]]
  60. if existing.get("sentiment"):
  61. c2["sentiment"] = existing.get("sentiment")
  62. if existing.get("sentimentScore") is not None:
  63. c2["sentimentScore"] = existing.get("sentimentScore")
  64. if existing.get("keywords"):
  65. c2["keywords"] = existing.get("keywords")
  66. else:
  67. c2 = await classify_cluster_groq(c2)
  68. enriched.append(c2)
  69. store.upsert_clusters(enriched, topic=t)
  70. logger.info("refresh stored topic=%s clusters=%s", t, len(enriched))