File size: 22,523 Bytes
8a6f58d
c50afc1
 
8a6f58d
 
 
 
 
 
c50afc1
 
 
8a6f58d
 
 
 
c50afc1
 
8a6f58d
c50afc1
8a6f58d
c50afc1
8a6f58d
 
c50afc1
8a6f58d
c50afc1
8a6f58d
c50afc1
8a6f58d
 
c50afc1
8a6f58d
79b79ac
 
c50afc1
 
79b79ac
 
 
0bbc893
 
 
 
c50afc1
ffc0c1b
c50afc1
ffc0c1b
 
0bbc893
ffc0c1b
 
 
 
 
 
 
 
 
 
0bbc893
ffc0c1b
3c88611
 
c50afc1
3f04b3e
 
 
30a2584
25e31b1
 
 
 
30a2584
 
 
 
25e31b1
 
 
 
30a2584
 
25e31b1
 
 
 
 
 
 
 
 
30a2584
3f04b3e
ffc0c1b
c50afc1
 
ffc0c1b
 
 
 
79b79ac
 
 
 
 
 
 
ffc0c1b
 
79b79ac
c50afc1
 
 
 
 
 
 
 
 
79b79ac
 
 
 
 
 
c50afc1
79b79ac
 
 
 
8a6f58d
c50afc1
 
 
 
8a6f58d
c50afc1
8a6f58d
 
 
c50afc1
 
 
79b79ac
 
 
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
c50afc1
8a6f58d
 
c50afc1
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
c50afc1
 
 
 
8a6f58d
c50afc1
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
c50afc1
 
 
8a6f58d
c50afc1
 
 
 
8a6f58d
c50afc1
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
 
 
8a6f58d
c50afc1
 
 
 
8a6f58d
c50afc1
8a6f58d
 
 
 
 
c50afc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
 
 
c50afc1
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
c50afc1
 
8a6f58d
c50afc1
 
8a6f58d
 
 
 
 
c50afc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
 
c50afc1
 
 
 
 
 
 
 
 
 
 
8a6f58d
c50afc1
8a6f58d
c50afc1
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
 
c50afc1
 
 
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
c50afc1
 
 
 
 
 
 
 
 
 
 
 
8a6f58d
c50afc1
 
 
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
c50afc1
 
 
8a6f58d
c50afc1
 
 
 
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c50afc1
8a6f58d
 
c50afc1
 
8a6f58d
 
 
c50afc1
 
 
8a6f58d
 
 
 
 
 
 
 
 
 
c50afc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6f58d
 
c50afc1
 
 
 
8a6f58d
 
c50afc1
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
"""
Firebase Firestore Integration Module
Handles database connections and operations using Firebase
"""

import os
from datetime import datetime
from typing import Dict, Any, Optional
import logging
import firebase_admin
from firebase_admin import credentials, firestore
from google.cloud.firestore_v1.base_query import FieldFilter

logger = logging.getLogger(__name__)


