dashboard_store.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. now = datetime.now(timezone.utc).isoformat()
  77. query = "SELECT payload FROM clusters WHERE updated_at >= ? AND updated_at <= ?"
  78. params: list = [cutoff, now]
  79. if topic and topic != "all":
  80. query += " AND topic = ?"
  81. params.append(topic)
  82. query += " ORDER BY updated_at DESC LIMIT ? OFFSET ?"
  83. params.extend([limit, offset])
  84. with self._store._conn() as conn:
  85. cur = conn.execute(query, params)
  86. rows = cur.fetchall()
  87. clusters: list[dict[str, Any]] = []
  88. for (payload_text,) in rows:
  89. c = json.loads(payload_text)
  90. clusters.append({
  91. "cluster_id": c.get("cluster_id", ""),
  92. "headline": c.get("headline", ""),
  93. "topic": c.get("topic", ""),
  94. "sentiment": c.get("sentiment", "neutral"),
  95. "sentimentScore": c.get("sentimentScore"),
  96. "importance": c.get("importance", 0),
  97. "entities": c.get("entities", []),
  98. "sources": c.get("sources", []),
  99. "timestamp": c.get("timestamp", ""),
  100. "keywords": c.get("keywords", []),
  101. "article_count": len(c.get("articles", [])),
  102. })
  103. return clusters
  104. def get_cluster_detail(self, cluster_id: str) -> dict[str, Any] | None:
  105. with self._store._conn() as conn:
  106. cur = conn.execute(
  107. "SELECT payload FROM clusters WHERE cluster_id = ?", (cluster_id,)
  108. )
  109. row = cur.fetchone()
  110. if not row:
  111. return None
  112. c = json.loads(row[0])
  113. summary = None
  114. if c.get("summary_payload"):
  115. try:
  116. summary = json.loads(c["summary_payload"])
  117. except Exception:
  118. pass
  119. return {
  120. "cluster_id": c.get("cluster_id"),
  121. "headline": c.get("headline", ""),
  122. "summary": c.get("summary", ""),
  123. "topic": c.get("topic", ""),
  124. "sentiment": c.get("sentiment", "neutral"),
  125. "sentimentScore": c.get("sentimentScore"),
  126. "importance": c.get("importance", 0),
  127. "entities": c.get("entities", []),
  128. "entityResolutions": c.get("entityResolutions", []),
  129. "keywords": c.get("keywords", []),
  130. "sources": c.get("sources", []),
  131. "timestamp": c.get("timestamp", ""),
  132. "first_seen": c.get("first_seen", ""),
  133. "last_updated": c.get("last_updated", ""),
  134. "article_count": len(c.get("articles", [])),
  135. "articles": c.get("articles", []),
  136. "summary_text": summary.get("mergedSummary", "") if summary else "",
  137. "key_facts": summary.get("keyFacts", []) if summary else [],
  138. }
  139. # ── Sentiment Series ────────────────────────────────────────────
  140. def get_sentiment_series(
  141. self,
  142. topic: str | None = None,
  143. hours: float = 24,
  144. bucket_hours: float = 1,
  145. ) -> list[dict[str, Any]]:
  146. """Sentiment score averaged per time bucket.
  147. Filters by the cluster's own event timestamp (payload.timestamp),
  148. not by updated_at which tracks row modification time.
  149. """
  150. cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
  151. query = "SELECT payload FROM clusters"
  152. params: list = []
  153. if topic and topic != "all":
  154. query += " WHERE topic = ?"
  155. params.append(topic)
  156. query += " ORDER BY updated_at ASC"
  157. with self._store._conn() as conn:
  158. cur = conn.execute(query, params)
  159. rows = cur.fetchall()
  160. def _parse_ts(ts: Any) -> datetime | None:
  161. if not ts:
  162. return None
  163. s = str(ts).strip()
  164. try:
  165. dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
  166. except Exception:
  167. try:
  168. dt = parsedate_to_datetime(s)
  169. except Exception:
  170. return None
  171. if dt.tzinfo is None:
  172. dt = dt.replace(tzinfo=timezone.utc)
  173. return dt.astimezone(timezone.utc)
  174. buckets: dict[datetime, list[float]] = {}
  175. for (payload_text,) in rows:
  176. c = json.loads(payload_text)
  177. dt = _parse_ts(c.get("timestamp"))
  178. score = c.get("sentimentScore")
  179. if dt is None or score is None:
  180. continue
  181. if dt < cutoff:
  182. continue
  183. bucket_key = dt.replace(minute=0, second=0, microsecond=0)
  184. if bucket_hours > 1:
  185. bucket_key = bucket_key.replace(
  186. hour=(bucket_key.hour // int(bucket_hours)) * int(bucket_hours)
  187. )
  188. buckets.setdefault(bucket_key, []).append(float(score))
  189. series: list[dict[str, Any]] = []
  190. for bucket_key in sorted(buckets):
  191. scores = buckets[bucket_key]
  192. series.append({
  193. "time": bucket_key.isoformat(),
  194. "avg_sentiment": round(sum(scores) / len(scores), 3),
  195. "count": len(scores),
  196. "min": round(min(scores), 3),
  197. "max": round(max(scores), 3),
  198. })
  199. return series
  200. # ── Entity Frequencies ──────────────────────────────────────────
  201. def get_entity_frequencies(
  202. self,
  203. hours: float = 24,
  204. limit: int = 30,
  205. ) -> list[dict[str, Any]]:
  206. """Top entities by mention count in recent clusters.
  207. Filters by the cluster's own event timestamp (payload.timestamp),
  208. not by updated_at which tracks row modification time.
  209. """
  210. cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
  211. query = "SELECT payload FROM clusters"
  212. params: list = []
  213. with self._store._conn() as conn:
  214. cur = conn.execute(query, params)
  215. rows = cur.fetchall()
  216. def _parse_ts(ts):
  217. if not ts:
  218. return None
  219. s = str(ts).strip()
  220. try:
  221. dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
  222. except Exception:
  223. try:
  224. from email.utils import parsedate_to_datetime
  225. dt = parsedate_to_datetime(s)
  226. except Exception:
  227. return None
  228. if dt.tzinfo is None:
  229. dt = dt.replace(tzinfo=timezone.utc)
  230. return dt.astimezone(timezone.utc)
  231. counter: dict[str, int] = {}
  232. for (payload_text,) in rows:
  233. c = json.loads(payload_text)
  234. dt = _parse_ts(c.get("timestamp"))
  235. if dt is None:
  236. continue
  237. if dt < cutoff:
  238. continue
  239. for ent in c.get("entities", []):
  240. counter[ent] = counter.get(ent, 0) + 1
  241. sorted_entities = sorted(counter.items(), key=lambda x: -x[1])[:limit]
  242. result: list[dict[str, Any]] = []
  243. for label, count in sorted_entities:
  244. meta = self._store.get_entity_metadata(label)
  245. result.append({
  246. "label": label,
  247. "count": count,
  248. "canonical_label": meta["canonical_label"] if meta else label,
  249. "mid": meta["mid"] if meta else None,
  250. })
  251. return result
  252. # ── Keyword Frequencies ─────────────────────────────────────────
  253. def get_keyword_frequencies(
  254. self,
  255. hours: float = 24,
  256. limit: int = 30,
  257. ) -> list[dict[str, Any]]:
  258. """Top keywords by occurrence count in recent clusters.
  259. Mirrors get_entity_frequencies but for LLM-curated thematic keywords.
  260. Filters by the cluster's own event timestamp (payload.timestamp).
  261. Only includes keywords that are NOT already extracted as entities
  262. in the same cluster — the entity signal is higher quality and is
  263. already shown in the entity frequencies view.
  264. """
  265. cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
  266. query = "SELECT payload FROM clusters"
  267. params: list = []
  268. with self._store._conn() as conn:
  269. cur = conn.execute(query, params)
  270. rows = cur.fetchall()
  271. def _parse_ts(ts):
  272. if not ts:
  273. return None
  274. s = str(ts).strip()
  275. try:
  276. dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
  277. except Exception:
  278. try:
  279. dt = parsedate_to_datetime(s)
  280. except Exception:
  281. return None
  282. if dt.tzinfo is None:
  283. dt = dt.replace(tzinfo=timezone.utc)
  284. return dt.astimezone(timezone.utc)
  285. counter: dict[str, int] = {}
  286. for (payload_text,) in rows:
  287. c = json.loads(payload_text)
  288. dt = _parse_ts(c.get("timestamp"))
  289. if dt is None:
  290. continue
  291. if dt < cutoff:
  292. continue
  293. # Get entities in this cluster to dedup against keywords
  294. ents_in_cluster = {str(e).strip().lower() for e in (c.get("entities", []) or []) if str(e).strip()}
  295. for kw in c.get("keywords", []):
  296. kw_str = str(kw).strip()
  297. if not kw_str:
  298. continue
  299. # Skip keywords that are already entities in this cluster
  300. if kw_str.lower() in ents_in_cluster:
  301. continue
  302. counter[kw_str] = counter.get(kw_str, 0) + 1
  303. sorted_kws = sorted(counter.items(), key=lambda x: -x[1])[:limit]
  304. return [
  305. {"label": label, "count": count}
  306. for label, count in sorted_kws
  307. ]