Download models/ensemble.py from devmm03/vs: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/devmm03/vs/resolve/main/models/ensemble.py
- Command line
-
hf download hf://spaces/devmm03/vs/models/ensemble.py
-
curl -L -o ensemble.py https://huggingface.co/spaces/devmm03/vs/resolve/main/models/ensemble.py
10.5 kB
| """ | |
| 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 | |
| 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 | |
| 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"] | |
| ) | |