dashboard_store.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. from __future__ import annotations
  2. import json
  3. from datetime import datetime, timedelta, timezone
  4. from typing import Any
  5. from email.utils import parsedate_to_datetime
  6. from news_mcp.config import (
  7. NEWS_PRUNE_INTERVAL_HOURS,
  8. NEWS_PRUNING_ENABLED,
  9. NEWS_REFRESH_INTERVAL_SECONDS,
  10. NEWS_RETENTION_DAYS,
  11. )
  12. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  13. class DashboardStore:
  14. """Read-only query layer for the dashboard."""
  15. def __init__(self, store=None):
  16. if store is not None:
  17. self._store = store
  18. else:
  19. from news_mcp.config import DB_PATH
  20. self._store = SQLiteClusterStore(DB_PATH)
  21. # ── Health & Stats ──────────────────────────────────────────────
  22. def get_dashboard_stats(self) -> dict[str, Any]:
  23. with self._store._conn() as conn:
  24. total_clusters = conn.execute("SELECT COUNT(*) FROM clusters").fetchone()[0]
  25. total_entities = conn.execute("SELECT COUNT(*) FROM entity_metadata").fetchone()[0]
  26. cluster_entities = conn.execute(
  27. "SELECT COUNT(DISTINCT e.value) "
  28. "FROM clusters, json_each(clusters.payload, '$.entities') AS e"
  29. ).fetchone()[0]
  30. topic_counts = dict(conn.execute(
  31. "SELECT topic, COUNT(*) FROM clusters GROUP BY topic"
  32. ).fetchall())
  33. last_refresh = self._store.get_meta("last_refresh_at")
  34. last_prune = self._store.get_meta("last_prune_at")
  35. # Freshness: did a refresh happen recently? (within 2x the configured interval)
  36. fresh = False
  37. if last_refresh:
  38. try:
  39. dt = datetime.fromisoformat(last_refresh.replace("Z", "+00:00"))
  40. if dt.tzinfo is None:
  41. dt = dt.replace(tzinfo=timezone.utc)
  42. age_hours = (datetime.now(timezone.utc) - dt).total_seconds() / 3600
  43. fresh = age_hours < max(1.0, NEWS_REFRESH_INTERVAL_SECONDS / 3600) * 2
  44. except Exception:
  45. pass
  46. feeds = {}
  47. with self._store._conn() as conn:
  48. for row in conn.execute("SELECT feed_key, last_hash, last_item_count, enabled, updated_at FROM feed_state ORDER BY updated_at DESC"):
  49. feeds[row[0]] = {"last_hash": row[1], "last_item_count": row[2], "enabled": bool(row[3]), "updated_at": row[4]}
  50. return {
  51. "total_clusters": total_clusters,
  52. "total_entities": total_entities,
  53. "cluster_entities": cluster_entities,
  54. "clusters_by_topic": topic_counts,
  55. "last_refresh_at": last_refresh,
  56. "last_prune_at": last_prune,
  57. "data_fresh": fresh,
  58. "feeds": feeds,
  59. "feed_count": len(feeds),
  60. "pruning": {
  61. "enabled": NEWS_PRUNING_ENABLED,
  62. "retention_days": NEWS_RETENTION_DAYS,
  63. "interval_hours": NEWS_PRUNE_INTERVAL_HOURS,
  64. "last_prune_at": last_prune,
  65. },
  66. }
  67. # ── Clusters ────────────────────────────────────────────────────
  68. def get_clusters_page(
  69. self,
  70. topic: str | None = None,
  71. hours: float = 24,
  72. limit: int = 20,
  73. offset: int = 0,
  74. ) -> list[dict[str, Any]]:
  75. cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat()
  76. query = "SELECT payload FROM clusters WHERE updated_at >= ?"
  77. params: list = [cutoff]
  78. if topic and topic != "all":
  79. query += " AND topic = ?"
  80. params.append(topic)
  81. query += " ORDER BY updated_at DESC LIMIT ? OFFSET ?"
  82. params.extend([limit, offset])
  83. with self._store._conn() as conn:
  84. cur = conn.execute(query, params)
  85. rows = cur.fetchall()
  86. clusters: list[dict[str, Any]] = []
  87. for (payload_text,) in rows:
  88. c = json.loads(payload_text)
  89. clusters.append({
  90. "cluster_id": c.get("cluster_id", ""),
  91. "headline": c.get("headline", ""),
  92. "topic": c.get("topic", ""),
  93. "sentiment": c.get("sentiment", "neutral"),
  94. "sentimentScore": c.get("sentimentScore"),
  95. "importance": c.get("importance", 0),
  96. "entities": c.get("entities", []),
  97. "sources": c.get("sources", []),
  98. "timestamp": c.get("timestamp", ""),
  99. "keywords": c.get("keywords", []),
  100. "article_count": len(c.get("articles", [])),
  101. })
  102. return clusters
  103. def get_cluster_detail(self, cluster_id: str) -> dict[str, Any] | None:
  104. with self._store._conn() as conn:
  105. cur = conn.execute(
  106. "SELECT payload FROM clusters WHERE cluster_id = ?", (cluster_id,)
  107. )
  108. row = cur.fetchone()
  109. if not row:
  110. return None
  111. c = json.loads(row[0])
  112. summary = None
  113. if c.get("summary_payload"):
  114. try:
  115. summary = json.loads(c["summary_payload"])
  116. except Exception:
  117. pass
  118. return {
  119. "cluster_id": c.get("cluster_id"),
  120. "headline": c.get("headline", ""),
  121. "summary": c.get("summary", ""),
  122. "topic": c.get("topic", ""),
  123. "sentiment": c.get("sentiment", "neutral"),
  124. "sentimentScore": c.get("sentimentScore"),
  125. "importance": c.get("importance", 0),
  126. "entities": c.get("entities", []),
  127. "entityResolutions": c.get("entityResolutions", []),
  128. "keywords": c.get("keywords", []),
  129. "sources": c.get("sources", []),
  130. "timestamp": c.get("timestamp", ""),
  131. "first_seen": c.get("first_seen", ""),
  132. "last_updated": c.get("last_updated", ""),
  133. "article_count": len(c.get("articles", [])),
  134. "articles": c.get("articles", []),
  135. "summary_text": summary.get("mergedSummary", "") if summary else "",
  136. "key_facts": summary.get("keyFacts", []) if summary else [],
  137. }
  138. # ── Sentiment Series ────────────────────────────────────────────
  139. def get_sentiment_series(
  140. self,
  141. topic: str | None = None,
  142. hours: float = 24,
  143. bucket_hours: float = 1,
  144. ) -> list[dict[str, Any]]:
  145. cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat()
  146. query = "SELECT payload FROM clusters WHERE updated_at >= ?"
  147. params: list = [cutoff]
  148. if topic and topic != "all":
  149. query += " AND topic = ?"
  150. params.append(topic)
  151. query += " ORDER BY updated_at ASC"
  152. with self._store._conn() as conn:
  153. cur = conn.execute(query, params)
  154. rows = cur.fetchall()
  155. def _parse_ts(ts: Any) -> datetime | None:
  156. if not ts:
  157. return None
  158. s = str(ts)
  159. try:
  160. dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
  161. except Exception:
  162. try:
  163. dt = parsedate_to_datetime(s)
  164. except Exception:
  165. return None
  166. if dt.tzinfo is None:
  167. dt = dt.replace(tzinfo=timezone.utc)
  168. return dt.astimezone(timezone.utc)
  169. step_hours = max(1, int(bucket_hours))
  170. buckets: dict[datetime, list[float]] = {}
  171. for (payload_text,) in rows:
  172. c = json.loads(payload_text)
  173. dt = _parse_ts(c.get("timestamp"))
  174. score = c.get("sentimentScore")
  175. if dt is None or score is None:
  176. continue
  177. bucket_key = dt.replace(minute=0, second=0, microsecond=0)
  178. if step_hours > 1:
  179. bucket_key = bucket_key.replace(
  180. hour=(bucket_key.hour // step_hours) * step_hours
  181. )
  182. buckets.setdefault(bucket_key, []).append(float(score))
  183. series: list[dict[str, Any]] = []
  184. for bucket_key in sorted(buckets):
  185. scores = buckets[bucket_key]
  186. series.append({
  187. "time": bucket_key.isoformat(),
  188. "avg_sentiment": round(sum(scores) / len(scores), 3),
  189. "count": len(scores),
  190. "min": round(min(scores), 3),
  191. "max": round(max(scores), 3),
  192. })
  193. return series
  194. # ── Entity Frequencies ──────────────────────────────────────────
  195. def get_entity_frequencies(
  196. self,
  197. hours: float = 24,
  198. limit: int = 30,
  199. ) -> list[dict[str, Any]]:
  200. cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat()
  201. with self._store._conn() as conn:
  202. cur = conn.execute(
  203. "SELECT payload FROM clusters WHERE updated_at >= ? "
  204. "ORDER BY updated_at DESC LIMIT 500",
  205. (cutoff,),
  206. )
  207. rows = cur.fetchall()
  208. counter: dict[str, int] = {}
  209. for (payload_text,) in rows:
  210. c = json.loads(payload_text)
  211. for ent in c.get("entities", []):
  212. counter[ent] = counter.get(ent, 0) + 1
  213. sorted_entities = sorted(counter.items(), key=lambda x: -x[1])[:limit]
  214. result: list[dict[str, Any]] = []
  215. for label, count in sorted_entities:
  216. meta = self._store.get_entity_metadata(label)
  217. result.append({
  218. "label": label,
  219. "count": count,
  220. "canonical_label": meta["canonical_label"] if meta else label,
  221. "mid": meta["mid"] if meta else None,
  222. })
  223. return result