File size: 6,305 Bytes
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Traditional ML Classifiers
Feature-based classification using SVM and Random Forest.
Best for interpretability - can explain WHY a voice is flagged as AI.
"""
import numpy as np
import pickle
from pathlib import Path
from typing import Dict, Tuple, Optional, Union, List
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import SVM_KERNEL, RF_N_ESTIMATORS, MODELS_DIR


class FeatureBasedClassifier:
    """
    Traditional ML classifier for AI voice detection.
    
    Uses extracted features (spectral, MFCC, prosodic) as input.
    Supports SVM and Random Forest classifiers.
    """
    
    def __init__(
        self,
        classifier_type: str = "random_forest",
        **kwargs
    ):
        """
        Initialize the classifier.
        
        Args:
            classifier_type: 'svm' or 'random_forest'
            **kwargs: Additional classifier parameters
        """
        self.classifier_type = classifier_type
        self.scaler = StandardScaler()
        self.is_fitted = False
        
        if classifier_type == "svm":
            self.classifier = SVC(
                kernel=kwargs.get("kernel", SVM_KERNEL),
                probability=True,
                C=kwargs.get("C", 1.0),
                gamma=kwargs.get("gamma", "scale"),
                random_state=42
            )
        elif classifier_type == "random_forest":
            self.classifier = RandomForestClassifier(
                n_estimators=kwargs.get("n_estimators", RF_N_ESTIMATORS),
                max_depth=kwargs.get("max_depth", None),
                min_samples_split=kwargs.get("min_samples_split", 2),
                random_state=42,
                n_jobs=-1
            )
        else:
            raise ValueError(f"Unknown classifier type: {classifier_type}")
        
        # Create pipeline
        self.pipeline = Pipeline([
            ("scaler", self.scaler),
            ("classifier", self.classifier)
        ])
    
    def fit(
        self,
        features: np.ndarray,
        labels: np.ndarray
    ) -> "FeatureBasedClassifier":
        """
        Train the classifier.
        
        Args:
            features: Feature matrix (n_samples, n_features)
            labels: Binary labels (0=human, 1=AI)
            
        Returns:
            Self
        """
        self.pipeline.fit(features, labels)
        self.is_fitted = True
        return self
    
    def predict(
        self,
        features: np.ndarray
    ) -> Tuple[np.ndarray, np.ndarray]:
        """
        Predict labels and probabilities.
        
        Args:
            features: Feature matrix (n_samples, n_features)
            
        Returns:
            Tuple of (predictions, probabilities)
        """
        if not self.is_fitted:
            raise RuntimeError("Classifier not fitted. Call fit() first.")
        
        predictions = self.pipeline.predict(features)
        probabilities = self.pipeline.predict_proba(features)[:, 1]  # P(AI)
        
        return predictions, probabilities
    
    def predict_single(
        self,
        features: np.ndarray
    ) -> Tuple[int, float]:
        """
        Predict for a single sample.
        
        Args:
            features: Feature vector (n_features,)
            
        Returns:
            Tuple of (prediction, probability)
        """
        features_2d = features.reshape(1, -1)
        predictions, probabilities = self.predict(features_2d)
        return int(predictions[0]), float(probabilities[0])
    
    def get_feature_importance(self) -> Optional[Dict[str, float]]:
        """
        Get feature importance (only for Random Forest).
        
        Returns:
            Dictionary mapping feature index to importance,
            or None if not applicable
        """
        if self.classifier_type != "random_forest":
            return None
        
        if not self.is_fitted:
            return None
        
        importances = self.classifier.feature_importances_
        return {f"feature_{i}": float(imp) for i, imp in enumerate(importances)}
    
    def save(self, path: Optional[Union[str, Path]] = None) -> Path:
        """
        Save the trained model.
        
        Args:
            path: Optional save path
            
        Returns:
            Path where model was saved
        """
        if path is None:
            path = MODELS_DIR / f"traditional_{self.classifier_type}.pkl"
        
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(path, "wb") as f:
            pickle.dump({
                "classifier_type": self.classifier_type,
                "pipeline": self.pipeline,
                "is_fitted": self.is_fitted
            }, f)
        
        return path
    
    @classmethod
    def load(cls, path: Union[str, Path]) -> "FeatureBasedClassifier":
        """
        Load a trained model.
        
        Args:
            path: Path to saved model
            
        Returns:
            Loaded classifier
        """
        with open(path, "rb") as f:
            data = pickle.load(f)
        
        instance = cls(classifier_type=data["classifier_type"])
        instance.pipeline = data["pipeline"]
        instance.scaler = data["pipeline"].named_steps["scaler"]
        instance.classifier = data["pipeline"].named_steps["classifier"]
        instance.is_fitted = data["is_fitted"]
        
        return instance


def create_feature_vector(
    spectral_features: Dict[str, float],
    mfcc_features: Dict[str, float],
    prosodic_features: Dict[str, float]
) -> np.ndarray:
    """
    Combine all features into a single vector.
    
    Args:
        spectral_features: From spectral extraction
        mfcc_features: From MFCC extraction
        prosodic_features: From prosodic extraction
        
    Returns:
        Combined feature vector
    """
    all_features = {}
    all_features.update(spectral_features)
    all_features.update(mfcc_features)
    all_features.update(prosodic_features)
    
    return np.array(list(all_features.values()))