import sqlite3 import os import traceback from datetime import datetime DB_FILE = "sentiment_analytics.db" def init_db(): """Initializes the SQLite database and creates tables if they do not exist.""" try: conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() # Create sessions table cursor.execute(""" CREATE TABLE IF NOT EXISTS sessions ( session_id TEXT PRIMARY KEY, article_id TEXT, language_code TEXT, country TEXT, city TEXT, timestamp TEXT ) """) # Create utterance_logs table cursor.execute(""" CREATE TABLE IF NOT EXISTS utterance_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, timestamp TEXT, user_text TEXT, model_text TEXT, primary_emotion TEXT, secondary_emotion TEXT, valence REAL, arousal REAL, dominance REAL, FOREIGN KEY(session_id) REFERENCES sessions(session_id) ) """) conn.commit() conn.close() print("[INFO] Local SQLite Analytics Database initialized.", flush=True) except Exception as e: print(f"[ERROR] Failed to initialize SQLite database: {e}", flush=True) traceback.print_exc() def log_session(session_id: str, article_id: str, language_code: str, country: str, city: str): """Registers a session in the database.""" try: conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() timestamp = datetime.utcnow().isoformat() cursor.execute(""" INSERT OR REPLACE INTO sessions (session_id, article_id, language_code, country, city, timestamp) VALUES (?, ?, ?, ?, ?, ?) """, (session_id, article_id, language_code, country, city, timestamp)) conn.commit() conn.close() except Exception as e: print(f"[ERROR] Failed to log session {session_id}: {e}", flush=True) def log_utterance(session_id: str, user_text: str, model_text: str, primary_emotion: str, secondary_emotion: str, valence: float, arousal: float, dominance: float): """Logs a single conversational turn (utterance) with granular sentiment scores.""" try: conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() timestamp = datetime.utcnow().isoformat() cursor.execute(""" INSERT INTO utterance_logs (session_id, timestamp, user_text, model_text, primary_emotion, secondary_emotion, valence, arousal, dominance) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) """, (session_id, timestamp, user_text, model_text, primary_emotion, secondary_emotion, valence, arousal, dominance)) conn.commit() conn.close() except Exception as e: print(f"[ERROR] Failed to log utterance for session {session_id}: {e}", flush=True) def get_analytics_data(): """Retrieves aggregated analytics data for the admin dashboard.""" try: conn = sqlite3.connect(DB_FILE) conn.row_factory = sqlite3.Row cursor = conn.cursor() # 1. Total sessions and utterances counts cursor.execute("SELECT COUNT(*) FROM sessions") total_sessions = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM utterance_logs") total_utterances = cursor.fetchone()[0] # 2. Sentiment average metrics by article cursor.execute(""" SELECT s.article_id, COUNT(u.id) as interactions, AVG(u.valence) as avg_valence, AVG(u.arousal) as avg_arousal, AVG(u.dominance) as avg_dominance FROM sessions s JOIN utterance_logs u ON s.session_id = u.session_id GROUP BY s.article_id ORDER BY interactions DESC """) articles = [dict(row) for row in cursor.fetchall()] # 3. Dynamic geo locations for pins cursor.execute(""" SELECT session_id, country, city, timestamp, article_id FROM sessions WHERE country IS NOT NULL AND country != '' """) geo_pins = [dict(row) for row in cursor.fetchall()] # 4. Active parameter occurrence lookup cursor.execute(""" SELECT primary_emotion, COUNT(*) as count FROM utterance_logs WHERE primary_emotion IS NOT NULL AND primary_emotion != '' GROUP BY primary_emotion ORDER BY count DESC """) emotions = [dict(row) for row in cursor.fetchall()] conn.close() return { "stats": { "total_sessions": total_sessions, "total_utterances": total_utterances }, "articles": articles, "geo_pins": geo_pins, "emotions": emotions } except Exception as e: print(f"[ERROR] Failed to fetch analytics data: {e}", flush=True) return {"stats": {"total_sessions": 0, "total_utterances": 0}, "articles": [], "geo_pins": [], "emotions": []} def get_session_timeline(session_id: str): """Retrieves chronological utterance records for a specific session to plot on the timeline.""" try: conn = sqlite3.connect(DB_FILE) conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(""" SELECT timestamp, user_text, model_text, primary_emotion, secondary_emotion, valence, arousal, dominance FROM utterance_logs WHERE session_id = ? ORDER BY timestamp ASC """, (session_id,)) rows = [dict(row) for row in cursor.fetchall()] conn.close() return rows except Exception as e: print(f"[ERROR] Failed to fetch session timeline for {session_id}: {e}", flush=True) return [] def get_articles_by_emotion(emotion: str): """Retrieves all articles that generated a specific primary emotion.""" try: conn = sqlite3.connect(DB_FILE) conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(""" SELECT s.article_id, COUNT(u.id) as count FROM sessions s JOIN utterance_logs u ON s.session_id = u.session_id WHERE u.primary_emotion = ? GROUP BY s.article_id ORDER BY count DESC """, (emotion,)) rows = [dict(row) for row in cursor.fetchall()] conn.close() return rows except Exception as e: print(f"[ERROR] Failed to fetch articles by emotion {emotion}: {e}", flush=True) return []