dashboard_store.py 9.8 KB

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