File size: 4,433 Bytes
8a6f58d
 
 
 
 
 
9c21b2b
8a6f58d
 
 
 
 
9c21b2b
 
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c21b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6f58d
 
9c21b2b
8a6f58d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Voice Classifier Module
Loads trained model and makes predictions
"""

import os
import logging
import pickle
import numpy as np
from typing import Tuple, Dict, Any


logger = logging.getLogger(__name__)

class VoiceClassifier:
    """AI Voice Detection Classifier"""
    
    def __init__(self):
        """Initialize classifier and load trained model"""
        self.model = None
        self.scaler = None
        self.load_model()
    
    def load_model(self):
        """Load trained model and scaler"""
        model_dir = os.path.dirname(os.path.abspath(__file__))
        model_path = os.path.join(model_dir, 'voice_classifier.pkl')
        scaler_path = os.path.join(model_dir, 'feature_scaler.pkl')
        
        # Check if model files exist, if not, reconstruct them from embedded strings
        if not os.path.exists(model_path) or not os.path.exists(scaler_path):
            try:
                # Try to import embedded models (generated to bypass git binary limits)
                from model.embedded_models import CLASSIFIER_B64, SCALER_B64
                import base64
                
                if CLASSIFIER_B64:
                    with open(model_path, "wb") as f:
                        f.write(base64.b64decode(CLASSIFIER_B64))
                        
                if SCALER_B64:
                    with open(scaler_path, "wb") as f:
                        f.write(base64.b64decode(SCALER_B64))
            except ImportError:
                # If embedded models are not found (e.g. strict training requirement)
                logger.warning("Embedded models not found, checking for file existence...")
            except Exception as e:
                logger.error(f"Failed to reconstitute models: {e}")

        if not os.path.exists(model_path) or not os.path.exists(scaler_path):
            raise FileNotFoundError(
                "Model files not found and could not be reconstituted. Please run train_model.py first."
            )
        
        with open(model_path, 'rb') as f:
            self.model = pickle.load(f)
        
        with open(scaler_path, 'rb') as f:
            self.scaler = pickle.load(f)
    
    def predict(self, feature_vector: np.ndarray) -> Tuple[str, float, np.ndarray]:
        """
        Make prediction on feature vector
        
        Args:
            feature_vector: Audio features (1D array)
            
        Returns:
            tuple: (prediction, confidence, probabilities)
                - prediction: "AI_GENERATED" or "HUMAN"
                - confidence: float between 0 and 1
                - probabilities: array of class probabilities
        """
        # Reshape if needed
        if feature_vector.ndim == 1:
            feature_vector = feature_vector.reshape(1, -1)
        
        # Scale features
        feature_scaled = self.scaler.transform(feature_vector)
        
        # Get prediction
        prediction_label = self.model.predict(feature_scaled)[0]
        
        # Get probabilities
        probabilities = self.model.predict_proba(feature_scaled)[0]
        
        # Convert to human-readable format
        if prediction_label == 0:
            prediction = "AI_GENERATED"
            confidence = probabilities[0]
        else:
            prediction = "HUMAN"
            confidence = probabilities[1]
        
        return prediction, float(confidence), probabilities
    
    def get_feature_importance(self) -> Dict[str, float]:
        """
        Get feature importance from model
        
        Returns:
            dict: Feature names and their importance scores
        """
        feature_names = [
            'mfcc_mean', 'mfcc_std', 'mfcc_var', 'mfcc_max', 'mfcc_min',
            'pitch_mean', 'pitch_std', 'pitch_variance', 'pitch_range',
            'spectral_flatness_mean', 'spectral_flatness_std',
            'spectral_centroid_mean', 'spectral_centroid_std',
            'spectral_rolloff_mean', 'spectral_bandwidth_mean',
            'rms_mean', 'rms_std', 'rms_variance',
            'zcr_mean', 'zcr_std',
            'energy_variation', 'audio_duration'
        ]
        
        importance_dict = dict(zip(feature_names, self.model.feature_importances_))
        
        # Sort by importance
        sorted_importance = dict(
            sorted(importance_dict.items(), key=lambda x: x[1], reverse=True)
        )
        
        return sorted_importance