File size: 10,432 Bytes
92a3517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""
Database and Logging System for NegaBot API
Handles prediction logging using SQLite database
"""
import sqlite3
import json
import logging
from datetime import datetime
from typing import List, Dict

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Database configuration
DB_PATH = "negabot_predictions.db"

class PredictionLogger:
    def __init__(self, db_path: str = DB_PATH):
        """
        Initialize the prediction logger with SQLite database
        
        Args:
            db_path (str): Path to SQLite database file
        """
        self.db_path = db_path
        self.init_database()
    
    def init_database(self):
        """Initialize the database with required tables"""
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                # Create predictions table
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS predictions (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        text TEXT NOT NULL,
                        sentiment TEXT NOT NULL,
                        confidence REAL NOT NULL,
                        predicted_class INTEGER NOT NULL,
                        timestamp TEXT NOT NULL,
                        metadata TEXT,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                """)
                
                # Create index for faster queries
                cursor.execute("""
                    CREATE INDEX IF NOT EXISTS idx_sentiment ON predictions(sentiment)
                """)
                cursor.execute("""
                    CREATE INDEX IF NOT EXISTS idx_timestamp ON predictions(timestamp)
                """)
                
                conn.commit()
                logger.info("Database initialized successfully")
                
        except Exception as e:
            logger.error(f"Error initializing database: {str(e)}")
            raise e
    
    def log_prediction(self, text: str, sentiment: str, confidence: float, 
                      predicted_class: int = None, metadata: Dict = None):
        """
        Log a prediction to the database
        
        Args:
            text (str): Input text
            sentiment (str): Predicted sentiment
            confidence (float): Prediction confidence
            predicted_class (int): Predicted class (0 or 1)
            metadata (dict): Optional metadata
        """
        try:
            # Infer predicted_class if not provided
            if predicted_class is None:
                predicted_class = 1 if sentiment == "Negative" else 0
            
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                cursor.execute("""
                    INSERT INTO predictions (text, sentiment, confidence, predicted_class, timestamp, metadata)
                    VALUES (?, ?, ?, ?, ?, ?)
                """, (
                    text,
                    sentiment,
                    confidence,
                    predicted_class,
                    datetime.now().isoformat(),
                    json.dumps(metadata) if metadata else None
                ))
                
                conn.commit()
                
        except Exception as e:
            logger.error(f"Error logging prediction: {str(e)}")
            raise e
    
    def get_all_predictions(self, limit: int = None) -> List[Dict]:
        """
        Get all predictions from the database
        
        Args:
            limit (int): Maximum number of records to return
            
        Returns:
            List of prediction dictionaries
        """
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                query = """
                    SELECT id, text, sentiment, confidence, predicted_class, timestamp, metadata, created_at
                    FROM predictions 
                    ORDER BY created_at DESC
                """
                
                if limit:
                    query += f" LIMIT {limit}"
                
                cursor.execute(query)
                rows = cursor.fetchall()
                
                predictions = []
                for row in rows:
                    prediction = {
                        "id": row[0],
                        "text": row[1],
                        "sentiment": row[2],
                        "confidence": row[3],
                        "predicted_class": row[4],
                        "timestamp": row[5],
                        "metadata": json.loads(row[6]) if row[6] else None,
                        "created_at": row[7]
                    }
                    predictions.append(prediction)
                
                return predictions
                
        except Exception as e:
            logger.error(f"Error getting predictions: {str(e)}")
            return []
    
    def get_predictions_by_sentiment(self, sentiment: str) -> List[Dict]:
        """
        Get predictions filtered by sentiment
        
        Args:
            sentiment (str): Sentiment to filter by ("Positive" or "Negative")
            
        Returns:
            List of prediction dictionaries
        """
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                cursor.execute("""
                    SELECT id, text, sentiment, confidence, predicted_class, timestamp, metadata, created_at
                    FROM predictions 
                    WHERE sentiment = ?
                    ORDER BY created_at DESC
                """, (sentiment,))
                
                rows = cursor.fetchall()
                
                predictions = []
                for row in rows:
                    prediction = {
                        "id": row[0],
                        "text": row[1],
                        "sentiment": row[2],
                        "confidence": row[3],
                        "predicted_class": row[4],
                        "timestamp": row[5],
                        "metadata": json.loads(row[6]) if row[6] else None,
                        "created_at": row[7]
                    }
                    predictions.append(prediction)
                
                return predictions
                
        except Exception as e:
            logger.error(f"Error getting predictions by sentiment: {str(e)}")
            return []
    
    def get_stats(self) -> Dict:
        """
        Get prediction statistics
        
        Returns:
            Dictionary with statistics
        """
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                # Total count
                cursor.execute("SELECT COUNT(*) FROM predictions")
                total_count = cursor.fetchone()[0]
                
                if total_count == 0:
                    return {
                        "total_predictions": 0,
                        "positive_count": 0,
                        "negative_count": 0,
                        "average_confidence": 0
                    }
                
                # Sentiment counts
                cursor.execute("SELECT sentiment, COUNT(*) FROM predictions GROUP BY sentiment")
                sentiment_counts = dict(cursor.fetchall())
                
                # Average confidence
                cursor.execute("SELECT AVG(confidence) FROM predictions")
                avg_confidence = cursor.fetchone()[0]
                
                return {
                    "total_predictions": total_count,
                    "positive_count": sentiment_counts.get("Positive", 0),
                    "negative_count": sentiment_counts.get("Negative", 0),
                    "average_confidence": round(avg_confidence, 4) if avg_confidence else 0
                }
                
        except Exception as e:
            logger.error(f"Error getting stats: {str(e)}")
            return {}

# Global logger instance
_logger_instance = None

def get_logger():
    """Get the global logger instance"""
    global _logger_instance
    if _logger_instance is None:
        _logger_instance = PredictionLogger()
    return _logger_instance

def log_prediction(text: str, sentiment: str, confidence: float, metadata: Dict = None):
    """Convenience function to log a prediction"""
    logger_instance = get_logger()
    logger_instance.log_prediction(text, sentiment, confidence, metadata=metadata)

def get_all_predictions(limit: int = None) -> List[Dict]:
    """Convenience function to get all predictions"""
    logger_instance = get_logger()
    return logger_instance.get_all_predictions(limit=limit)

def get_predictions_by_sentiment(sentiment: str) -> List[Dict]:
    """Convenience function to get predictions by sentiment"""
    logger_instance = get_logger()
    return logger_instance.get_predictions_by_sentiment(sentiment)

def get_prediction_stats() -> Dict:
    """Convenience function to get prediction statistics"""
    logger_instance = get_logger()
    return logger_instance.get_stats()

if __name__ == "__main__":
    # Test the logging system
    logger_instance = PredictionLogger()
    
    # Test logging
    test_predictions = [
        ("This product is amazing!", "Positive", 0.95),
        ("Terrible quality, waste of money", "Negative", 0.89),
        ("It's okay, nothing special", "Positive", 0.67),
        ("Awful customer service", "Negative", 0.92)
    ]
    
    print("Testing prediction logging...")
    for text, sentiment, confidence in test_predictions:
        logger_instance.log_prediction(text, sentiment, confidence)
        print(f"Logged: {sentiment} - {text}")
    
    # Test retrieval
    print("\nRetrieving all predictions:")
    predictions = logger_instance.get_all_predictions()
    for pred in predictions:
        print(f"ID: {pred['id']}, Sentiment: {pred['sentiment']}, Text: {pred['text'][:50]}...")
    
    # Test stats
    print("\nPrediction statistics:")
    stats = logger_instance.get_stats()
    print(json.dumps(stats, indent=2))