File size: 15,533 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | """
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
|