poller.py 4.3 KB

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