Dmitry Beresnev commited on
Commit ·
c571607
1
Parent(s): 4bd052e
Added a shared SQLite store and buffer.
Browse filesAdded a background worker process with retries and batching.
Updated dashboard to enqueue items and read summaries from the shared cache.
Files changed (4)
- app/pages/05_Dashboard.py+12-9
- app/utils/ai_summary_store.pyAdded+195
- app/utils/ai_summary_worker.pyAdded+110
- app/utils/news_cache.py+8-5
25 unmodified lines26272829303132232 unmodified lines265266267268269270285 unmodified lines556557558559560561562563564565566567307 unmodified lines87587687787887988088188288317 unmodified lines90190290390490590690725 unmodified linesdisplay_economic_calendar_widget)from utils.breaking_news_scorer import get_breaking_news_scorerfrom utils.ai_summary_cache import ai_summary_cache# Import news scraperstry:232 unmodified lines# Check for forced refresh (don't clear yet - wait until after fetching)force_refresh = st.session_state.get('force_refresh', False)# Fetch news from all sources IN PARALLEL for maximum performanceimport pandas as pdfrom concurrent.futures import ThreadPoolExecutor, as_completed285 unmodified linesfor df in ai_summary_dfs:if df.empty:continuerecords = df.to_dict("records")all_items.extend(records)if all_items:ai_summary_cache.buffer_items(all_items)ai_summary_cache.maybe_flush()# Clear force refresh flag after fetching is completeif force_refresh:307 unmodified linesst.markdown("---")@st.fragment(run_every=60)def render_ai_summary_section():summaries, last_update = ai_summary_cache.get_summaries()status = ai_summary_cache.get_status()last_update_text = last_update.strftime("%Y-%m-%d %H:%M:%S") if last_update else "N/A"buffer_remaining = status.get("buffer_remaining_seconds")buffer_text = "N/A"if buffer_remaining is not None:17 unmodified lines)if summaries:for item in summaries[:50]:source = item.get("source", "")summary = item.get("summary", "")title = item.get("title", "")25 unmodified lines2627282930313233232 unmodified lines266267268269270271272273274275285 unmodified lines561562563564565566567568569570307 unmodified lines87887988088188288388488588617 unmodified lines90490590690790890991025 unmodified linesdisplay_economic_calendar_widget)from utils.breaking_news_scorer import get_breaking_news_scorerfrom utils.ai_summary_store import init_db, enqueue_items, fetch_summaries, get_statusfrom utils.ai_summary_worker import start_worker_if_needed# Import news scraperstry:232 unmodified lines# Check for forced refresh (don't clear yet - wait until after fetching)force_refresh = st.session_state.get('force_refresh', False)# Initialize AI summary store/worker (shared across sessions/processes)init_db()start_worker_if_needed()# Fetch news from all sources IN PARALLEL for maximum performanceimport pandas as pdfrom concurrent.futures import ThreadPoolExecutor, as_completed285 unmodified linesfor df in ai_summary_dfs:if df.empty:continueall_items.extend(df.to_dict("records"))if all_items:enqueue_items(all_items)# Clear force refresh flag after fetching is completeif force_refresh:307 unmodified linesst.markdown("---")@st.fragment(run_every=60)def render_ai_summary_section():summaries = fetch_summaries(limit=50)status = get_status()last_update_text = status.get("last_update") or "N/A"buffer_remaining = status.get("buffer_remaining_seconds")buffer_text = "N/A"if buffer_remaining is not None:17 unmodified lines)if summaries:for item in summaries:source = item.get("source", "")summary = item.get("summary", "")title = item.get("title", "")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""SQLite-backed AI summary buffer and cache (shared across processes)."""
import osimport sqlite3import timefrom contextlib import contextmanagerfrom datetime import datetimefrom typing import Dict, Iterable, List, Optional, Tuple
DB_PATH = os.getenv("AI_SUMMARY_DB_PATH", "/tmp/ai_summary_cache.sqlite")BUFFER_SECONDS = int(os.getenv("LLM_SUMMARY_BUFFER_SECONDS", "120"))BATCH_MAX_CHARS = int(os.getenv("LLM_SUMMARY_BATCH_MAX_CHARS", "2400"))
def _connect() -> sqlite3.Connection: conn = sqlite3.connect(DB_PATH, timeout=30, isolation_level=None) conn.execute("PRAGMA journal_mode=WAL;") conn.execute("PRAGMA synchronous=NORMAL;") return conn
@contextmanagerdef _db(): conn = _connect() try: yield conn finally: conn.close()
def init_db(): with _db() as conn: conn.execute( """ CREATE TABLE IF NOT EXISTS summary_buffer ( item_key TEXT PRIMARY KEY, title TEXT NOT NULL, source TEXT, created_at REAL NOT NULL ); """ ) conn.execute( """ CREATE TABLE IF NOT EXISTS summaries ( item_key TEXT PRIMARY KEY, title TEXT NOT NULL, source TEXT, summary TEXT NOT NULL, updated_at REAL NOT NULL ); """ )
def _item_key(item: Dict) -> str: if item.get("id") is not None: return str(item.get("id")) title = str(item.get("title", "")).strip() source = str(item.get("source", "")).strip() if not title: return "" return f"{source}|{title}".lower()
def enqueue_items(items: Iterable[Dict]): now = time.time() rows = [] for item in items: key = _item_key(item) title = str(item.get("title", "")).strip() if not key or not title: continue source = str(item.get("source", "")).strip() rows.append((key, title, source, now))
if not rows: return
with _db() as conn: conn.executemany( """ INSERT OR IGNORE INTO summary_buffer (item_key, title, source, created_at) VALUES (?, ?, ?, ?) """, rows, )
def get_status() -> Dict: with _db() as conn: buffer_count = conn.execute("SELECT COUNT(*) FROM summary_buffer").fetchone()[0] summaries_count = conn.execute("SELECT COUNT(*) FROM summaries").fetchone()[0] last_update_row = conn.execute("SELECT MAX(updated_at) FROM summaries").fetchone() buffer_oldest_row = conn.execute("SELECT MIN(created_at) FROM summary_buffer").fetchone()
last_update = ( datetime.fromtimestamp(last_update_row[0]).strftime("%Y-%m-%d %H:%M:%S") if last_update_row and last_update_row[0] else None ) buffer_oldest = buffer_oldest_row[0] if buffer_oldest_row else None buffer_remaining = None if buffer_oldest: age = time.time() - buffer_oldest buffer_remaining = max(BUFFER_SECONDS - age, 0)
return { "buffer_size": buffer_count, "total_summaries": summaries_count, "last_update": last_update, "buffer_remaining_seconds": buffer_remaining, "batch_max_chars": BATCH_MAX_CHARS, "buffer_window_seconds": BUFFER_SECONDS, }
def fetch_summaries(limit: int = 50) -> List[Dict]: with _db() as conn: rows = conn.execute( """ SELECT title, source, summary, updated_at FROM summaries ORDER BY updated_at DESC LIMIT ? """, (limit,), ).fetchall()
results = [] for title, source, summary, updated_at in rows: results.append( { "title": title, "source": source or "", "summary": summary, "timestamp": datetime.fromtimestamp(updated_at), } ) return results
def _build_input_text(title: str, source: str) -> str: if source: return f"Source: {source}\nTitle: {title}" return f"Title: {title}"
def fetch_ready_batches(max_chars_total: int, buffer_seconds: int) -> List[List[Tuple[str, str, str]]]: cutoff = time.time() - buffer_seconds with _db() as conn: rows = conn.execute( """ SELECT item_key, title, source FROM summary_buffer WHERE created_at <= ? ORDER BY created_at ASC """, (cutoff,), ).fetchall()
batches: List[List[Tuple[str, str, str]]] = [] current: List[Tuple[str, str, str]] = [] current_chars = 0
for item_key, title, source in rows: text = _build_input_text(title, source or "") text_len = len(text) if current and current_chars + text_len > max_chars_total: batches.append(current) current = [] current_chars = 0 current.append((item_key, title, source or "")) current_chars += text_len
if current: batches.append(current)
return batches
def store_summaries(items: List[Tuple[str, str, str, str]]): now = time.time() with _db() as conn: conn.executemany( """ INSERT OR REPLACE INTO summaries (item_key, title, source, summary, updated_at) VALUES (?, ?, ?, ?, ?) """, [(k, t, s, summary, now) for k, t, s, summary in items], ) conn.executemany( "DELETE FROM summary_buffer WHERE item_key = ?", [(k,) for k, _, _, _ in items], )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Background worker process for AI summarization."""
import osimport timeimport loggingimport signalimport sqlite3from typing import List, Tuple
from utils.llm_summarizer import OpenAICompatSummarizerfrom utils.ai_summary_store import ( init_db, fetch_ready_batches, store_summaries, BATCH_MAX_CHARS, BUFFER_SECONDS,)
logger = logging.getLogger(__name__)
PID_FILE = os.getenv("AI_SUMMARY_WORKER_PID", "/tmp/ai_summary_worker.pid")POLL_SECONDS = int(os.getenv("AI_SUMMARY_POLL_SECONDS", "5"))MAX_RETRIES = int(os.getenv("LLM_SUMMARY_RETRIES", "3"))
class Worker: def __init__(self): self._stop = False self.summarizer = OpenAICompatSummarizer()
def stop(self, *_args): self._stop = True
def run(self): init_db() signal.signal(signal.SIGTERM, self.stop) signal.signal(signal.SIGINT, self.stop)
while not self._stop: try: batches = fetch_ready_batches(BATCH_MAX_CHARS, BUFFER_SECONDS) for batch in batches: self._process_batch(batch) except sqlite3.Error as exc: logger.warning(f"AI worker DB error: {exc}") except Exception as exc: logger.warning(f"AI worker error: {exc}")
time.sleep(POLL_SECONDS)
def _process_batch(self, batch: List[Tuple[str, str, str]]): if not batch or not self.summarizer.enabled: return
texts = [] for _, title, source in batch: if source: texts.append(f"Source: {source}\nTitle: {title}") else: texts.append(f"Title: {title}")
for attempt in range(1, MAX_RETRIES + 1): summaries = self.summarizer._summarize_chunk(texts, source="dashboard") if summaries and len(summaries) == len(batch): break if attempt < MAX_RETRIES: time.sleep(2 ** attempt) else: logger.warning("AI worker failed to summarize batch after retries") return
to_store = [] for (item_key, title, source), summary in zip(batch, summaries): if not summary: continue to_store.append((item_key, title, source, summary))
if to_store: store_summaries(to_store)
def _pid_running(pid: int) -> bool: try: os.kill(pid, 0) return True except Exception: return False
def start_worker_if_needed(): if os.path.exists(PID_FILE): try: with open(PID_FILE, "r", encoding="utf-8") as f: pid = int(f.read().strip() or 0) if pid and _pid_running(pid): return except Exception: pass
pid = os.fork() if pid != 0: return
os.setsid() with open(PID_FILE, "w", encoding="utf-8") as f: f.write(str(os.getpid()))
worker = Worker() worker.run()
48 unmodified lines4950515253543 unmodified lines58596061626329 unmodified lines9394959697989910010110210310448 unmodified linessource: str,fetcher_func: Callable,force_refresh: bool = False,**kwargs) -> List[Dict]:"""3 unmodified linessource: News source ('twitter', 'reddit', 'rss', 'ai_tech')fetcher_func: Function to fetch fresh newsforce_refresh: If True, bypass cache and fetch fresh**kwargs: Arguments to pass to fetcher_funcReturns:29 unmodified lines# Update cacheself._update_cache(source, new_items)# Deduplicate across sourcesdeduplicated = self._deduplicate(new_items, source)logger.info(f"✅ Fetched {len(new_items)} items for {source}, {len(deduplicated)} unique after dedup")return deduplicatedexcept Exception as e:logger.error(f"Error fetching news for {source}: {e}")48 unmodified lines495051525354553 unmodified lines5960616263646529 unmodified lines959697989910010110210310410510610748 unmodified linessource: str,fetcher_func: Callable,force_refresh: bool = False,deduplicate: bool = False,**kwargs) -> List[Dict]:"""3 unmodified linessource: News source ('twitter', 'reddit', 'rss', 'ai_tech')fetcher_func: Function to fetch fresh newsforce_refresh: If True, bypass cache and fetch freshdeduplicate: If True, remove duplicates across sources using global index**kwargs: Arguments to pass to fetcher_funcReturns:29 unmodified lines# Update cacheself._update_cache(source, new_items)if deduplicate:deduplicated = self._deduplicate(new_items, source)logger.info(f"✅ Fetched {len(new_items)} items for {source}, {len(deduplicated)} unique after dedup")return deduplicatedlogger.info(f"✅ Fetched {len(new_items)} items for {source} (dedup disabled)")return new_itemsexcept Exception as e:logger.error(f"Error fetching news for {source}: {e}")
app/pages/05_Dashboard.py+12-9
app/utils/ai_summary_store.pyAdded+195
app/utils/ai_summary_worker.pyAdded+110
app/utils/news_cache.py+8-5