class FirebaseManager:
    """Manage Firebase Firestore connections and operations"""
    
    def __init__(self, credentials_path: Optional[str] = None):
        """
        Initialize Firebase manager
        
        Args:
            credentials_path: Path to Firebase credentials JSON file
        """
        self.credentials_path = credentials_path or os.getenv('FIREBASE_CREDENTIALS_PATH', 'firebase-credentials.json')
        self.db = None
        self.app = None
        
    def connect(self):
        """Establish connection to Firebase Firestore"""
        try:
            # Robust initialization pattern: Try to get app, if fails, initialize it.
            try:
                self.app = firebase_admin.get_app()
                logger.info("Using existing Firebase app")
            except ValueError:
                # App not returned by get_app(), try to initialize
                
                # Debug logging to see what's actually available
                env_keys = [k for k in os.environ.keys() if k.startswith('FIREBASE_')]
                logger.info(f"Available FIREBASE env vars: {env_keys}")

                json_creds = os.getenv('FIREBASE_CREDENTIALS_JSON')
                b64_creds = os.getenv('FIREBASE_CREDENTIALS_BASE64')
                
                cred_dict = None
                
                if b64_creds and b64_creds.strip():
                    # Robust Base64 decoding
                    import base64
                    import json
                    try:
                        json_str = base64.b64decode(b64_creds).decode('utf-8')
                        cred_dict = json.loads(json_str)
                        logger.info("Loaded credentials from FIREBASE_CREDENTIALS_BASE64")
                    except Exception as e:
                        logger.error(f"Failed to decode base64 credentials: {e}")

                if not cred_dict and json_creds and json_creds.strip():
                    # Fallback to JSON parsing with aggressive cleaning
                    import json
                    try:
                        cred_dict = json.loads(json_creds)
                        
                        # Fix potential newline escaping issues in private key
                        if 'private_key' in cred_dict:
                            key = cred_dict['private_key']
                            
                            # Clean up the key string
                            key = key.strip()
                            
                            # Remove surrounding quotes if accidentally included
                            if key.startswith('"') and key.endswith('"'):
                                key = key[1:-1]
                            
                            # Replace escaped newlines (handle multiple levels)
                            # First handle double escaping
                            key = key.replace('\\\\n', '\n')
                            # Then handle standard JSON escaping
                            key = key.replace('\\n', '\n')
                            
                            # Ensure headers are correct
                            if '-----BEGIN PRIVATE KEY-----' in key:
                                # Ensure strict formatting if it looks like a PEM
                                parts = key.split('-----BEGIN PRIVATE KEY-----')
                                if len(parts) > 1:
                                    content = parts[1].split('-----END PRIVATE KEY-----')[0]
                                    content = content.replace(' ', '\n') # Fix spaces that should be newlines
                                    key = f"-----BEGIN PRIVATE KEY-----\n{content.strip()}\n-----END PRIVATE KEY-----\n"

                            cred_dict['private_key'] = key
                            
                        logger.info("Loaded Firebase credentials from FIREBASE_CREDENTIALS_JSON")
                    except json.JSONDecodeError as e:
                        logger.error(f"Failed to parse FIREBASE_CREDENTIALS_JSON: {e}")

                if cred_dict:
                    try:
                        cred = credentials.Certificate(cred_dict)
                        # Try to initialize, but handle race conditions where it might have just been created
                        try:
                            self.app = firebase_admin.initialize_app(cred)
                            logger.info("Initialized new Firebase app")
                        except ValueError:
                             self.app = firebase_admin.get_app()
                             logger.info("Using existing Firebase app (caught race condition)")
                    except Exception as e:
                        logger.error(f"Failed to initialize Firebase app with credentials: {e}")
                        return False
                else:
                    # Load from file (local development)
                    cred_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), self.credentials_path)
                    
                    if not os.path.exists(cred_path):
                        logger.error(f"Firebase credentials file not found at: {cred_path}")
                        return False
                    
                    cred = credentials.Certificate(cred_path)
                    try:
                        self.app = firebase_admin.initialize_app(cred)
                        logger.info(f"Loaded Firebase credentials from file: {self.credentials_path}")
                    except ValueError:
                        self.app = firebase_admin.get_app()
                        logger.info("Using existing Firebase app (local)")

            # Get Firestore client explicitly using the app we have
            logger.info("Getting Firestore client...")
            self.db = firestore.client(app=self.app)
            logger.info("Firestore client created")
            
            # Test connection by attempting to read from a collection
            # This will create the collection if it doesn't exist
            test_ref = self.db.collection('_connection_test').document('test')
            test_ref.set({'timestamp': datetime.utcnow()}, merge=True)
            
            logger.info("Successfully connected to Firebase Firestore")
            return True
            
        except Exception as e:
            logger.warning(f"Failed to connect to Firebase: {str(e)}")
            logger.warning("Server will continue without database connection")
            return False
            
        except Exception as e:
            logger.warning(f"Failed to connect to Firebase: {str(e)}")
            logger.warning("Server will continue without database connection")
            return False
    
    # ============ USER MANAGEMENT METHODS ============
    
    def create_user(self, email: str, password_hash: str, api_key: str) -> Optional[str]:
        """
        Create a new user
        
        Args:
            email: User email
            password_hash: Hashed password
            api_key: Generated API key
            
        Returns:
            str: User ID or None if failed
        """
        if self.db is None:
            logger.warning("Database not connected")
            raise Exception("Database not connected")
        
        try:
            users_ref = self.db.collection('users')
            
            # Check if user exists
            existing = users_ref.where(filter=FieldFilter('email', '==', email)).limit(1).get()
            if len(list(existing)) > 0:
                logger.warning(f"User already exists: {email}")
                return None
            
            user_doc = {
                'email': email,
                'password_hash': password_hash,
                'api_key': api_key,
                'created_at': datetime.utcnow(),
                'total_requests': 0
            }
            
            # Add user document
            doc_ref = users_ref.add(user_doc)
            user_id = doc_ref[1].id
            
            logger.info(f"Created user: {email}")
            return user_id
            
        except Exception as e:
            logger.error(f"Failed to create user: {str(e)}")
            return None
    
    def get_user_by_email(self, email: str) -> Optional[Dict[str, Any]]:
        """
        Get user by email
        
        Args:
            email: User email
            
        Returns:
            dict: User document or None
        """
        if self.db is None:
            raise Exception("Database not connected")
        
        try:
            users_ref = self.db.collection('users')
            query = users_ref.where(filter=FieldFilter('email', '==', email)).limit(1)
            results = query.get()
            
            for doc in results:
                user = doc.to_dict()
                user['_id'] = doc.id
                return user
            
            return None
            
        except Exception as e:
            logger.error(f"Failed to get user: {str(e)}")
            return None
    
    def get_user_by_api_key(self, api_key: str) -> Optional[Dict[str, Any]]:
        """
        Get user by API key
        
        Args:
            api_key: User's API key
            
        Returns:
            dict: User document or None
        """
        if self.db is None:
            return None
        
        try:
            users_ref = self.db.collection('users')
            query = users_ref.where(filter=FieldFilter('api_key', '==', api_key)).limit(1)
            results = query.get()
            
            for doc in results:
                user = doc.to_dict()
                user['_id'] = doc.id
                return user
            
            return None
            
        except Exception as e:
            logger.error(f"Failed to get user by API key: {str(e)}")
            return None
    
    # ============ PREDICTION LOGGING METHODS ============
    
    def log_prediction(
        self,
        prediction: str,
        confidence: float,
        features: Dict[str, float],
        explanation: Dict[str, str],
        metadata: Optional[Dict[str, Any]] = None
    ) -> Optional[str]:
        """
        Log prediction to database
        
        Args:
            prediction: Prediction result (AI_GENERATED or HUMAN)
            confidence: Confidence score
            features: Extracted features
            explanation: Explanation dictionary
            metadata: Additional metadata
            
        Returns:
            str: Inserted document ID or None if failed
        """
        if self.db is None:
            logger.warning("Database not connected, skipping logging")
            return None
        
        try:
            predictions_ref = self.db.collection('predictions')
            
            document = {
                'timestamp': datetime.utcnow(),
                'prediction': prediction,
                'confidence': confidence,
                'explanation': explanation,
                'features': features,
                'metadata': metadata or {}
            }
            
            doc_ref = predictions_ref.add(document)
            doc_id = doc_ref[1].id
            
            logger.info(f"Logged prediction with ID: {doc_id}")
            return doc_id
            
        except Exception as e:
            logger.error(f"Failed to log prediction: {str(e)}")
            return None
    
    def log_user_prediction(
        self,
        user_email: str,
        filename: str,
        prediction: str,
        confidence: float,
        features: Dict[str, float],
        explanation: Dict[str, str],
        metadata: Optional[Dict[str, Any]] = None
    ) -> Optional[str]:
        """
        Log prediction with user information
        
        Args:
            user_email: User's email
            filename: Audio filename
            prediction: Prediction result
            confidence: Confidence score
            features: Extracted features
            explanation: Explanation dictionary
            metadata: Additional metadata
            
        Returns:
            str: Inserted document ID or None
        """
        if self.db is None:
            logger.warning("Database not connected, skipping logging")
            return None
        
        try:
            predictions_ref = self.db.collection('predictions')
            
            document = {
                'user_email': user_email,
                'filename': filename,
                'timestamp': datetime.utcnow(),
                'prediction': prediction,
                'confidence': confidence,
                'explanation': explanation,
                'features': features,
                'metadata': metadata or {}
            }
            
            doc_ref = predictions_ref.add(document)
            doc_id = doc_ref[1].id
            
            logger.info(f"Logged prediction for user: {user_email}")
            return doc_id
            
        except Exception as e:
            logger.error(f"Failed to log prediction: {str(e)}")
            return None
    
    # ============ STATISTICS METHODS ============
    
    def get_statistics(self) -> Dict[str, Any]:
        """
        Get prediction statistics
        
        Returns:
            dict: Statistics summary
        """
        if self.db is None:
            return {}
        
        try:
            predictions_ref = self.db.collection('predictions')
            all_predictions = predictions_ref.get()
            
            total = 0
            ai_count = 0
            human_count = 0
            total_confidence = 0
            
            for doc in all_predictions:
                data = doc.to_dict()
                total += 1
                if data.get('prediction') == 'AI_GENERATED':
                    ai_count += 1
                else:
                    human_count += 1
                total_confidence += data.get('confidence', 0)
            
            avg_confidence = total_confidence / total if total > 0 else 0
            
            return {
                'total_predictions': total,
                'ai_generated_count': ai_count,
                'human_count': human_count,
                'average_confidence': round(avg_confidence, 3)
            }
            
        except Exception as e:
            logger.error(f"Failed to get statistics: {str(e)}")
            return {}
    
    def get_user_history(self, user_email: str, limit: int = 50) -> list:
        """
        Get prediction history for a user
        
        Args:
            user_email: User's email
            limit: Maximum number of records
            
        Returns:
            list: Prediction history
        """
        if self.db is None:
            return []
        
        try:
            predictions_ref = self.db.collection('predictions')
            query = predictions_ref.where(filter=FieldFilter('user_email', '==', user_email)) \
                                  .order_by('timestamp', direction=firestore.Query.DESCENDING) \
                                  .limit(limit)
            
            results = query.get()
            predictions = []
            
            for doc in results:
                pred = doc.to_dict()
                pred['_id'] = doc.id
                # Format timestamp for display
                if 'timestamp' in pred and pred['timestamp']:
                    pred['timestamp_formatted'] = pred['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
                predictions.append(pred)
            
            return predictions
            
        except Exception as e:
            logger.error(f"Failed to get user history: {str(e)}")
            return []
    
    def get_user_stats(self, user_email: str) -> Dict[str, Any]:
        """
        Get statistics for a specific user
        
        Args:
            user_email: User's email
            
        Returns:
            dict: User statistics
        """
        if self.db is None:
            return {}
        
        try:
            predictions_ref = self.db.collection('predictions')
            query = predictions_ref.where(filter=FieldFilter('user_email', '==', user_email))
            results = list(query.get())
            
            total = len(results)
            
            if total == 0:
                return {
                    'total_tests': 0,
                    'ai_count': 0,
                    'human_count': 0,
                    'avg_confidence': 0,
                    'last_prediction': None,
                    'trend': 'No data'
                }
            
            ai_count = 0
            human_count = 0
            total_confidence = 0
            last_pred = None
            
            for doc in results:
                data = doc.to_dict()
                if data.get('prediction') == 'AI_GENERATED':
                    ai_count += 1
                else:
                    human_count += 1
                total_confidence += data.get('confidence', 0)
                
                # Track most recent
                if last_pred is None or data.get('timestamp', datetime.min) > last_pred.get('timestamp', datetime.min):
                    last_pred = data
            
            avg_confidence = total_confidence / total if total > 0 else 0
            
            return {
                'total_tests': total,
                'ai_count': ai_count,
                'human_count': human_count,
                'avg_confidence': round(avg_confidence, 3),
                'last_prediction': {
                    'prediction': last_pred['prediction'],
                    'confidence': last_pred['confidence'],
                    'timestamp': last_pred['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
                } if last_pred else None,
                'trend': 'Stable'
            }
            
        except Exception as e:
            logger.error(f"Failed to get user stats: {str(e)}")
            return {}
    
    # ============ API USAGE TRACKING METHODS ============
    
    def log_api_usage(self, user_email: str, endpoint: str, status: str = "success") -> Optional[str]:
        """
        Log API usage
        
        Args:
            user_email: User's email
            endpoint: API endpoint called
            status: Request status (success/error)
            
        Returns:
            str: Log ID or None
        """
        if self.db is None:
            return None
        
        try:
            usage_ref = self.db.collection('api_usage_logs')
            
            log_doc = {
                'user_email': user_email,
                'endpoint': endpoint,
                'status': status,
                'timestamp': datetime.utcnow()
            }
            
            doc_ref = usage_ref.add(log_doc)
            
            # Update user's total request count
            users_ref = self.db.collection('users')
            query = users_ref.where(filter=FieldFilter('email', '==', user_email)).limit(1)
            results = query.get()
            
            for doc in results:
                doc.reference.update({
                    'total_requests': firestore.Increment(1)
                })
            
            return doc_ref[1].id
            
        except Exception as e:
            logger.error(f"Failed to log API usage: {str(e)}")
            return None
    
    def get_usage_stats(self, user_email: str) -> Dict[str, int]:
        """
        Get API usage statistics for a user
        
        Args:
            user_email: User's email
            
        Returns:
            dict: Usage statistics
        """
        if self.db is None:
            return {'requests_today': 0, 'total_requests': 0}
        
        try:
            usage_ref = self.db.collection('api_usage_logs')
            
            # Total requests
            total_query = usage_ref.where(filter=FieldFilter('user_email', '==', user_email))
            total = len(list(total_query.get()))
            
            # Requests today
            today_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
            today_query = usage_ref.where(filter=FieldFilter('user_email', '==', user_email)) \
                                   .where(filter=FieldFilter('timestamp', '>=', today_start))
            today_count = len(list(today_query.get()))
            
            return {
                'requests_today': today_count,
                'total_requests': total
            }
            
        except Exception as e:
            logger.error(f"Failed to get usage stats: {str(e)}")
            return {'requests_today': 0, 'total_requests': 0}
    
    def get_recent_predictions(self, limit: int = 10) -> list:
        """
        Get recent predictions
        
        Args:
            limit: Number of predictions to retrieve
            
        Returns:
            list: Recent prediction documents
        """
        if self.db is None:
            return []
        
        try:
            predictions_ref = self.db.collection('predictions')
            query = predictions_ref.order_by('timestamp', direction=firestore.Query.DESCENDING).limit(limit)
            results = query.get()
            
            predictions = []
            for doc in results:
                pred = doc.to_dict()
                pred['_id'] = doc.id
                predictions.append(pred)
            
            return predictions
            
        except Exception as e:
            logger.error(f"Failed to retrieve predictions: {str(e)}")
            return []
    
    def close(self):
        """Close database connection"""
        if self.app:
            # Firebase Admin SDK doesn't require explicit closing
            # but we can delete the app if needed
            logger.info("Firebase connection closed")


# Global Firebase instance
firebase_db_manager = FirebaseManager()