File size: 10,528 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
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
"""
Ensemble Classifier
Combines traditional ML and CNN approaches for robust detection.
"""
import numpy as np
from pathlib import Path
from typing import Dict, Tuple, Optional, Union
import json

import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import ENSEMBLE_WEIGHTS, MODELS_DIR, AI_DETECTION_THRESHOLD
from models.traditional import FeatureBasedClassifier
from models.cnn import CNNClassifier
from features.spectral import extract_spectral_features
from features.mfcc import extract_mfcc_features, prepare_spectrogram_for_cnn
from features.prosody import extract_prosodic_features


class EnsembleClassifier:
    """
    Ensemble classifier combining traditional ML and deep learning.
    
    Combines predictions from:
    - Feature-based classifier (SVM/Random Forest)
    - CNN classifier (spectrogram-based)
    
    Weighted averaging produces the final prediction.
    """
    
    def __init__(
        self,
        traditional_model: Optional[FeatureBasedClassifier] = None,
        cnn_model: Optional[CNNClassifier] = None,
        weights: Optional[Dict[str, float]] = None,
        threshold: float = AI_DETECTION_THRESHOLD
    ):
        """
        Initialize the ensemble classifier.
        
        Args:
            traditional_model: Pre-trained feature-based classifier
            cnn_model: Pre-trained CNN classifier
            weights: Weight dict {'traditional': w1, 'cnn': w2}
            threshold: Threshold for AI classification
        """
        self.traditional_model = traditional_model
        self.cnn_model = cnn_model
        self.weights = weights or ENSEMBLE_WEIGHTS
        self.threshold = threshold
        
        # Normalize weights
        total = self.weights["traditional"] + self.weights["cnn"]
        self.weights["traditional"] /= total
        self.weights["cnn"] /= total
    
    @property
    def is_ready(self) -> bool:
        """Check if at least one model is available."""
        trad_ready = self.traditional_model is not None and self.traditional_model.is_fitted
        cnn_ready = self.cnn_model is not None and self.cnn_model.is_fitted
        return trad_ready or cnn_ready
    
    def analyze(
        self,
        audio: np.ndarray,
        sr: int
    ) -> Dict:
        """
        Analyze audio and return detailed results.
        
        Args:
            audio: Audio waveform
            sr: Sample rate
            
        Returns:
            Dictionary with classification results and analysis
        """
        results = {
            "classification": "HUMAN",
            "confidence_score": 0.5,
            "traditional_score": None,
            "cnn_score": None,
            "features": {},
            "explanation_parts": []
        }
        
        # Extract features
        spectral = extract_spectral_features(audio, sr)
        mfcc = extract_mfcc_features(audio, sr)
        prosody = extract_prosodic_features(audio, sr)
        
        results["features"] = {
            "spectral": spectral,
            "mfcc": {k: v for k, v in mfcc.items() if "mfcc_0" in k or "energy" in k},
            "prosody": prosody
        }
        
        scores = []
        weights_used = []
        
        # Traditional model prediction
        if self.traditional_model is not None and self.traditional_model.is_fitted:
            try:
                feature_vector = np.concatenate([
                    np.array(list(spectral.values())),
                    np.array(list(mfcc.values())),
                    np.array(list(prosody.values()))
                ])
                _, trad_prob = self.traditional_model.predict_single(feature_vector)
                results["traditional_score"] = trad_prob
                scores.append(trad_prob)
                weights_used.append(self.weights["traditional"])
                
                # Add explanation based on features
                self._add_traditional_explanation(results, spectral, prosody, trad_prob)
            except Exception as e:
                results["traditional_error"] = str(e)
        
        # CNN model prediction
        if self.cnn_model is not None and self.cnn_model.is_fitted:
            try:
                spectrogram = prepare_spectrogram_for_cnn(audio, sr)
                _, cnn_prob = self.cnn_model.predict_single(spectrogram)
                results["cnn_score"] = cnn_prob
                scores.append(cnn_prob)
                weights_used.append(self.weights["cnn"])
                
                self._add_cnn_explanation(results, cnn_prob)
            except Exception as e:
                results["cnn_error"] = str(e)
        
        # Combine scores
        if scores:
            # Normalize weights for available models
            total_weight = sum(weights_used)
            normalized_weights = [w / total_weight for w in weights_used]
            
            final_score = sum(s * w for s, w in zip(scores, normalized_weights))
            results["confidence_score"] = float(final_score)
            results["classification"] = "AI_GENERATED" if final_score >= self.threshold else "HUMAN"
        
        # Generate final explanation
        results["explanation"] = self._generate_explanation(results)
        
        return results
    
    def _add_traditional_explanation(
        self,
        results: Dict,
        spectral: Dict,
        prosody: Dict,
        score: float
    ):
        """Add explanations based on traditional feature analysis."""
        explanations = results["explanation_parts"]
        
        # Check jitter (low jitter often indicates AI)
        jitter = prosody.get("jitter_local", 0)
        if jitter < 0.01:
            explanations.append(f"Very low pitch variation (jitter={jitter:.4f})")
        elif jitter > 0.05:
            explanations.append(f"Natural pitch micro-variations detected")
        
        # Check F0 coefficient of variation
        f0_cv = prosody.get("f0_cv", 0)
        if f0_cv < 0.1:
            explanations.append("Unnaturally stable pitch contour")
        
        # Check spectral characteristics
        centroid_cv = spectral.get("centroid_cv", 0)
        if centroid_cv < 0.1:
            explanations.append("Spectral consistency suggests synthesized audio")
        
        # Check rolloff patterns
        rolloff_std = spectral.get("rolloff_std", 0)
        if rolloff_std < 500:
            explanations.append("Sharp frequency cutoff pattern detected")
    
    def _add_cnn_explanation(self, results: Dict, score: float):
        """Add explanations based on CNN analysis."""
        if score > 0.8:
            results["explanation_parts"].append(
                "Spectrogram patterns strongly match AI voice signatures"
            )
        elif score > 0.6:
            results["explanation_parts"].append(
                "Some AI-like patterns detected in spectrogram"
            )
    
    def _generate_explanation(self, results: Dict) -> str:
        """Generate human-readable explanation."""
        parts = results["explanation_parts"]
        score = results["confidence_score"]
        classification = results["classification"]
        
        if not parts:
            if classification == "AI_GENERATED":
                return f"Audio shows characteristics of AI-generated speech (confidence: {score:.0%})"
            else:
                return f"Audio appears to be natural human speech (confidence: {1-score:.0%})"
        
        intro = f"Analysis indicates {'AI-generated' if classification == 'AI_GENERATED' else 'human'} voice. "
        details = " ".join(parts[:3])  # Limit to 3 explanations
        
        return intro + details
    
    def predict_simple(
        self,
        audio: np.ndarray,
        sr: int
    ) -> Tuple[str, float]:
        """
        Simple prediction returning just classification and confidence.
        
        Args:
            audio: Audio waveform
            sr: Sample rate
            
        Returns:
            Tuple of (classification, confidence)
        """
        results = self.analyze(audio, sr)
        return results["classification"], results["confidence_score"]
    
    def save(self, directory: Optional[Union[str, Path]] = None) -> Path:
        """
        Save the ensemble model.
        
        Args:
            directory: Save directory
            
        Returns:
            Directory where models were saved
        """
        if directory is None:
            directory = MODELS_DIR / "ensemble"
        
        directory = Path(directory)
        directory.mkdir(parents=True, exist_ok=True)
        
        # Save traditional model
        if self.traditional_model is not None:
            self.traditional_model.save(directory / "traditional.pkl")
        
        # Save CNN model
        if self.cnn_model is not None:
            self.cnn_model.save(directory / "cnn.pth")
        
        # Save config
        config = {
            "weights": self.weights,
            "threshold": self.threshold,
            "has_traditional": self.traditional_model is not None,
            "has_cnn": self.cnn_model is not None
        }
        with open(directory / "config.json", "w") as f:
            json.dump(config, f)
        
        return directory
    
    @classmethod
    def load(
        cls,
        directory: Union[str, Path],
        device: Optional[str] = None
    ) -> "EnsembleClassifier":
        """
        Load an ensemble model.
        
        Args:
            directory: Directory containing saved models
            device: Device for CNN
            
        Returns:
            Loaded ensemble classifier
        """
        directory = Path(directory)
        
        # Load config
        with open(directory / "config.json", "r") as f:
            config = json.load(f)
        
        traditional_model = None
        cnn_model = None
        
        # Load traditional model
        if config["has_traditional"] and (directory / "traditional.pkl").exists():
            traditional_model = FeatureBasedClassifier.load(directory / "traditional.pkl")
        
        # Load CNN model
        if config["has_cnn"] and (directory / "cnn.pth").exists():
            cnn_model = CNNClassifier.load(directory / "cnn.pth", device=device)
        
        return cls(
            traditional_model=traditional_model,
            cnn_model=cnn_model,
            weights=config["weights"],
            threshold=config["threshold"]
        )