vs / api /detector.py
devmm03's picture
intial commit
0468ff5
Raw History Blame Contribute Delete
15.5 kB
"""
VocalSense Voice Detection Service
Hybrid detection using trained model + heuristics for better generalization.
"""
import numpy as np
from pathlib import Path
from typing import Dict, Optional, Union
import logging
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import SAMPLE_RATE, SUPPORTED_LANGUAGES, AI_DETECTION_THRESHOLD, MODELS_DIR
from utils.audio import load_audio, decode_base64_audio, preprocess_audio, segment_audio
from features.spectral import extract_spectral_features
from features.mfcc import extract_mfcc_features
from features.prosody import extract_prosodic_features
logger = logging.getLogger(__name__)
class VoiceDetector:
"""
Hybrid voice detection service.
Combines trained ML model with heuristic rules for better generalization.
"""
def __init__(
self,
model_path: Optional[Path] = None,
threshold: float = AI_DETECTION_THRESHOLD
):
"""
Initialize the detector.
Args:
model_path: Path to trained model (auto-loads if not specified)
threshold: Threshold for AI classification
"""
self.threshold = threshold
self.model = None
self._load_model(model_path)
def _load_model(self, model_path: Optional[Path] = None):
"""Load the trained model."""
if model_path is None:
model_path = MODELS_DIR / "traditional_random_forest.pkl"
if model_path.exists():
try:
from models.traditional import FeatureBasedClassifier
self.model = FeatureBasedClassifier.load(model_path)
logger.info(f"Loaded trained model from {model_path}")
print(f"[OK] Loaded trained model: {model_path.name}")
except Exception as e:
logger.warning(f"Could not load model: {e}")
self.model = None
else:
self.model = None
def _extract_features(self, audio: np.ndarray, sr: int) -> np.ndarray:
"""Extract all features from audio."""
spectral = extract_spectral_features(audio, sr)
mfcc = extract_mfcc_features(audio, sr)
prosody = extract_prosodic_features(audio, sr)
all_features = {}
all_features.update(spectral)
all_features.update(mfcc)
all_features.update(prosody)
return np.array(list(all_features.values()))
def _compute_heuristic_score(self, audio: np.ndarray, sr: int) -> Dict:
"""
Compute AI detection score using proven heuristics.
These work well on unseen data because they're based on research.
"""
spectral = extract_spectral_features(audio, sr)
mfcc = extract_mfcc_features(audio, sr)
prosody = extract_prosodic_features(audio, sr)
ai_score = 0.0
human_score = 0.0
reasons = []
# 1. Jitter (pitch micro-variations) - AI has less
jitter = prosody.get("jitter_local", 0.01)
if jitter < 0.005:
ai_score += 0.20
reasons.append("Very low pitch micro-variations (typical of TTS)")
elif jitter < 0.010:
ai_score += 0.10
reasons.append("Low pitch variation")
elif jitter > 0.025:
human_score += 0.15
# 2. Shimmer (amplitude micro-variations) - AI has less
shimmer = prosody.get("shimmer_local", 0.03)
if shimmer < 0.015:
ai_score += 0.18
reasons.append("Unnaturally stable amplitude")
elif shimmer < 0.025:
ai_score += 0.08
elif shimmer > 0.06:
human_score += 0.12
# 3. F0 coefficient of variation - AI often too consistent
f0_cv = prosody.get("f0_cv", 0.15)
if f0_cv < 0.06:
ai_score += 0.18
reasons.append("Monotonous pitch pattern")
elif f0_cv < 0.10:
ai_score += 0.08
elif f0_cv > 0.30:
human_score += 0.12
# 4. HNR (Harmonics-to-Noise Ratio) - AI often too clean
hnr = prosody.get("hnr", 15)
if hnr > 28:
ai_score += 0.15
reasons.append("Unnaturally clear audio signal")
elif hnr > 22:
ai_score += 0.07
elif hnr < 8:
human_score += 0.10
# 5. Spectral flux - how much spectrum changes over time
flux_mean = spectral.get("flux_mean", 0)
flux_std = spectral.get("flux_std", 0)
if flux_std < 0.01 and flux_mean < 0.05:
ai_score += 0.12
reasons.append("Overly stable spectral content")
elif flux_std > 0.03:
human_score += 0.10
# 6. Spectral centroid variation
centroid_cv = spectral.get("centroid_cv", 0.1)
if centroid_cv < 0.04:
ai_score += 0.12
reasons.append("Lack of spectral variation")
elif centroid_cv > 0.15:
human_score += 0.08
# 7. Spectral rolloff consistency - AI has sharp cutoffs
rolloff_std = spectral.get("rolloff_std", 500)
if rolloff_std < 250:
ai_score += 0.10
reasons.append("Sharp frequency cutoff detected")
elif rolloff_std > 800:
human_score += 0.08
# 8. MFCC delta variation - AI often has smoother transitions
mfcc_delta_std = np.mean([mfcc.get(f"mfcc_{i}_delta_std", 0) for i in range(5)])
if mfcc_delta_std < 1.5:
ai_score += 0.10
elif mfcc_delta_std > 4.0:
human_score += 0.08
# 9. Zero crossing rate variation
zcr_std = spectral.get("zcr_std", 0)
if zcr_std < 0.01:
ai_score += 0.08
elif zcr_std > 0.04:
human_score += 0.06
# 10. Speech rate consistency check via energy envelope
energy_std = spectral.get("rms_std", 0)
energy_mean = spectral.get("rms_mean", 0.01)
energy_cv = energy_std / (energy_mean + 1e-6)
if energy_cv < 0.3:
ai_score += 0.08
elif energy_cv > 0.8:
human_score += 0.06
# Normalize to probability
total = ai_score + human_score + 0.25 # baseline (lowered for sensitivity)
ai_probability = ai_score / total
return {
"ai_probability": ai_probability,
"ai_score": ai_score,
"human_score": human_score,
"reasons": reasons
}
def analyze_audio(
self,
audio: np.ndarray,
sr: int,
language: str
) -> Dict:
"""
Analyze audio using hybrid approach.
Combines ML model prediction with heuristic rules.
"""
# Preprocess
audio = preprocess_audio(audio, sr)
# Get heuristic score (always computed - works on any data)
heuristic = self._compute_heuristic_score(audio, sr)
heuristic_prob = heuristic["ai_probability"]
# Get model score if available
model_prob = None
if self.model is not None and self.model.is_fitted:
try:
features = self._extract_features(audio, sr)
_, model_prob = self.model.predict_single(features)
except Exception as e:
logger.warning(f"Model prediction failed: {e}")
model_prob = None
# HYBRID SCORING: Combine model and heuristics
if model_prob is not None:
# Give model more weight since it learned from TTS patterns
# Model: 70%, Heuristics: 30%
final_prob = 0.70 * model_prob + 0.30 * heuristic_prob
# Boost if model detects AI (even slightly)
if model_prob > 0.4:
final_prob = min(final_prob * 1.2, 0.99)
# Additional boost if both agree on AI
if model_prob > 0.5 and heuristic_prob > 0.25:
final_prob = min(final_prob * 1.1, 0.99)
method = "hybrid"
else:
final_prob = heuristic_prob
method = "heuristics"
# Determine classification (lower threshold for higher sensitivity)
detection_threshold = 0.38 # More sensitive to catch phone-recorded AI
if final_prob >= detection_threshold:
classification = "AI_GENERATED"
confidence = final_prob
if heuristic["reasons"]:
explanation = " | ".join(heuristic["reasons"][:3])
else:
explanation = "Audio exhibits synthetic voice characteristics."
else:
classification = "HUMAN"
confidence = 1 - final_prob
explanation = self._get_human_explanation(confidence)
return {
"status": "success",
"language": language,
"classification": classification,
"confidenceScore": round(confidence, 4),
"explanation": explanation,
"method": method,
"details": {
"heuristic_score": round(heuristic_prob, 4),
"model_score": round(model_prob, 4) if model_prob else None,
"final_score": round(final_prob, 4)
}
}
def _get_human_explanation(self, confidence: float) -> str:
"""Generate explanation for human detection."""
if confidence > 0.85:
return "Audio shows natural speech patterns with normal micro-variations typical of human voice."
elif confidence > 0.65:
return "Audio appears to be natural human speech with typical voice characteristics."
else:
return "Audio likely human speech, though some characteristics need more analysis."
def _analyze_multi_segment(
self,
audio: np.ndarray,
sr: int,
language: str,
segment_duration: float = 3.0
) -> Dict:
"""
Analyze audio in multiple segments and combine results.
This improves accuracy by voting across different parts of the audio.
"""
segment_samples = int(segment_duration * sr)
total_samples = len(audio)
# Create overlapping segments
segments = []
step = segment_samples // 2 # 50% overlap
for start in range(0, total_samples - segment_samples + 1, step):
end = start + segment_samples
segments.append(audio[start:end])
# If audio is shorter than segment, just analyze it directly
if len(segments) == 0:
return self.analyze_audio(audio, sr, language)
# Limit to 5 segments for efficiency
if len(segments) > 5:
# Take evenly spaced segments
indices = np.linspace(0, len(segments) - 1, 5, dtype=int)
segments = [segments[i] for i in indices]
# Analyze each segment
ai_votes = 0
human_votes = 0
total_ai_prob = 0.0
total_model_prob = 0.0
all_reasons = []
for i, segment in enumerate(segments):
result = self.analyze_audio(segment, sr, language)
if result["classification"] == "AI_GENERATED":
ai_votes += 1
else:
human_votes += 1
total_ai_prob += result["details"]["final_score"]
if result["details"].get("model_score"):
total_model_prob += result["details"]["model_score"]
if result.get("explanation"):
all_reasons.append(result["explanation"])
# Average probability
avg_ai_prob = total_ai_prob / len(segments)
avg_model_prob = total_model_prob / len(segments) if total_model_prob > 0 else 0
# AGGRESSIVE DETECTION: Classify as AI if:
# 1. Any segment says AI, OR
# 2. Average probability >= 0.30, OR
# 3. Model average >= 0.15 (catches phone-recorded AI where model shows slight AI signal)
is_ai = (ai_votes >= 1) or (avg_ai_prob >= 0.30) or (avg_model_prob >= 0.15)
if is_ai:
classification = "AI_GENERATED"
confidence = max(avg_ai_prob, 0.5) # Minimum 50% confidence for AI
# Get unique reasons
unique_reasons = list(set([r for r in all_reasons if "Overly" in r or "low" in r.lower() or "stable" in r.lower()]))
explanation = " | ".join(unique_reasons[:2]) if unique_reasons else "Audio segments show synthetic voice patterns."
else:
classification = "HUMAN"
confidence = 1 - avg_ai_prob
explanation = self._get_human_explanation(confidence)
return {
"status": "success",
"language": language,
"classification": classification,
"confidenceScore": round(confidence, 4),
"explanation": explanation,
"method": "multi_segment",
"details": {
"segments_analyzed": len(segments),
"ai_votes": ai_votes,
"human_votes": human_votes,
"heuristic_score": round(avg_ai_prob, 4),
"model_score": round(avg_model_prob, 4) if avg_model_prob > 0 else None,
"final_score": round(avg_ai_prob, 4)
}
}
def analyze_file(
self,
file_path: Union[str, Path],
language: str
) -> Dict:
"""Analyze audio from file path with multi-segment analysis."""
try:
audio, sr = load_audio(file_path, sr=SAMPLE_RATE)
# For longer audio (>5 seconds), use multi-segment analysis
duration = len(audio) / sr
if duration > 5.0:
return self._analyze_multi_segment(audio, sr, language)
else:
return self.analyze_audio(audio, sr, language)
except Exception as e:
logger.error(f"Error analyzing file: {e}")
raise
def analyze_base64(
self,
audio_base64: str,
audio_format: str,
language: str
) -> Dict:
"""Analyze base64-encoded audio."""
try:
audio, sr = decode_base64_audio(audio_base64, audio_format, sr=SAMPLE_RATE)
return self.analyze_audio(audio, sr, language)
except Exception as e:
logger.error(f"Error analyzing base64 audio: {e}")
raise
def analyze_bytes(
self,
audio_bytes: bytes,
language: str
) -> Dict:
"""Analyze audio from bytes."""
try:
audio, sr = load_audio(audio_bytes, sr=SAMPLE_RATE)
return self.analyze_audio(audio, sr, language)
except Exception as e:
logger.error(f"Error analyzing audio bytes: {e}")
raise
# Global detector instance
_detector_instance: Optional[VoiceDetector] = None
def get_detector() -> VoiceDetector:
"""Get or create the global detector instance."""
global _detector_instance
if _detector_instance is None:
_detector_instance = VoiceDetector()
return _detector_instance
def set_detector(detector: VoiceDetector):
"""Set the global detector instance."""
global _detector_instance
_detector_instance = detector