Spaces:
Sleeping

File size: 6,883 Bytes
607968c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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 []