intial commit
Browse files- .gitignore +43 -0
- Dockerfile +30 -0
- api/__init__.py +1 -0
- api/app.py +350 -0
- api/detector.py +422 -0
- config.py +89 -0
- features/__init__.py +4 -0
- features/mfcc.py +208 -0
- features/prosody.py +361 -0
- features/spectral.py +226 -0
- main.py +265 -0
- models/__init__.py +1 -0
- models/cnn.py +265 -0
- models/ensemble.py +300 -0
- models/traditional.py +212 -0
- requirements.txt +26 -0
- saved_models/traditional_random_forest.pkl +3 -0
- training/__init__.py +1 -0
- training/dataset.py +192 -0
- training/trainer.py +226 -0
- utils/__init__.py +1 -0
- utils/audio.py +176 -0
.gitignore
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
.Python
|
| 7 |
+
env/
|
| 8 |
+
venv/
|
| 9 |
+
.venv/
|
| 10 |
+
build/
|
| 11 |
+
develop-eggs/
|
| 12 |
+
dist/
|
| 13 |
+
downloads/
|
| 14 |
+
eggs/
|
| 15 |
+
.eggs/
|
| 16 |
+
lib/
|
| 17 |
+
lib64/
|
| 18 |
+
parts/
|
| 19 |
+
sdist/
|
| 20 |
+
var/
|
| 21 |
+
wheels/
|
| 22 |
+
*.egg-info/
|
| 23 |
+
.installed.cfg
|
| 24 |
+
*.egg
|
| 25 |
+
|
| 26 |
+
# Installer logs
|
| 27 |
+
pip-log.txt
|
| 28 |
+
pip-delete-this-directory.txt
|
| 29 |
+
|
| 30 |
+
# Audio files (optional: keep if needed for demos, ignore if large dataset)
|
| 31 |
+
# *.wav
|
| 32 |
+
# *.mp3
|
| 33 |
+
# *.flac
|
| 34 |
+
|
| 35 |
+
# VocalSense specific
|
| 36 |
+
data/
|
| 37 |
+
temp/
|
| 38 |
+
logs/
|
| 39 |
+
.env
|
| 40 |
+
|
| 41 |
+
# OS specific
|
| 42 |
+
.DS_Store
|
| 43 |
+
Thumbs.db
|
Dockerfile
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system dependencies required for audio processing (libsndfile)
|
| 6 |
+
RUN apt-get update && apt-get install -y \
|
| 7 |
+
libsndfile1 \
|
| 8 |
+
ffmpeg \
|
| 9 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
+
|
| 11 |
+
# Copy requirements first to leverage Docker cache
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
+
|
| 14 |
+
# Install python dependencies
|
| 15 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 16 |
+
|
| 17 |
+
# Copy the rest of the application
|
| 18 |
+
COPY . .
|
| 19 |
+
|
| 20 |
+
# Create a non-root user (recommended for security and HF Spaces)
|
| 21 |
+
RUN useradd -m -u 1000 user
|
| 22 |
+
USER user
|
| 23 |
+
ENV HOME=/home/user \
|
| 24 |
+
PATH=/home/user/.local/bin:$PATH
|
| 25 |
+
|
| 26 |
+
# Expose the port used by Hugging Face Spaces (7860)
|
| 27 |
+
EXPOSE 7860
|
| 28 |
+
|
| 29 |
+
# Start the application on port 7860
|
| 30 |
+
CMD ["python", "main.py", "serve", "--host", "0.0.0.0", "--port", "7860"]
|
api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# API module
|
api/app.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VocalSense FastAPI Application
|
| 3 |
+
REST API for AI voice detection with two endpoints:
|
| 4 |
+
- POST /api/v1/analyze/base64 - Accept base64-encoded audio
|
| 5 |
+
- POST /api/v1/analyze/file - Accept file upload
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import tempfile
|
| 9 |
+
import logging
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Optional
|
| 12 |
+
from contextlib import asynccontextmanager
|
| 13 |
+
|
| 14 |
+
from fastapi import FastAPI, HTTPException, Depends, Header, UploadFile, File, Form
|
| 15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from fastapi.responses import JSONResponse
|
| 17 |
+
from pydantic import BaseModel, Field, validator
|
| 18 |
+
|
| 19 |
+
import sys
|
| 20 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 21 |
+
from config import (
|
| 22 |
+
API_VERSION, API_KEY, SUPPORTED_LANGUAGES,
|
| 23 |
+
ALLOWED_AUDIO_FORMATS, MAX_FILE_SIZE_MB
|
| 24 |
+
)
|
| 25 |
+
from api.detector import get_detector, VoiceDetector
|
| 26 |
+
|
| 27 |
+
# Configure logging
|
| 28 |
+
logging.basicConfig(level=logging.INFO)
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# =============================================================================
|
| 33 |
+
# Pydantic Models
|
| 34 |
+
# =============================================================================
|
| 35 |
+
|
| 36 |
+
class Base64AudioRequest(BaseModel):
|
| 37 |
+
"""Request model for base64-encoded audio."""
|
| 38 |
+
language: str = Field(..., description="Language of the audio")
|
| 39 |
+
audioFormat: str = Field(..., description="Audio format (wav, mp3, etc.)")
|
| 40 |
+
audioBase64: str = Field(..., description="Base64-encoded audio data")
|
| 41 |
+
|
| 42 |
+
@validator("language")
|
| 43 |
+
def validate_language(cls, v):
|
| 44 |
+
if v not in SUPPORTED_LANGUAGES:
|
| 45 |
+
raise ValueError(f"Unsupported language. Must be one of: {SUPPORTED_LANGUAGES}")
|
| 46 |
+
return v
|
| 47 |
+
|
| 48 |
+
@validator("audioFormat")
|
| 49 |
+
def validate_format(cls, v):
|
| 50 |
+
v_lower = v.lower()
|
| 51 |
+
if v_lower not in ALLOWED_AUDIO_FORMATS:
|
| 52 |
+
raise ValueError(f"Unsupported format. Must be one of: {ALLOWED_AUDIO_FORMATS}")
|
| 53 |
+
return v_lower
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class AnalysisResponse(BaseModel):
|
| 57 |
+
"""Successful analysis response."""
|
| 58 |
+
status: str = "success"
|
| 59 |
+
language: str
|
| 60 |
+
classification: str # "AI_GENERATED" or "HUMAN"
|
| 61 |
+
confidenceScore: float
|
| 62 |
+
explanation: str
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ErrorResponse(BaseModel):
|
| 66 |
+
"""Error response model."""
|
| 67 |
+
status: str = "error"
|
| 68 |
+
message: str
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# =============================================================================
|
| 72 |
+
# Dependency Injection
|
| 73 |
+
# =============================================================================
|
| 74 |
+
|
| 75 |
+
async def verify_api_key(x_api_key: str = Header(..., alias="X-API-Key")) -> str:
|
| 76 |
+
"""
|
| 77 |
+
Verify the API key from request headers.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
x_api_key: API key from X-API-Key header
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
The validated API key
|
| 84 |
+
|
| 85 |
+
Raises:
|
| 86 |
+
HTTPException: If API key is invalid or missing
|
| 87 |
+
"""
|
| 88 |
+
if not x_api_key:
|
| 89 |
+
raise HTTPException(
|
| 90 |
+
status_code=401,
|
| 91 |
+
detail={"status": "error", "message": "API key is required"}
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
if x_api_key != API_KEY:
|
| 95 |
+
raise HTTPException(
|
| 96 |
+
status_code=403,
|
| 97 |
+
detail={"status": "error", "message": "Invalid API key"}
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
return x_api_key
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def validate_language(language: str) -> str:
|
| 104 |
+
"""Validate language parameter."""
|
| 105 |
+
if language not in SUPPORTED_LANGUAGES:
|
| 106 |
+
raise HTTPException(
|
| 107 |
+
status_code=400,
|
| 108 |
+
detail={
|
| 109 |
+
"status": "error",
|
| 110 |
+
"message": f"Unsupported language '{language}'. Supported languages: {', '.join(SUPPORTED_LANGUAGES)}"
|
| 111 |
+
}
|
| 112 |
+
)
|
| 113 |
+
return language
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# =============================================================================
|
| 117 |
+
# Lifespan Events
|
| 118 |
+
# =============================================================================
|
| 119 |
+
|
| 120 |
+
@asynccontextmanager
|
| 121 |
+
async def lifespan(app: FastAPI):
|
| 122 |
+
"""Application lifespan events."""
|
| 123 |
+
# Startup
|
| 124 |
+
logger.info("Starting VocalSense API...")
|
| 125 |
+
logger.info(f"Supported languages: {SUPPORTED_LANGUAGES}")
|
| 126 |
+
logger.info(f"API Version: {API_VERSION}")
|
| 127 |
+
|
| 128 |
+
# Initialize detector
|
| 129 |
+
detector = get_detector()
|
| 130 |
+
logger.info("Voice detector initialized")
|
| 131 |
+
|
| 132 |
+
yield
|
| 133 |
+
|
| 134 |
+
# Shutdown
|
| 135 |
+
logger.info("Shutting down VocalSense API...")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# =============================================================================
|
| 139 |
+
# FastAPI Application
|
| 140 |
+
# =============================================================================
|
| 141 |
+
|
| 142 |
+
app = FastAPI(
|
| 143 |
+
title="VocalSense API",
|
| 144 |
+
description="AI Voice Detection System - Detect AI-generated voices using spectral analysis",
|
| 145 |
+
version="1.0.0",
|
| 146 |
+
lifespan=lifespan
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# CORS middleware
|
| 150 |
+
app.add_middleware(
|
| 151 |
+
CORSMiddleware,
|
| 152 |
+
allow_origins=["*"],
|
| 153 |
+
allow_credentials=True,
|
| 154 |
+
allow_methods=["*"],
|
| 155 |
+
allow_headers=["*"],
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# =============================================================================
|
| 160 |
+
# Exception Handlers
|
| 161 |
+
# =============================================================================
|
| 162 |
+
|
| 163 |
+
@app.exception_handler(HTTPException)
|
| 164 |
+
async def http_exception_handler(request, exc):
|
| 165 |
+
"""Handle HTTP exceptions with proper error format."""
|
| 166 |
+
if isinstance(exc.detail, dict):
|
| 167 |
+
return JSONResponse(status_code=exc.status_code, content=exc.detail)
|
| 168 |
+
return JSONResponse(
|
| 169 |
+
status_code=exc.status_code,
|
| 170 |
+
content={"status": "error", "message": str(exc.detail)}
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@app.exception_handler(Exception)
|
| 175 |
+
async def general_exception_handler(request, exc):
|
| 176 |
+
"""Handle unexpected exceptions."""
|
| 177 |
+
logger.exception(f"Unexpected error: {exc}")
|
| 178 |
+
return JSONResponse(
|
| 179 |
+
status_code=500,
|
| 180 |
+
content={"status": "error", "message": "Internal server error"}
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# =============================================================================
|
| 185 |
+
# API Endpoints
|
| 186 |
+
# =============================================================================
|
| 187 |
+
|
| 188 |
+
@app.get("/health")
|
| 189 |
+
async def health_check():
|
| 190 |
+
"""Health check endpoint."""
|
| 191 |
+
return {"status": "healthy", "version": API_VERSION}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@app.post(
|
| 195 |
+
f"/api/{API_VERSION}/analyze/base64",
|
| 196 |
+
response_model=AnalysisResponse,
|
| 197 |
+
responses={
|
| 198 |
+
400: {"model": ErrorResponse, "description": "Bad request"},
|
| 199 |
+
401: {"model": ErrorResponse, "description": "Missing API key"},
|
| 200 |
+
403: {"model": ErrorResponse, "description": "Invalid API key"},
|
| 201 |
+
500: {"model": ErrorResponse, "description": "Internal server error"}
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
async def analyze_base64_audio(
|
| 205 |
+
request: Base64AudioRequest,
|
| 206 |
+
api_key: str = Depends(verify_api_key)
|
| 207 |
+
):
|
| 208 |
+
"""
|
| 209 |
+
Analyze base64-encoded audio for AI voice detection.
|
| 210 |
+
|
| 211 |
+
Requires X-API-Key header for authentication.
|
| 212 |
+
|
| 213 |
+
**Request Body:**
|
| 214 |
+
- language: Language of the audio (Hindi, Tamil, Telugu, Malayalam, English)
|
| 215 |
+
- audioFormat: Audio format (wav, mp3, flac, ogg, m4a)
|
| 216 |
+
- audioBase64: Base64-encoded audio data
|
| 217 |
+
|
| 218 |
+
**Response:**
|
| 219 |
+
- status: "success"
|
| 220 |
+
- language: The input language
|
| 221 |
+
- classification: "AI_GENERATED" or "HUMAN"
|
| 222 |
+
- confidenceScore: Confidence score (0-1)
|
| 223 |
+
- explanation: Human-readable explanation
|
| 224 |
+
"""
|
| 225 |
+
try:
|
| 226 |
+
detector = get_detector()
|
| 227 |
+
result = detector.analyze_base64(
|
| 228 |
+
audio_base64=request.audioBase64,
|
| 229 |
+
audio_format=request.audioFormat,
|
| 230 |
+
language=request.language
|
| 231 |
+
)
|
| 232 |
+
return result
|
| 233 |
+
|
| 234 |
+
except ValueError as e:
|
| 235 |
+
raise HTTPException(
|
| 236 |
+
status_code=400,
|
| 237 |
+
detail={"status": "error", "message": str(e)}
|
| 238 |
+
)
|
| 239 |
+
except Exception as e:
|
| 240 |
+
logger.exception(f"Error analyzing base64 audio: {e}")
|
| 241 |
+
raise HTTPException(
|
| 242 |
+
status_code=500,
|
| 243 |
+
detail={"status": "error", "message": "Failed to analyze audio"}
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@app.post(
|
| 248 |
+
f"/api/{API_VERSION}/analyze/file",
|
| 249 |
+
response_model=AnalysisResponse,
|
| 250 |
+
responses={
|
| 251 |
+
400: {"model": ErrorResponse, "description": "Bad request"},
|
| 252 |
+
401: {"model": ErrorResponse, "description": "Missing API key"},
|
| 253 |
+
403: {"model": ErrorResponse, "description": "Invalid API key"},
|
| 254 |
+
413: {"model": ErrorResponse, "description": "File too large"},
|
| 255 |
+
500: {"model": ErrorResponse, "description": "Internal server error"}
|
| 256 |
+
}
|
| 257 |
+
)
|
| 258 |
+
async def analyze_file_upload(
|
| 259 |
+
language: str = Form(..., description="Language of the audio"),
|
| 260 |
+
file: UploadFile = File(..., description="Audio file to analyze"),
|
| 261 |
+
api_key: str = Depends(verify_api_key)
|
| 262 |
+
):
|
| 263 |
+
"""
|
| 264 |
+
Analyze uploaded audio file for AI voice detection.
|
| 265 |
+
|
| 266 |
+
Requires X-API-Key header for authentication.
|
| 267 |
+
|
| 268 |
+
**Form Data:**
|
| 269 |
+
- language: Language of the audio (Hindi, Tamil, Telugu, Malayalam, English)
|
| 270 |
+
- file: Audio file (multipart/form-data)
|
| 271 |
+
|
| 272 |
+
**Response:**
|
| 273 |
+
- status: "success"
|
| 274 |
+
- language: The input language
|
| 275 |
+
- classification: "AI_GENERATED" or "HUMAN"
|
| 276 |
+
- confidenceScore: Confidence score (0-1)
|
| 277 |
+
- explanation: Human-readable explanation
|
| 278 |
+
"""
|
| 279 |
+
# Validate language
|
| 280 |
+
validate_language(language)
|
| 281 |
+
|
| 282 |
+
# Check file size
|
| 283 |
+
content = await file.read()
|
| 284 |
+
file_size_mb = len(content) / (1024 * 1024)
|
| 285 |
+
|
| 286 |
+
if file_size_mb > MAX_FILE_SIZE_MB:
|
| 287 |
+
raise HTTPException(
|
| 288 |
+
status_code=413,
|
| 289 |
+
detail={
|
| 290 |
+
"status": "error",
|
| 291 |
+
"message": f"File too large. Maximum size is {MAX_FILE_SIZE_MB}MB"
|
| 292 |
+
}
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
# Get file extension
|
| 296 |
+
filename = file.filename or "audio.wav"
|
| 297 |
+
extension = Path(filename).suffix.lower().lstrip(".")
|
| 298 |
+
|
| 299 |
+
if extension not in ALLOWED_AUDIO_FORMATS:
|
| 300 |
+
raise HTTPException(
|
| 301 |
+
status_code=400,
|
| 302 |
+
detail={
|
| 303 |
+
"status": "error",
|
| 304 |
+
"message": f"Unsupported file format. Allowed: {', '.join(ALLOWED_AUDIO_FORMATS)}"
|
| 305 |
+
}
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
try:
|
| 309 |
+
# Save to temp file and analyze
|
| 310 |
+
with tempfile.NamedTemporaryFile(suffix=f".{extension}", delete=False) as tmp:
|
| 311 |
+
tmp.write(content)
|
| 312 |
+
tmp_path = tmp.name
|
| 313 |
+
|
| 314 |
+
try:
|
| 315 |
+
detector = get_detector()
|
| 316 |
+
result = detector.analyze_file(tmp_path, language)
|
| 317 |
+
return result
|
| 318 |
+
finally:
|
| 319 |
+
# Clean up temp file
|
| 320 |
+
os.unlink(tmp_path)
|
| 321 |
+
|
| 322 |
+
except ValueError as e:
|
| 323 |
+
raise HTTPException(
|
| 324 |
+
status_code=400,
|
| 325 |
+
detail={"status": "error", "message": str(e)}
|
| 326 |
+
)
|
| 327 |
+
except Exception as e:
|
| 328 |
+
logger.exception(f"Error analyzing uploaded file: {e}")
|
| 329 |
+
raise HTTPException(
|
| 330 |
+
status_code=500,
|
| 331 |
+
detail={"status": "error", "message": "Failed to analyze audio"}
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
@app.get(f"/api/{API_VERSION}/languages")
|
| 336 |
+
async def get_supported_languages():
|
| 337 |
+
"""Get list of supported languages."""
|
| 338 |
+
return {
|
| 339 |
+
"status": "success",
|
| 340 |
+
"languages": SUPPORTED_LANGUAGES
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# =============================================================================
|
| 345 |
+
# Run with Uvicorn
|
| 346 |
+
# =============================================================================
|
| 347 |
+
|
| 348 |
+
if __name__ == "__main__":
|
| 349 |
+
import uvicorn
|
| 350 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
api/detector.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VocalSense Voice Detection Service
|
| 3 |
+
Hybrid detection using trained model + heuristics for better generalization.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Dict, Optional, Union
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 12 |
+
from config import SAMPLE_RATE, SUPPORTED_LANGUAGES, AI_DETECTION_THRESHOLD, MODELS_DIR
|
| 13 |
+
from utils.audio import load_audio, decode_base64_audio, preprocess_audio, segment_audio
|
| 14 |
+
from features.spectral import extract_spectral_features
|
| 15 |
+
from features.mfcc import extract_mfcc_features
|
| 16 |
+
from features.prosody import extract_prosodic_features
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class VoiceDetector:
|
| 22 |
+
"""
|
| 23 |
+
Hybrid voice detection service.
|
| 24 |
+
Combines trained ML model with heuristic rules for better generalization.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
model_path: Optional[Path] = None,
|
| 30 |
+
threshold: float = AI_DETECTION_THRESHOLD
|
| 31 |
+
):
|
| 32 |
+
"""
|
| 33 |
+
Initialize the detector.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
model_path: Path to trained model (auto-loads if not specified)
|
| 37 |
+
threshold: Threshold for AI classification
|
| 38 |
+
"""
|
| 39 |
+
self.threshold = threshold
|
| 40 |
+
self.model = None
|
| 41 |
+
self._load_model(model_path)
|
| 42 |
+
|
| 43 |
+
def _load_model(self, model_path: Optional[Path] = None):
|
| 44 |
+
"""Load the trained model."""
|
| 45 |
+
if model_path is None:
|
| 46 |
+
model_path = MODELS_DIR / "traditional_random_forest.pkl"
|
| 47 |
+
|
| 48 |
+
if model_path.exists():
|
| 49 |
+
try:
|
| 50 |
+
from models.traditional import FeatureBasedClassifier
|
| 51 |
+
self.model = FeatureBasedClassifier.load(model_path)
|
| 52 |
+
logger.info(f"Loaded trained model from {model_path}")
|
| 53 |
+
print(f"[OK] Loaded trained model: {model_path.name}")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.warning(f"Could not load model: {e}")
|
| 56 |
+
self.model = None
|
| 57 |
+
else:
|
| 58 |
+
self.model = None
|
| 59 |
+
|
| 60 |
+
def _extract_features(self, audio: np.ndarray, sr: int) -> np.ndarray:
|
| 61 |
+
"""Extract all features from audio."""
|
| 62 |
+
spectral = extract_spectral_features(audio, sr)
|
| 63 |
+
mfcc = extract_mfcc_features(audio, sr)
|
| 64 |
+
prosody = extract_prosodic_features(audio, sr)
|
| 65 |
+
|
| 66 |
+
all_features = {}
|
| 67 |
+
all_features.update(spectral)
|
| 68 |
+
all_features.update(mfcc)
|
| 69 |
+
all_features.update(prosody)
|
| 70 |
+
|
| 71 |
+
return np.array(list(all_features.values()))
|
| 72 |
+
|
| 73 |
+
def _compute_heuristic_score(self, audio: np.ndarray, sr: int) -> Dict:
|
| 74 |
+
"""
|
| 75 |
+
Compute AI detection score using proven heuristics.
|
| 76 |
+
These work well on unseen data because they're based on research.
|
| 77 |
+
"""
|
| 78 |
+
spectral = extract_spectral_features(audio, sr)
|
| 79 |
+
mfcc = extract_mfcc_features(audio, sr)
|
| 80 |
+
prosody = extract_prosodic_features(audio, sr)
|
| 81 |
+
|
| 82 |
+
ai_score = 0.0
|
| 83 |
+
human_score = 0.0
|
| 84 |
+
reasons = []
|
| 85 |
+
|
| 86 |
+
# 1. Jitter (pitch micro-variations) - AI has less
|
| 87 |
+
jitter = prosody.get("jitter_local", 0.01)
|
| 88 |
+
if jitter < 0.005:
|
| 89 |
+
ai_score += 0.20
|
| 90 |
+
reasons.append("Very low pitch micro-variations (typical of TTS)")
|
| 91 |
+
elif jitter < 0.010:
|
| 92 |
+
ai_score += 0.10
|
| 93 |
+
reasons.append("Low pitch variation")
|
| 94 |
+
elif jitter > 0.025:
|
| 95 |
+
human_score += 0.15
|
| 96 |
+
|
| 97 |
+
# 2. Shimmer (amplitude micro-variations) - AI has less
|
| 98 |
+
shimmer = prosody.get("shimmer_local", 0.03)
|
| 99 |
+
if shimmer < 0.015:
|
| 100 |
+
ai_score += 0.18
|
| 101 |
+
reasons.append("Unnaturally stable amplitude")
|
| 102 |
+
elif shimmer < 0.025:
|
| 103 |
+
ai_score += 0.08
|
| 104 |
+
elif shimmer > 0.06:
|
| 105 |
+
human_score += 0.12
|
| 106 |
+
|
| 107 |
+
# 3. F0 coefficient of variation - AI often too consistent
|
| 108 |
+
f0_cv = prosody.get("f0_cv", 0.15)
|
| 109 |
+
if f0_cv < 0.06:
|
| 110 |
+
ai_score += 0.18
|
| 111 |
+
reasons.append("Monotonous pitch pattern")
|
| 112 |
+
elif f0_cv < 0.10:
|
| 113 |
+
ai_score += 0.08
|
| 114 |
+
elif f0_cv > 0.30:
|
| 115 |
+
human_score += 0.12
|
| 116 |
+
|
| 117 |
+
# 4. HNR (Harmonics-to-Noise Ratio) - AI often too clean
|
| 118 |
+
hnr = prosody.get("hnr", 15)
|
| 119 |
+
if hnr > 28:
|
| 120 |
+
ai_score += 0.15
|
| 121 |
+
reasons.append("Unnaturally clear audio signal")
|
| 122 |
+
elif hnr > 22:
|
| 123 |
+
ai_score += 0.07
|
| 124 |
+
elif hnr < 8:
|
| 125 |
+
human_score += 0.10
|
| 126 |
+
|
| 127 |
+
# 5. Spectral flux - how much spectrum changes over time
|
| 128 |
+
flux_mean = spectral.get("flux_mean", 0)
|
| 129 |
+
flux_std = spectral.get("flux_std", 0)
|
| 130 |
+
if flux_std < 0.01 and flux_mean < 0.05:
|
| 131 |
+
ai_score += 0.12
|
| 132 |
+
reasons.append("Overly stable spectral content")
|
| 133 |
+
elif flux_std > 0.03:
|
| 134 |
+
human_score += 0.10
|
| 135 |
+
|
| 136 |
+
# 6. Spectral centroid variation
|
| 137 |
+
centroid_cv = spectral.get("centroid_cv", 0.1)
|
| 138 |
+
if centroid_cv < 0.04:
|
| 139 |
+
ai_score += 0.12
|
| 140 |
+
reasons.append("Lack of spectral variation")
|
| 141 |
+
elif centroid_cv > 0.15:
|
| 142 |
+
human_score += 0.08
|
| 143 |
+
|
| 144 |
+
# 7. Spectral rolloff consistency - AI has sharp cutoffs
|
| 145 |
+
rolloff_std = spectral.get("rolloff_std", 500)
|
| 146 |
+
if rolloff_std < 250:
|
| 147 |
+
ai_score += 0.10
|
| 148 |
+
reasons.append("Sharp frequency cutoff detected")
|
| 149 |
+
elif rolloff_std > 800:
|
| 150 |
+
human_score += 0.08
|
| 151 |
+
|
| 152 |
+
# 8. MFCC delta variation - AI often has smoother transitions
|
| 153 |
+
mfcc_delta_std = np.mean([mfcc.get(f"mfcc_{i}_delta_std", 0) for i in range(5)])
|
| 154 |
+
if mfcc_delta_std < 1.5:
|
| 155 |
+
ai_score += 0.10
|
| 156 |
+
elif mfcc_delta_std > 4.0:
|
| 157 |
+
human_score += 0.08
|
| 158 |
+
|
| 159 |
+
# 9. Zero crossing rate variation
|
| 160 |
+
zcr_std = spectral.get("zcr_std", 0)
|
| 161 |
+
if zcr_std < 0.01:
|
| 162 |
+
ai_score += 0.08
|
| 163 |
+
elif zcr_std > 0.04:
|
| 164 |
+
human_score += 0.06
|
| 165 |
+
|
| 166 |
+
# 10. Speech rate consistency check via energy envelope
|
| 167 |
+
energy_std = spectral.get("rms_std", 0)
|
| 168 |
+
energy_mean = spectral.get("rms_mean", 0.01)
|
| 169 |
+
energy_cv = energy_std / (energy_mean + 1e-6)
|
| 170 |
+
if energy_cv < 0.3:
|
| 171 |
+
ai_score += 0.08
|
| 172 |
+
elif energy_cv > 0.8:
|
| 173 |
+
human_score += 0.06
|
| 174 |
+
|
| 175 |
+
# Normalize to probability
|
| 176 |
+
total = ai_score + human_score + 0.25 # baseline (lowered for sensitivity)
|
| 177 |
+
ai_probability = ai_score / total
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
"ai_probability": ai_probability,
|
| 181 |
+
"ai_score": ai_score,
|
| 182 |
+
"human_score": human_score,
|
| 183 |
+
"reasons": reasons
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
def analyze_audio(
|
| 187 |
+
self,
|
| 188 |
+
audio: np.ndarray,
|
| 189 |
+
sr: int,
|
| 190 |
+
language: str
|
| 191 |
+
) -> Dict:
|
| 192 |
+
"""
|
| 193 |
+
Analyze audio using hybrid approach.
|
| 194 |
+
Combines ML model prediction with heuristic rules.
|
| 195 |
+
"""
|
| 196 |
+
# Preprocess
|
| 197 |
+
audio = preprocess_audio(audio, sr)
|
| 198 |
+
|
| 199 |
+
# Get heuristic score (always computed - works on any data)
|
| 200 |
+
heuristic = self._compute_heuristic_score(audio, sr)
|
| 201 |
+
heuristic_prob = heuristic["ai_probability"]
|
| 202 |
+
|
| 203 |
+
# Get model score if available
|
| 204 |
+
model_prob = None
|
| 205 |
+
if self.model is not None and self.model.is_fitted:
|
| 206 |
+
try:
|
| 207 |
+
features = self._extract_features(audio, sr)
|
| 208 |
+
_, model_prob = self.model.predict_single(features)
|
| 209 |
+
except Exception as e:
|
| 210 |
+
logger.warning(f"Model prediction failed: {e}")
|
| 211 |
+
model_prob = None
|
| 212 |
+
|
| 213 |
+
# HYBRID SCORING: Combine model and heuristics
|
| 214 |
+
if model_prob is not None:
|
| 215 |
+
# Give model more weight since it learned from TTS patterns
|
| 216 |
+
# Model: 70%, Heuristics: 30%
|
| 217 |
+
final_prob = 0.70 * model_prob + 0.30 * heuristic_prob
|
| 218 |
+
|
| 219 |
+
# Boost if model detects AI (even slightly)
|
| 220 |
+
if model_prob > 0.4:
|
| 221 |
+
final_prob = min(final_prob * 1.2, 0.99)
|
| 222 |
+
|
| 223 |
+
# Additional boost if both agree on AI
|
| 224 |
+
if model_prob > 0.5 and heuristic_prob > 0.25:
|
| 225 |
+
final_prob = min(final_prob * 1.1, 0.99)
|
| 226 |
+
|
| 227 |
+
method = "hybrid"
|
| 228 |
+
else:
|
| 229 |
+
final_prob = heuristic_prob
|
| 230 |
+
method = "heuristics"
|
| 231 |
+
|
| 232 |
+
# Determine classification (lower threshold for higher sensitivity)
|
| 233 |
+
detection_threshold = 0.38 # More sensitive to catch phone-recorded AI
|
| 234 |
+
if final_prob >= detection_threshold:
|
| 235 |
+
classification = "AI_GENERATED"
|
| 236 |
+
confidence = final_prob
|
| 237 |
+
if heuristic["reasons"]:
|
| 238 |
+
explanation = " | ".join(heuristic["reasons"][:3])
|
| 239 |
+
else:
|
| 240 |
+
explanation = "Audio exhibits synthetic voice characteristics."
|
| 241 |
+
else:
|
| 242 |
+
classification = "HUMAN"
|
| 243 |
+
confidence = 1 - final_prob
|
| 244 |
+
explanation = self._get_human_explanation(confidence)
|
| 245 |
+
|
| 246 |
+
return {
|
| 247 |
+
"status": "success",
|
| 248 |
+
"language": language,
|
| 249 |
+
"classification": classification,
|
| 250 |
+
"confidenceScore": round(confidence, 4),
|
| 251 |
+
"explanation": explanation,
|
| 252 |
+
"method": method,
|
| 253 |
+
"details": {
|
| 254 |
+
"heuristic_score": round(heuristic_prob, 4),
|
| 255 |
+
"model_score": round(model_prob, 4) if model_prob else None,
|
| 256 |
+
"final_score": round(final_prob, 4)
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
def _get_human_explanation(self, confidence: float) -> str:
|
| 261 |
+
"""Generate explanation for human detection."""
|
| 262 |
+
if confidence > 0.85:
|
| 263 |
+
return "Audio shows natural speech patterns with normal micro-variations typical of human voice."
|
| 264 |
+
elif confidence > 0.65:
|
| 265 |
+
return "Audio appears to be natural human speech with typical voice characteristics."
|
| 266 |
+
else:
|
| 267 |
+
return "Audio likely human speech, though some characteristics need more analysis."
|
| 268 |
+
|
| 269 |
+
def _analyze_multi_segment(
|
| 270 |
+
self,
|
| 271 |
+
audio: np.ndarray,
|
| 272 |
+
sr: int,
|
| 273 |
+
language: str,
|
| 274 |
+
segment_duration: float = 3.0
|
| 275 |
+
) -> Dict:
|
| 276 |
+
"""
|
| 277 |
+
Analyze audio in multiple segments and combine results.
|
| 278 |
+
This improves accuracy by voting across different parts of the audio.
|
| 279 |
+
"""
|
| 280 |
+
segment_samples = int(segment_duration * sr)
|
| 281 |
+
total_samples = len(audio)
|
| 282 |
+
|
| 283 |
+
# Create overlapping segments
|
| 284 |
+
segments = []
|
| 285 |
+
step = segment_samples // 2 # 50% overlap
|
| 286 |
+
for start in range(0, total_samples - segment_samples + 1, step):
|
| 287 |
+
end = start + segment_samples
|
| 288 |
+
segments.append(audio[start:end])
|
| 289 |
+
|
| 290 |
+
# If audio is shorter than segment, just analyze it directly
|
| 291 |
+
if len(segments) == 0:
|
| 292 |
+
return self.analyze_audio(audio, sr, language)
|
| 293 |
+
|
| 294 |
+
# Limit to 5 segments for efficiency
|
| 295 |
+
if len(segments) > 5:
|
| 296 |
+
# Take evenly spaced segments
|
| 297 |
+
indices = np.linspace(0, len(segments) - 1, 5, dtype=int)
|
| 298 |
+
segments = [segments[i] for i in indices]
|
| 299 |
+
|
| 300 |
+
# Analyze each segment
|
| 301 |
+
ai_votes = 0
|
| 302 |
+
human_votes = 0
|
| 303 |
+
total_ai_prob = 0.0
|
| 304 |
+
total_model_prob = 0.0
|
| 305 |
+
all_reasons = []
|
| 306 |
+
|
| 307 |
+
for i, segment in enumerate(segments):
|
| 308 |
+
result = self.analyze_audio(segment, sr, language)
|
| 309 |
+
|
| 310 |
+
if result["classification"] == "AI_GENERATED":
|
| 311 |
+
ai_votes += 1
|
| 312 |
+
else:
|
| 313 |
+
human_votes += 1
|
| 314 |
+
|
| 315 |
+
total_ai_prob += result["details"]["final_score"]
|
| 316 |
+
if result["details"].get("model_score"):
|
| 317 |
+
total_model_prob += result["details"]["model_score"]
|
| 318 |
+
|
| 319 |
+
if result.get("explanation"):
|
| 320 |
+
all_reasons.append(result["explanation"])
|
| 321 |
+
|
| 322 |
+
# Average probability
|
| 323 |
+
avg_ai_prob = total_ai_prob / len(segments)
|
| 324 |
+
avg_model_prob = total_model_prob / len(segments) if total_model_prob > 0 else 0
|
| 325 |
+
|
| 326 |
+
# AGGRESSIVE DETECTION: Classify as AI if:
|
| 327 |
+
# 1. Any segment says AI, OR
|
| 328 |
+
# 2. Average probability >= 0.30, OR
|
| 329 |
+
# 3. Model average >= 0.15 (catches phone-recorded AI where model shows slight AI signal)
|
| 330 |
+
is_ai = (ai_votes >= 1) or (avg_ai_prob >= 0.30) or (avg_model_prob >= 0.15)
|
| 331 |
+
|
| 332 |
+
if is_ai:
|
| 333 |
+
classification = "AI_GENERATED"
|
| 334 |
+
confidence = max(avg_ai_prob, 0.5) # Minimum 50% confidence for AI
|
| 335 |
+
# Get unique reasons
|
| 336 |
+
unique_reasons = list(set([r for r in all_reasons if "Overly" in r or "low" in r.lower() or "stable" in r.lower()]))
|
| 337 |
+
explanation = " | ".join(unique_reasons[:2]) if unique_reasons else "Audio segments show synthetic voice patterns."
|
| 338 |
+
else:
|
| 339 |
+
classification = "HUMAN"
|
| 340 |
+
confidence = 1 - avg_ai_prob
|
| 341 |
+
explanation = self._get_human_explanation(confidence)
|
| 342 |
+
|
| 343 |
+
return {
|
| 344 |
+
"status": "success",
|
| 345 |
+
"language": language,
|
| 346 |
+
"classification": classification,
|
| 347 |
+
"confidenceScore": round(confidence, 4),
|
| 348 |
+
"explanation": explanation,
|
| 349 |
+
"method": "multi_segment",
|
| 350 |
+
"details": {
|
| 351 |
+
"segments_analyzed": len(segments),
|
| 352 |
+
"ai_votes": ai_votes,
|
| 353 |
+
"human_votes": human_votes,
|
| 354 |
+
"heuristic_score": round(avg_ai_prob, 4),
|
| 355 |
+
"model_score": round(avg_model_prob, 4) if avg_model_prob > 0 else None,
|
| 356 |
+
"final_score": round(avg_ai_prob, 4)
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
def analyze_file(
|
| 361 |
+
self,
|
| 362 |
+
file_path: Union[str, Path],
|
| 363 |
+
language: str
|
| 364 |
+
) -> Dict:
|
| 365 |
+
"""Analyze audio from file path with multi-segment analysis."""
|
| 366 |
+
try:
|
| 367 |
+
audio, sr = load_audio(file_path, sr=SAMPLE_RATE)
|
| 368 |
+
|
| 369 |
+
# For longer audio (>5 seconds), use multi-segment analysis
|
| 370 |
+
duration = len(audio) / sr
|
| 371 |
+
if duration > 5.0:
|
| 372 |
+
return self._analyze_multi_segment(audio, sr, language)
|
| 373 |
+
else:
|
| 374 |
+
return self.analyze_audio(audio, sr, language)
|
| 375 |
+
except Exception as e:
|
| 376 |
+
logger.error(f"Error analyzing file: {e}")
|
| 377 |
+
raise
|
| 378 |
+
|
| 379 |
+
def analyze_base64(
|
| 380 |
+
self,
|
| 381 |
+
audio_base64: str,
|
| 382 |
+
audio_format: str,
|
| 383 |
+
language: str
|
| 384 |
+
) -> Dict:
|
| 385 |
+
"""Analyze base64-encoded audio."""
|
| 386 |
+
try:
|
| 387 |
+
audio, sr = decode_base64_audio(audio_base64, audio_format, sr=SAMPLE_RATE)
|
| 388 |
+
return self.analyze_audio(audio, sr, language)
|
| 389 |
+
except Exception as e:
|
| 390 |
+
logger.error(f"Error analyzing base64 audio: {e}")
|
| 391 |
+
raise
|
| 392 |
+
|
| 393 |
+
def analyze_bytes(
|
| 394 |
+
self,
|
| 395 |
+
audio_bytes: bytes,
|
| 396 |
+
language: str
|
| 397 |
+
) -> Dict:
|
| 398 |
+
"""Analyze audio from bytes."""
|
| 399 |
+
try:
|
| 400 |
+
audio, sr = load_audio(audio_bytes, sr=SAMPLE_RATE)
|
| 401 |
+
return self.analyze_audio(audio, sr, language)
|
| 402 |
+
except Exception as e:
|
| 403 |
+
logger.error(f"Error analyzing audio bytes: {e}")
|
| 404 |
+
raise
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
# Global detector instance
|
| 408 |
+
_detector_instance: Optional[VoiceDetector] = None
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def get_detector() -> VoiceDetector:
|
| 412 |
+
"""Get or create the global detector instance."""
|
| 413 |
+
global _detector_instance
|
| 414 |
+
if _detector_instance is None:
|
| 415 |
+
_detector_instance = VoiceDetector()
|
| 416 |
+
return _detector_instance
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def set_detector(detector: VoiceDetector):
|
| 420 |
+
"""Set the global detector instance."""
|
| 421 |
+
global _detector_instance
|
| 422 |
+
_detector_instance = detector
|
config.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VocalSense Configuration
|
| 3 |
+
Central configuration for audio processing, models, and API settings.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# =============================================================================
|
| 10 |
+
# Paths
|
| 11 |
+
# =============================================================================
|
| 12 |
+
BASE_DIR = Path(__file__).parent
|
| 13 |
+
DATA_DIR = BASE_DIR / "data"
|
| 14 |
+
MODELS_DIR = BASE_DIR / "saved_models"
|
| 15 |
+
TEMP_DIR = BASE_DIR / "temp"
|
| 16 |
+
|
| 17 |
+
# Create directories if they don't exist
|
| 18 |
+
for dir_path in [DATA_DIR, MODELS_DIR, TEMP_DIR]:
|
| 19 |
+
dir_path.mkdir(exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# =============================================================================
|
| 22 |
+
# Audio Configuration
|
| 23 |
+
# =============================================================================
|
| 24 |
+
SAMPLE_RATE = 16000 # 16 kHz standard for speech
|
| 25 |
+
DURATION = 3.0 # 3-second chunks
|
| 26 |
+
N_FFT = 2048 # FFT window size
|
| 27 |
+
HOP_LENGTH = 512 # Hop length for STFT
|
| 28 |
+
N_MELS = 128 # Number of Mel bands
|
| 29 |
+
N_MFCC = 20 # Number of MFCCs
|
| 30 |
+
|
| 31 |
+
# F0 (Pitch) Configuration
|
| 32 |
+
F0_MIN = 50 # Minimum pitch (Hz)
|
| 33 |
+
F0_MAX = 500 # Maximum pitch (Hz)
|
| 34 |
+
|
| 35 |
+
# Spectral Rolloff
|
| 36 |
+
ROLLOFF_PERCENT = 0.85 # 85% energy rolloff
|
| 37 |
+
|
| 38 |
+
# =============================================================================
|
| 39 |
+
# Supported Languages
|
| 40 |
+
# =============================================================================
|
| 41 |
+
SUPPORTED_LANGUAGES = [
|
| 42 |
+
"Hindi",
|
| 43 |
+
"Tamil",
|
| 44 |
+
"Telugu",
|
| 45 |
+
"Malayalam",
|
| 46 |
+
"English"
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
# =============================================================================
|
| 50 |
+
# Model Configuration
|
| 51 |
+
# =============================================================================
|
| 52 |
+
# Traditional ML
|
| 53 |
+
SVM_KERNEL = "rbf"
|
| 54 |
+
RF_N_ESTIMATORS = 100
|
| 55 |
+
|
| 56 |
+
# CNN Configuration
|
| 57 |
+
CNN_INPUT_CHANNELS = 1
|
| 58 |
+
CNN_HIDDEN_DIMS = [32, 64, 128, 256]
|
| 59 |
+
CNN_DROPOUT = 0.3
|
| 60 |
+
|
| 61 |
+
# Ensemble Weights
|
| 62 |
+
ENSEMBLE_WEIGHTS = {
|
| 63 |
+
"traditional": 0.4,
|
| 64 |
+
"cnn": 0.6
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# =============================================================================
|
| 68 |
+
# Training Configuration
|
| 69 |
+
# =============================================================================
|
| 70 |
+
BATCH_SIZE = 32
|
| 71 |
+
LEARNING_RATE = 0.001
|
| 72 |
+
EPOCHS = 50
|
| 73 |
+
EARLY_STOPPING_PATIENCE = 5
|
| 74 |
+
|
| 75 |
+
# =============================================================================
|
| 76 |
+
# API Configuration
|
| 77 |
+
# =============================================================================
|
| 78 |
+
API_VERSION = "v1"
|
| 79 |
+
API_KEY = os.getenv("VOCALSENSE_API_KEY", "dev-key-change-in-production")
|
| 80 |
+
MAX_FILE_SIZE_MB = 50
|
| 81 |
+
ALLOWED_AUDIO_FORMATS = ["wav", "mp3", "flac", "ogg", "m4a"]
|
| 82 |
+
|
| 83 |
+
# =============================================================================
|
| 84 |
+
# Classification Thresholds
|
| 85 |
+
# =============================================================================
|
| 86 |
+
AI_DETECTION_THRESHOLD = 0.5 # Above this = AI generated
|
| 87 |
+
CONFIDENCE_HIGH = 0.8
|
| 88 |
+
CONFIDENCE_MEDIUM = 0.6
|
| 89 |
+
CONFIDENCE_LOW = 0.4
|
features/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Features module
|
| 2 |
+
from .spectral import extract_spectral_features
|
| 3 |
+
from .mfcc import extract_mel_spectrogram, extract_mfcc
|
| 4 |
+
from .prosody import extract_prosodic_features
|
features/mfcc.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MFCC and Mel-Spectrogram Feature Extraction
|
| 3 |
+
Extract Mel-frequency cepstral coefficients and spectrograms for voice analysis.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
import librosa
|
| 7 |
+
from typing import Dict, Tuple, Optional
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 12 |
+
from config import SAMPLE_RATE, N_FFT, HOP_LENGTH, N_MELS, N_MFCC
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_mel_spectrogram(
|
| 16 |
+
audio: np.ndarray,
|
| 17 |
+
sr: int = SAMPLE_RATE,
|
| 18 |
+
n_fft: int = N_FFT,
|
| 19 |
+
hop_length: int = HOP_LENGTH,
|
| 20 |
+
n_mels: int = N_MELS,
|
| 21 |
+
to_db: bool = True
|
| 22 |
+
) -> np.ndarray:
|
| 23 |
+
"""
|
| 24 |
+
Extract Mel-spectrogram from audio.
|
| 25 |
+
|
| 26 |
+
The Mel-spectrogram is a 2D representation that can reveal:
|
| 27 |
+
- Vertical stripes: temporal glitches in AI voices
|
| 28 |
+
- Horizontal ringing: vocoder artifacts
|
| 29 |
+
- Unnatural smoothness in AI-generated audio
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
audio: Audio waveform
|
| 33 |
+
sr: Sample rate
|
| 34 |
+
n_fft: FFT window size
|
| 35 |
+
hop_length: Hop length
|
| 36 |
+
n_mels: Number of Mel bands
|
| 37 |
+
to_db: Convert to decibels
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
Mel-spectrogram array (n_mels, time)
|
| 41 |
+
"""
|
| 42 |
+
mel_spec = librosa.feature.melspectrogram(
|
| 43 |
+
y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if to_db:
|
| 47 |
+
mel_spec = librosa.power_to_db(mel_spec, ref=np.max)
|
| 48 |
+
|
| 49 |
+
return mel_spec
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def extract_mfcc(
|
| 53 |
+
audio: np.ndarray,
|
| 54 |
+
sr: int = SAMPLE_RATE,
|
| 55 |
+
n_fft: int = N_FFT,
|
| 56 |
+
hop_length: int = HOP_LENGTH,
|
| 57 |
+
n_mfcc: int = N_MFCC
|
| 58 |
+
) -> np.ndarray:
|
| 59 |
+
"""
|
| 60 |
+
Extract Mel-frequency cepstral coefficients.
|
| 61 |
+
|
| 62 |
+
MFCCs are essentially a "thumbprint" of the vocal tract,
|
| 63 |
+
capturing the spectral envelope of the audio.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
audio: Audio waveform
|
| 67 |
+
sr: Sample rate
|
| 68 |
+
n_fft: FFT window size
|
| 69 |
+
hop_length: Hop length
|
| 70 |
+
n_mfcc: Number of MFCCs to extract
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
MFCC array (n_mfcc, time)
|
| 74 |
+
"""
|
| 75 |
+
mfcc = librosa.feature.mfcc(
|
| 76 |
+
y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mfcc=n_mfcc
|
| 77 |
+
)
|
| 78 |
+
return mfcc
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def extract_delta_mfcc(
|
| 82 |
+
mfcc: np.ndarray,
|
| 83 |
+
order: int = 1
|
| 84 |
+
) -> np.ndarray:
|
| 85 |
+
"""
|
| 86 |
+
Extract delta (derivative) MFCCs.
|
| 87 |
+
|
| 88 |
+
Delta MFCCs capture the dynamics of the spectral features,
|
| 89 |
+
which can differ between human and AI voices.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
mfcc: MFCC array
|
| 93 |
+
order: Derivative order (1 for delta, 2 for delta-delta)
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
Delta MFCC array
|
| 97 |
+
"""
|
| 98 |
+
return librosa.feature.delta(mfcc, order=order)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def extract_mfcc_with_deltas(
|
| 102 |
+
audio: np.ndarray,
|
| 103 |
+
sr: int = SAMPLE_RATE,
|
| 104 |
+
n_mfcc: int = N_MFCC
|
| 105 |
+
) -> np.ndarray:
|
| 106 |
+
"""
|
| 107 |
+
Extract MFCCs with first and second-order deltas.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
audio: Audio waveform
|
| 111 |
+
sr: Sample rate
|
| 112 |
+
n_mfcc: Number of MFCCs
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
Stacked array of MFCCs, delta, and delta-delta (3*n_mfcc, time)
|
| 116 |
+
"""
|
| 117 |
+
mfcc = extract_mfcc(audio, sr, n_mfcc=n_mfcc)
|
| 118 |
+
delta = extract_delta_mfcc(mfcc, order=1)
|
| 119 |
+
delta2 = extract_delta_mfcc(mfcc, order=2)
|
| 120 |
+
|
| 121 |
+
return np.vstack([mfcc, delta, delta2])
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def extract_mfcc_features(
|
| 125 |
+
audio: np.ndarray,
|
| 126 |
+
sr: int = SAMPLE_RATE,
|
| 127 |
+
n_mfcc: int = N_MFCC
|
| 128 |
+
) -> Dict[str, float]:
|
| 129 |
+
"""
|
| 130 |
+
Extract MFCC-based features with statistics.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
audio: Audio waveform
|
| 134 |
+
sr: Sample rate
|
| 135 |
+
n_mfcc: Number of MFCCs
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
Dictionary of MFCC statistics
|
| 139 |
+
"""
|
| 140 |
+
mfcc = extract_mfcc(audio, sr, n_mfcc=n_mfcc)
|
| 141 |
+
delta = extract_delta_mfcc(mfcc, order=1)
|
| 142 |
+
|
| 143 |
+
features = {}
|
| 144 |
+
|
| 145 |
+
# Statistics for each MFCC coefficient
|
| 146 |
+
for i in range(n_mfcc):
|
| 147 |
+
features[f"mfcc_{i}_mean"] = float(np.mean(mfcc[i]))
|
| 148 |
+
features[f"mfcc_{i}_std"] = float(np.std(mfcc[i]))
|
| 149 |
+
features[f"delta_mfcc_{i}_mean"] = float(np.mean(delta[i]))
|
| 150 |
+
features[f"delta_mfcc_{i}_std"] = float(np.std(delta[i]))
|
| 151 |
+
|
| 152 |
+
# Global MFCC statistics
|
| 153 |
+
features["mfcc_mean_energy"] = float(np.mean(np.sum(mfcc**2, axis=0)))
|
| 154 |
+
features["mfcc_std_energy"] = float(np.std(np.sum(mfcc**2, axis=0)))
|
| 155 |
+
|
| 156 |
+
return features
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_mfcc_feature_vector(
|
| 160 |
+
audio: np.ndarray,
|
| 161 |
+
sr: int = SAMPLE_RATE,
|
| 162 |
+
n_mfcc: int = N_MFCC
|
| 163 |
+
) -> np.ndarray:
|
| 164 |
+
"""
|
| 165 |
+
Get flattened feature vector from MFCC features.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
audio: Audio waveform
|
| 169 |
+
sr: Sample rate
|
| 170 |
+
n_mfcc: Number of MFCCs
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
1D numpy array of MFCC-based features
|
| 174 |
+
"""
|
| 175 |
+
features = extract_mfcc_features(audio, sr, n_mfcc)
|
| 176 |
+
return np.array(list(features.values()))
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def prepare_spectrogram_for_cnn(
|
| 180 |
+
audio: np.ndarray,
|
| 181 |
+
sr: int = SAMPLE_RATE,
|
| 182 |
+
target_shape: Tuple[int, int] = (128, 128)
|
| 183 |
+
) -> np.ndarray:
|
| 184 |
+
"""
|
| 185 |
+
Prepare Mel-spectrogram for CNN input.
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
audio: Audio waveform
|
| 189 |
+
sr: Sample rate
|
| 190 |
+
target_shape: Target (height, width) for the spectrogram
|
| 191 |
+
|
| 192 |
+
Returns:
|
| 193 |
+
Normalized spectrogram array with shape (1, height, width)
|
| 194 |
+
"""
|
| 195 |
+
mel_spec = extract_mel_spectrogram(audio, sr, n_mels=target_shape[0])
|
| 196 |
+
|
| 197 |
+
# Resize to target width if needed
|
| 198 |
+
if mel_spec.shape[1] > target_shape[1]:
|
| 199 |
+
mel_spec = mel_spec[:, :target_shape[1]]
|
| 200 |
+
elif mel_spec.shape[1] < target_shape[1]:
|
| 201 |
+
padding = target_shape[1] - mel_spec.shape[1]
|
| 202 |
+
mel_spec = np.pad(mel_spec, ((0, 0), (0, padding)), mode='constant')
|
| 203 |
+
|
| 204 |
+
# Normalize to [0, 1]
|
| 205 |
+
mel_spec = (mel_spec - mel_spec.min()) / (mel_spec.max() - mel_spec.min() + 1e-8)
|
| 206 |
+
|
| 207 |
+
# Add channel dimension
|
| 208 |
+
return mel_spec[np.newaxis, :, :]
|
features/prosody.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prosodic Feature Extraction
|
| 3 |
+
Extract F0 (fundamental frequency), jitter, shimmer, and other prosodic features.
|
| 4 |
+
These features capture micro-variations that distinguish human from AI voices.
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
import librosa
|
| 8 |
+
from typing import Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 13 |
+
from config import SAMPLE_RATE, F0_MIN, F0_MAX, HOP_LENGTH
|
| 14 |
+
|
| 15 |
+
# Try to import parselmouth for advanced prosody analysis
|
| 16 |
+
try:
|
| 17 |
+
import parselmouth
|
| 18 |
+
from parselmouth.praat import call
|
| 19 |
+
PARSELMOUTH_AVAILABLE = True
|
| 20 |
+
except ImportError:
|
| 21 |
+
PARSELMOUTH_AVAILABLE = False
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def extract_f0_librosa(
|
| 25 |
+
audio: np.ndarray,
|
| 26 |
+
sr: int = SAMPLE_RATE,
|
| 27 |
+
fmin: float = F0_MIN,
|
| 28 |
+
fmax: float = F0_MAX,
|
| 29 |
+
hop_length: int = HOP_LENGTH
|
| 30 |
+
) -> np.ndarray:
|
| 31 |
+
"""
|
| 32 |
+
Extract fundamental frequency using librosa's pyin algorithm.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
audio: Audio waveform
|
| 36 |
+
sr: Sample rate
|
| 37 |
+
fmin: Minimum frequency
|
| 38 |
+
fmax: Maximum frequency
|
| 39 |
+
hop_length: Hop length
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
F0 contour (with NaN for unvoiced frames)
|
| 43 |
+
"""
|
| 44 |
+
f0, voiced_flag, voiced_probs = librosa.pyin(
|
| 45 |
+
audio, fmin=fmin, fmax=fmax, sr=sr, hop_length=hop_length
|
| 46 |
+
)
|
| 47 |
+
return f0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def extract_f0_parselmouth(
|
| 51 |
+
audio: np.ndarray,
|
| 52 |
+
sr: int = SAMPLE_RATE,
|
| 53 |
+
fmin: float = F0_MIN,
|
| 54 |
+
fmax: float = F0_MAX
|
| 55 |
+
) -> np.ndarray:
|
| 56 |
+
"""
|
| 57 |
+
Extract F0 using Parselmouth/Praat (more accurate for speech).
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
audio: Audio waveform
|
| 61 |
+
sr: Sample rate
|
| 62 |
+
fmin: Minimum frequency
|
| 63 |
+
fmax: Maximum frequency
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
F0 contour
|
| 67 |
+
"""
|
| 68 |
+
if not PARSELMOUTH_AVAILABLE:
|
| 69 |
+
return extract_f0_librosa(audio, sr, fmin, fmax)
|
| 70 |
+
|
| 71 |
+
# Create Parselmouth Sound object
|
| 72 |
+
sound = parselmouth.Sound(audio, sampling_frequency=sr)
|
| 73 |
+
|
| 74 |
+
# Extract pitch
|
| 75 |
+
pitch = call(sound, "To Pitch", 0.0, fmin, fmax)
|
| 76 |
+
|
| 77 |
+
# Get F0 values
|
| 78 |
+
n_frames = call(pitch, "Get number of frames")
|
| 79 |
+
f0 = []
|
| 80 |
+
for i in range(1, n_frames + 1):
|
| 81 |
+
f0_value = call(pitch, "Get value in frame", i, "Hertz")
|
| 82 |
+
f0.append(f0_value if not np.isnan(f0_value) else 0.0)
|
| 83 |
+
|
| 84 |
+
return np.array(f0)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def extract_f0(
|
| 88 |
+
audio: np.ndarray,
|
| 89 |
+
sr: int = SAMPLE_RATE,
|
| 90 |
+
fmin: float = F0_MIN,
|
| 91 |
+
fmax: float = F0_MAX
|
| 92 |
+
) -> np.ndarray:
|
| 93 |
+
"""
|
| 94 |
+
Extract fundamental frequency using best available method.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
audio: Audio waveform
|
| 98 |
+
sr: Sample rate
|
| 99 |
+
fmin: Minimum frequency
|
| 100 |
+
fmax: Maximum frequency
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
F0 contour
|
| 104 |
+
"""
|
| 105 |
+
if PARSELMOUTH_AVAILABLE:
|
| 106 |
+
return extract_f0_parselmouth(audio, sr, fmin, fmax)
|
| 107 |
+
return extract_f0_librosa(audio, sr, fmin, fmax)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def calculate_jitter(f0: np.ndarray) -> Dict[str, float]:
|
| 111 |
+
"""
|
| 112 |
+
Calculate jitter (frequency perturbation) from F0 contour.
|
| 113 |
+
|
| 114 |
+
Jitter measures cycle-to-cycle variations in frequency.
|
| 115 |
+
Human voices have natural micro-perturbations, while AI voices
|
| 116 |
+
are often too smooth or follow rigid mathematical curves.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
f0: F0 contour (NaN/0 for unvoiced)
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
Dictionary with jitter metrics
|
| 123 |
+
"""
|
| 124 |
+
# Filter out unvoiced frames
|
| 125 |
+
f0_voiced = f0[~np.isnan(f0) & (f0 > 0)]
|
| 126 |
+
|
| 127 |
+
if len(f0_voiced) < 2:
|
| 128 |
+
return {
|
| 129 |
+
"jitter_local": 0.0,
|
| 130 |
+
"jitter_local_abs": 0.0,
|
| 131 |
+
"jitter_rap": 0.0,
|
| 132 |
+
"jitter_ppq5": 0.0
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
# Convert to periods
|
| 136 |
+
periods = 1.0 / f0_voiced
|
| 137 |
+
|
| 138 |
+
# Local jitter (relative)
|
| 139 |
+
diffs = np.abs(np.diff(periods))
|
| 140 |
+
jitter_local = float(np.mean(diffs) / np.mean(periods)) if np.mean(periods) > 0 else 0.0
|
| 141 |
+
|
| 142 |
+
# Local jitter (absolute) - in seconds
|
| 143 |
+
jitter_local_abs = float(np.mean(diffs))
|
| 144 |
+
|
| 145 |
+
# RAP (Relative Average Perturbation) - 3-point average
|
| 146 |
+
if len(periods) >= 3:
|
| 147 |
+
rap_diffs = []
|
| 148 |
+
for i in range(1, len(periods) - 1):
|
| 149 |
+
avg = (periods[i-1] + periods[i] + periods[i+1]) / 3
|
| 150 |
+
rap_diffs.append(abs(periods[i] - avg))
|
| 151 |
+
jitter_rap = float(np.mean(rap_diffs) / np.mean(periods)) if np.mean(periods) > 0 else 0.0
|
| 152 |
+
else:
|
| 153 |
+
jitter_rap = jitter_local
|
| 154 |
+
|
| 155 |
+
# PPQ5 (5-point Period Perturbation Quotient)
|
| 156 |
+
if len(periods) >= 5:
|
| 157 |
+
ppq5_diffs = []
|
| 158 |
+
for i in range(2, len(periods) - 2):
|
| 159 |
+
avg = np.mean(periods[i-2:i+3])
|
| 160 |
+
ppq5_diffs.append(abs(periods[i] - avg))
|
| 161 |
+
jitter_ppq5 = float(np.mean(ppq5_diffs) / np.mean(periods)) if np.mean(periods) > 0 else 0.0
|
| 162 |
+
else:
|
| 163 |
+
jitter_ppq5 = jitter_rap
|
| 164 |
+
|
| 165 |
+
return {
|
| 166 |
+
"jitter_local": jitter_local,
|
| 167 |
+
"jitter_local_abs": jitter_local_abs,
|
| 168 |
+
"jitter_rap": jitter_rap,
|
| 169 |
+
"jitter_ppq5": jitter_ppq5
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def calculate_shimmer(
|
| 174 |
+
audio: np.ndarray,
|
| 175 |
+
sr: int = SAMPLE_RATE,
|
| 176 |
+
f0: Optional[np.ndarray] = None
|
| 177 |
+
) -> Dict[str, float]:
|
| 178 |
+
"""
|
| 179 |
+
Calculate shimmer (amplitude perturbation).
|
| 180 |
+
|
| 181 |
+
Shimmer measures cycle-to-cycle variations in amplitude.
|
| 182 |
+
Like jitter, it captures the natural "noise" in human voices.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
audio: Audio waveform
|
| 186 |
+
sr: Sample rate
|
| 187 |
+
f0: Optional precomputed F0 contour
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
Dictionary with shimmer metrics
|
| 191 |
+
"""
|
| 192 |
+
if PARSELMOUTH_AVAILABLE:
|
| 193 |
+
return _calculate_shimmer_parselmouth(audio, sr)
|
| 194 |
+
|
| 195 |
+
# Simplified shimmer calculation without Parselmouth
|
| 196 |
+
return _calculate_shimmer_simple(audio, sr)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _calculate_shimmer_parselmouth(
|
| 200 |
+
audio: np.ndarray,
|
| 201 |
+
sr: int
|
| 202 |
+
) -> Dict[str, float]:
|
| 203 |
+
"""Calculate shimmer using Parselmouth/Praat."""
|
| 204 |
+
sound = parselmouth.Sound(audio, sampling_frequency=sr)
|
| 205 |
+
|
| 206 |
+
try:
|
| 207 |
+
point_process = call(sound, "To PointProcess (periodic, cc)", F0_MIN, F0_MAX)
|
| 208 |
+
|
| 209 |
+
shimmer_local = call(
|
| 210 |
+
[sound, point_process], "Get shimmer (local)", 0.0, 0.0,
|
| 211 |
+
0.0001, 0.02, 1.3, 1.6
|
| 212 |
+
)
|
| 213 |
+
shimmer_local_db = call(
|
| 214 |
+
[sound, point_process], "Get shimmer (local, dB)", 0.0, 0.0,
|
| 215 |
+
0.0001, 0.02, 1.3, 1.6
|
| 216 |
+
)
|
| 217 |
+
shimmer_apq3 = call(
|
| 218 |
+
[sound, point_process], "Get shimmer (apq3)", 0.0, 0.0,
|
| 219 |
+
0.0001, 0.02, 1.3, 1.6
|
| 220 |
+
)
|
| 221 |
+
shimmer_apq5 = call(
|
| 222 |
+
[sound, point_process], "Get shimmer (apq5)", 0.0, 0.0,
|
| 223 |
+
0.0001, 0.02, 1.3, 1.6
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
return {
|
| 227 |
+
"shimmer_local": float(shimmer_local) if not np.isnan(shimmer_local) else 0.0,
|
| 228 |
+
"shimmer_local_db": float(shimmer_local_db) if not np.isnan(shimmer_local_db) else 0.0,
|
| 229 |
+
"shimmer_apq3": float(shimmer_apq3) if not np.isnan(shimmer_apq3) else 0.0,
|
| 230 |
+
"shimmer_apq5": float(shimmer_apq5) if not np.isnan(shimmer_apq5) else 0.0
|
| 231 |
+
}
|
| 232 |
+
except Exception:
|
| 233 |
+
return _calculate_shimmer_simple(audio, sr)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _calculate_shimmer_simple(
|
| 237 |
+
audio: np.ndarray,
|
| 238 |
+
sr: int
|
| 239 |
+
) -> Dict[str, float]:
|
| 240 |
+
"""Simplified shimmer calculation using amplitude envelope."""
|
| 241 |
+
# Compute amplitude envelope
|
| 242 |
+
envelope = np.abs(librosa.effects.preemphasis(audio))
|
| 243 |
+
|
| 244 |
+
# Compute frame-level amplitudes
|
| 245 |
+
frame_length = int(sr * 0.025) # 25ms frames
|
| 246 |
+
hop_length = int(sr * 0.010) # 10ms hop
|
| 247 |
+
|
| 248 |
+
amplitudes = []
|
| 249 |
+
for i in range(0, len(envelope) - frame_length, hop_length):
|
| 250 |
+
frame = envelope[i:i + frame_length]
|
| 251 |
+
amplitudes.append(np.max(frame))
|
| 252 |
+
|
| 253 |
+
amplitudes = np.array(amplitudes)
|
| 254 |
+
|
| 255 |
+
if len(amplitudes) < 2:
|
| 256 |
+
return {
|
| 257 |
+
"shimmer_local": 0.0,
|
| 258 |
+
"shimmer_local_db": 0.0,
|
| 259 |
+
"shimmer_apq3": 0.0,
|
| 260 |
+
"shimmer_apq5": 0.0
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
# Local shimmer
|
| 264 |
+
diffs = np.abs(np.diff(amplitudes))
|
| 265 |
+
shimmer_local = float(np.mean(diffs) / np.mean(amplitudes)) if np.mean(amplitudes) > 0 else 0.0
|
| 266 |
+
|
| 267 |
+
# Shimmer in dB
|
| 268 |
+
shimmer_db = 20 * np.log10(1 + shimmer_local) if shimmer_local > 0 else 0.0
|
| 269 |
+
|
| 270 |
+
return {
|
| 271 |
+
"shimmer_local": shimmer_local,
|
| 272 |
+
"shimmer_local_db": float(shimmer_db),
|
| 273 |
+
"shimmer_apq3": shimmer_local, # Simplified
|
| 274 |
+
"shimmer_apq5": shimmer_local # Simplified
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def extract_prosodic_features(
|
| 279 |
+
audio: np.ndarray,
|
| 280 |
+
sr: int = SAMPLE_RATE
|
| 281 |
+
) -> Dict[str, float]:
|
| 282 |
+
"""
|
| 283 |
+
Extract all prosodic features from audio.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
audio: Audio waveform
|
| 287 |
+
sr: Sample rate
|
| 288 |
+
|
| 289 |
+
Returns:
|
| 290 |
+
Dictionary of prosodic features
|
| 291 |
+
"""
|
| 292 |
+
features = {}
|
| 293 |
+
|
| 294 |
+
# Extract F0
|
| 295 |
+
f0 = extract_f0(audio, sr)
|
| 296 |
+
f0_voiced = f0[~np.isnan(f0) & (f0 > 0)]
|
| 297 |
+
|
| 298 |
+
# F0 statistics
|
| 299 |
+
if len(f0_voiced) > 0:
|
| 300 |
+
features["f0_mean"] = float(np.mean(f0_voiced))
|
| 301 |
+
features["f0_std"] = float(np.std(f0_voiced))
|
| 302 |
+
features["f0_max"] = float(np.max(f0_voiced))
|
| 303 |
+
features["f0_min"] = float(np.min(f0_voiced))
|
| 304 |
+
features["f0_range"] = float(np.max(f0_voiced) - np.min(f0_voiced))
|
| 305 |
+
# Coefficient of variation - key indicator of naturalness
|
| 306 |
+
features["f0_cv"] = float(np.std(f0_voiced) / np.mean(f0_voiced)) if np.mean(f0_voiced) > 0 else 0.0
|
| 307 |
+
else:
|
| 308 |
+
features["f0_mean"] = 0.0
|
| 309 |
+
features["f0_std"] = 0.0
|
| 310 |
+
features["f0_max"] = 0.0
|
| 311 |
+
features["f0_min"] = 0.0
|
| 312 |
+
features["f0_range"] = 0.0
|
| 313 |
+
features["f0_cv"] = 0.0
|
| 314 |
+
|
| 315 |
+
# Jitter features
|
| 316 |
+
jitter = calculate_jitter(f0)
|
| 317 |
+
features.update(jitter)
|
| 318 |
+
|
| 319 |
+
# Shimmer features
|
| 320 |
+
shimmer = calculate_shimmer(audio, sr, f0)
|
| 321 |
+
features.update(shimmer)
|
| 322 |
+
|
| 323 |
+
# Harmonics-to-Noise Ratio (HNR) - simplified version
|
| 324 |
+
features["hnr"] = _calculate_hnr_simple(audio, sr)
|
| 325 |
+
|
| 326 |
+
return features
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _calculate_hnr_simple(audio: np.ndarray, sr: int) -> float:
|
| 330 |
+
"""Calculate simplified Harmonics-to-Noise Ratio."""
|
| 331 |
+
try:
|
| 332 |
+
# Use librosa's harmonic-percussive separation
|
| 333 |
+
harmonic, percussive = librosa.effects.hpss(audio)
|
| 334 |
+
|
| 335 |
+
harmonic_energy = np.sum(harmonic ** 2)
|
| 336 |
+
noise_energy = np.sum(percussive ** 2)
|
| 337 |
+
|
| 338 |
+
if noise_energy > 0:
|
| 339 |
+
hnr = 10 * np.log10(harmonic_energy / noise_energy)
|
| 340 |
+
return float(np.clip(hnr, -20, 40)) # Clip to reasonable range
|
| 341 |
+
return 0.0
|
| 342 |
+
except Exception:
|
| 343 |
+
return 0.0
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def get_prosodic_feature_vector(
|
| 347 |
+
audio: np.ndarray,
|
| 348 |
+
sr: int = SAMPLE_RATE
|
| 349 |
+
) -> np.ndarray:
|
| 350 |
+
"""
|
| 351 |
+
Get flattened feature vector from prosodic features.
|
| 352 |
+
|
| 353 |
+
Args:
|
| 354 |
+
audio: Audio waveform
|
| 355 |
+
sr: Sample rate
|
| 356 |
+
|
| 357 |
+
Returns:
|
| 358 |
+
1D numpy array of prosodic features
|
| 359 |
+
"""
|
| 360 |
+
features = extract_prosodic_features(audio, sr)
|
| 361 |
+
return np.array(list(features.values()))
|
features/spectral.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Spectral Feature Extraction
|
| 3 |
+
Extract spectral centroid, rolloff, bandwidth, and other spectral features.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
import librosa
|
| 7 |
+
from typing import Dict, Optional
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 12 |
+
from config import SAMPLE_RATE, N_FFT, HOP_LENGTH, ROLLOFF_PERCENT
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_spectral_centroid(
|
| 16 |
+
audio: np.ndarray,
|
| 17 |
+
sr: int = SAMPLE_RATE,
|
| 18 |
+
n_fft: int = N_FFT,
|
| 19 |
+
hop_length: int = HOP_LENGTH
|
| 20 |
+
) -> np.ndarray:
|
| 21 |
+
"""
|
| 22 |
+
Extract spectral centroid - the "center of mass" of the spectrum.
|
| 23 |
+
|
| 24 |
+
AI voices often have a more static/stable centroid compared to human voices
|
| 25 |
+
which show more natural variation.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
audio: Audio waveform
|
| 29 |
+
sr: Sample rate
|
| 30 |
+
n_fft: FFT window size
|
| 31 |
+
hop_length: Hop length
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Spectral centroid values over time
|
| 35 |
+
"""
|
| 36 |
+
centroid = librosa.feature.spectral_centroid(
|
| 37 |
+
y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length
|
| 38 |
+
)
|
| 39 |
+
return centroid[0]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def extract_spectral_rolloff(
|
| 43 |
+
audio: np.ndarray,
|
| 44 |
+
sr: int = SAMPLE_RATE,
|
| 45 |
+
n_fft: int = N_FFT,
|
| 46 |
+
hop_length: int = HOP_LENGTH,
|
| 47 |
+
roll_percent: float = ROLLOFF_PERCENT
|
| 48 |
+
) -> np.ndarray:
|
| 49 |
+
"""
|
| 50 |
+
Extract spectral rolloff - frequency below which a percentage of energy lies.
|
| 51 |
+
|
| 52 |
+
AI-generated audio often shows sharp cutoffs around certain frequencies
|
| 53 |
+
(e.g., vocoder artifacts).
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
audio: Audio waveform
|
| 57 |
+
sr: Sample rate
|
| 58 |
+
n_fft: FFT window size
|
| 59 |
+
hop_length: Hop length
|
| 60 |
+
roll_percent: Energy percentage threshold (0.85 = 85%)
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
Spectral rolloff frequencies over time
|
| 64 |
+
"""
|
| 65 |
+
rolloff = librosa.feature.spectral_rolloff(
|
| 66 |
+
y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, roll_percent=roll_percent
|
| 67 |
+
)
|
| 68 |
+
return rolloff[0]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def extract_spectral_bandwidth(
|
| 72 |
+
audio: np.ndarray,
|
| 73 |
+
sr: int = SAMPLE_RATE,
|
| 74 |
+
n_fft: int = N_FFT,
|
| 75 |
+
hop_length: int = HOP_LENGTH
|
| 76 |
+
) -> np.ndarray:
|
| 77 |
+
"""
|
| 78 |
+
Extract spectral bandwidth - weighted standard deviation of frequencies.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
audio: Audio waveform
|
| 82 |
+
sr: Sample rate
|
| 83 |
+
n_fft: FFT window size
|
| 84 |
+
hop_length: Hop length
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
Spectral bandwidth values over time
|
| 88 |
+
"""
|
| 89 |
+
bandwidth = librosa.feature.spectral_bandwidth(
|
| 90 |
+
y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length
|
| 91 |
+
)
|
| 92 |
+
return bandwidth[0]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def extract_spectral_flatness(
|
| 96 |
+
audio: np.ndarray,
|
| 97 |
+
n_fft: int = N_FFT,
|
| 98 |
+
hop_length: int = HOP_LENGTH
|
| 99 |
+
) -> np.ndarray:
|
| 100 |
+
"""
|
| 101 |
+
Extract spectral flatness - measure of how noise-like vs tonal the sound is.
|
| 102 |
+
|
| 103 |
+
AI voices may show different flatness patterns than human voices.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
audio: Audio waveform
|
| 107 |
+
n_fft: FFT window size
|
| 108 |
+
hop_length: Hop length
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
Spectral flatness values over time
|
| 112 |
+
"""
|
| 113 |
+
flatness = librosa.feature.spectral_flatness(
|
| 114 |
+
y=audio, n_fft=n_fft, hop_length=hop_length
|
| 115 |
+
)
|
| 116 |
+
return flatness[0]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def extract_spectral_contrast(
|
| 120 |
+
audio: np.ndarray,
|
| 121 |
+
sr: int = SAMPLE_RATE,
|
| 122 |
+
n_fft: int = N_FFT,
|
| 123 |
+
hop_length: int = HOP_LENGTH,
|
| 124 |
+
n_bands: int = 6
|
| 125 |
+
) -> np.ndarray:
|
| 126 |
+
"""
|
| 127 |
+
Extract spectral contrast - difference between peaks and valleys in spectrum.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
audio: Audio waveform
|
| 131 |
+
sr: Sample rate
|
| 132 |
+
n_fft: FFT window size
|
| 133 |
+
hop_length: Hop length
|
| 134 |
+
n_bands: Number of frequency bands
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
Spectral contrast matrix (n_bands+1, time)
|
| 138 |
+
"""
|
| 139 |
+
contrast = librosa.feature.spectral_contrast(
|
| 140 |
+
y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_bands=n_bands
|
| 141 |
+
)
|
| 142 |
+
return contrast
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def extract_zero_crossing_rate(
|
| 146 |
+
audio: np.ndarray,
|
| 147 |
+
hop_length: int = HOP_LENGTH
|
| 148 |
+
) -> np.ndarray:
|
| 149 |
+
"""
|
| 150 |
+
Extract zero-crossing rate - rate at which signal changes sign.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
audio: Audio waveform
|
| 154 |
+
hop_length: Hop length
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
Zero-crossing rate values over time
|
| 158 |
+
"""
|
| 159 |
+
zcr = librosa.feature.zero_crossing_rate(y=audio, hop_length=hop_length)
|
| 160 |
+
return zcr[0]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def extract_spectral_features(
|
| 164 |
+
audio: np.ndarray,
|
| 165 |
+
sr: int = SAMPLE_RATE,
|
| 166 |
+
n_fft: int = N_FFT,
|
| 167 |
+
hop_length: int = HOP_LENGTH
|
| 168 |
+
) -> Dict[str, np.ndarray]:
|
| 169 |
+
"""
|
| 170 |
+
Extract all spectral features from audio.
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
audio: Audio waveform
|
| 174 |
+
sr: Sample rate
|
| 175 |
+
n_fft: FFT window size
|
| 176 |
+
hop_length: Hop length
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
Dictionary of spectral features with statistics
|
| 180 |
+
"""
|
| 181 |
+
# Extract raw features
|
| 182 |
+
centroid = extract_spectral_centroid(audio, sr, n_fft, hop_length)
|
| 183 |
+
rolloff = extract_spectral_rolloff(audio, sr, n_fft, hop_length)
|
| 184 |
+
bandwidth = extract_spectral_bandwidth(audio, sr, n_fft, hop_length)
|
| 185 |
+
flatness = extract_spectral_flatness(audio, n_fft, hop_length)
|
| 186 |
+
zcr = extract_zero_crossing_rate(audio, hop_length)
|
| 187 |
+
|
| 188 |
+
# Compute statistics for each feature
|
| 189 |
+
features = {}
|
| 190 |
+
|
| 191 |
+
for name, values in [
|
| 192 |
+
("centroid", centroid),
|
| 193 |
+
("rolloff", rolloff),
|
| 194 |
+
("bandwidth", bandwidth),
|
| 195 |
+
("flatness", flatness),
|
| 196 |
+
("zcr", zcr)
|
| 197 |
+
]:
|
| 198 |
+
features[f"{name}_mean"] = float(np.mean(values))
|
| 199 |
+
features[f"{name}_std"] = float(np.std(values))
|
| 200 |
+
features[f"{name}_max"] = float(np.max(values))
|
| 201 |
+
features[f"{name}_min"] = float(np.min(values))
|
| 202 |
+
# Variation coefficient (indicator of stability)
|
| 203 |
+
if np.mean(values) != 0:
|
| 204 |
+
features[f"{name}_cv"] = float(np.std(values) / np.mean(values))
|
| 205 |
+
else:
|
| 206 |
+
features[f"{name}_cv"] = 0.0
|
| 207 |
+
|
| 208 |
+
return features
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def get_spectral_feature_vector(
|
| 212 |
+
audio: np.ndarray,
|
| 213 |
+
sr: int = SAMPLE_RATE
|
| 214 |
+
) -> np.ndarray:
|
| 215 |
+
"""
|
| 216 |
+
Get flattened feature vector from spectral features.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
audio: Audio waveform
|
| 220 |
+
sr: Sample rate
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
1D numpy array of spectral features
|
| 224 |
+
"""
|
| 225 |
+
features = extract_spectral_features(audio, sr)
|
| 226 |
+
return np.array(list(features.values()))
|
main.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VocalSense - AI Voice Detection System
|
| 3 |
+
Main entry point for CLI and application.
|
| 4 |
+
"""
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
# Add project root to path
|
| 9 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
"""Main entry point."""
|
| 14 |
+
import argparse
|
| 15 |
+
|
| 16 |
+
parser = argparse.ArgumentParser(
|
| 17 |
+
description="VocalSense - AI Voice Detection System",
|
| 18 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 19 |
+
epilog="""
|
| 20 |
+
Examples:
|
| 21 |
+
# Start the API server
|
| 22 |
+
python main.py serve --port 8000
|
| 23 |
+
|
| 24 |
+
# Analyze a single audio file
|
| 25 |
+
python main.py analyze --file audio.wav --language English
|
| 26 |
+
|
| 27 |
+
# Extract features from audio
|
| 28 |
+
python main.py features --file audio.wav
|
| 29 |
+
|
| 30 |
+
# Train the model on your dataset
|
| 31 |
+
python main.py train --epochs 50 --model random_forest
|
| 32 |
+
"""
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
| 36 |
+
|
| 37 |
+
# Serve command
|
| 38 |
+
serve_parser = subparsers.add_parser("serve", help="Start the API server")
|
| 39 |
+
serve_parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
|
| 40 |
+
serve_parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
|
| 41 |
+
serve_parser.add_argument("--reload", action="store_true", help="Enable auto-reload")
|
| 42 |
+
|
| 43 |
+
# Analyze command
|
| 44 |
+
analyze_parser = subparsers.add_parser("analyze", help="Analyze an audio file")
|
| 45 |
+
analyze_parser.add_argument("--file", "-f", required=True, help="Path to audio file")
|
| 46 |
+
analyze_parser.add_argument(
|
| 47 |
+
"--language", "-l",
|
| 48 |
+
default="English",
|
| 49 |
+
choices=["Hindi", "Tamil", "Telugu", "Malayalam", "English"],
|
| 50 |
+
help="Language of the audio"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Batch command - analyze multiple files
|
| 54 |
+
batch_parser = subparsers.add_parser("batch", help="Analyze all audio files in a folder")
|
| 55 |
+
batch_parser.add_argument("--folder", "-d", required=True, help="Path to folder with audio files")
|
| 56 |
+
batch_parser.add_argument(
|
| 57 |
+
"--language", "-l",
|
| 58 |
+
default="English",
|
| 59 |
+
choices=["Hindi", "Tamil", "Telugu", "Malayalam", "English"],
|
| 60 |
+
help="Language of the audio"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Features command
|
| 64 |
+
features_parser = subparsers.add_parser("features", help="Extract features from audio")
|
| 65 |
+
features_parser.add_argument("--file", "-f", required=True, help="Path to audio file")
|
| 66 |
+
features_parser.add_argument("--output", "-o", help="Output JSON file")
|
| 67 |
+
|
| 68 |
+
# Train command
|
| 69 |
+
train_parser = subparsers.add_parser("train", help="Train the AI voice detection model")
|
| 70 |
+
train_parser.add_argument("--epochs", "-e", type=int, default=50, help="Number of epochs")
|
| 71 |
+
train_parser.add_argument(
|
| 72 |
+
"--model", "-m",
|
| 73 |
+
default="random_forest",
|
| 74 |
+
choices=["random_forest", "svm"],
|
| 75 |
+
help="Model type to train"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
args = parser.parse_args()
|
| 79 |
+
|
| 80 |
+
if args.command == "serve":
|
| 81 |
+
run_server(args.host, args.port, args.reload)
|
| 82 |
+
elif args.command == "analyze":
|
| 83 |
+
analyze_file(args.file, args.language)
|
| 84 |
+
elif args.command == "batch":
|
| 85 |
+
batch_analyze(args.folder, args.language)
|
| 86 |
+
elif args.command == "features":
|
| 87 |
+
extract_features_cli(args.file, args.output)
|
| 88 |
+
elif args.command == "train":
|
| 89 |
+
run_training(args.model, args.epochs)
|
| 90 |
+
else:
|
| 91 |
+
parser.print_help()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def run_server(host: str, port: int, reload: bool):
|
| 95 |
+
"""Start the FastAPI server."""
|
| 96 |
+
import uvicorn
|
| 97 |
+
print(f"Starting VocalSense API server on {host}:{port}...")
|
| 98 |
+
uvicorn.run(
|
| 99 |
+
"api.app:app",
|
| 100 |
+
host=host,
|
| 101 |
+
port=port,
|
| 102 |
+
reload=reload
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def analyze_file(file_path: str, language: str):
|
| 107 |
+
"""Analyze a single audio file."""
|
| 108 |
+
import json
|
| 109 |
+
from api.detector import get_detector
|
| 110 |
+
|
| 111 |
+
path = Path(file_path)
|
| 112 |
+
if not path.exists():
|
| 113 |
+
print(f"Error: File not found: {file_path}")
|
| 114 |
+
sys.exit(1)
|
| 115 |
+
|
| 116 |
+
print(f"Analyzing: {path.name}")
|
| 117 |
+
print(f"Language: {language}")
|
| 118 |
+
print("-" * 40)
|
| 119 |
+
|
| 120 |
+
detector = get_detector()
|
| 121 |
+
result = detector.analyze_file(file_path, language)
|
| 122 |
+
|
| 123 |
+
print(f"Status: {result['status']}")
|
| 124 |
+
print(f"Classification: {result['classification']}")
|
| 125 |
+
print(f"Confidence: {result['confidenceScore']:.2%}")
|
| 126 |
+
print(f"Explanation: {result['explanation']}")
|
| 127 |
+
|
| 128 |
+
# Show detailed scores if available
|
| 129 |
+
if 'details' in result:
|
| 130 |
+
details = result['details']
|
| 131 |
+
print("-" * 40)
|
| 132 |
+
print("Detailed Analysis:")
|
| 133 |
+
if details.get('model_score') is not None:
|
| 134 |
+
print(f" Model Score: {details['model_score']:.2%}")
|
| 135 |
+
if details.get('heuristic_score') is not None:
|
| 136 |
+
print(f" Heuristic Score: {details['heuristic_score']:.2%}")
|
| 137 |
+
print(f" Final Score: {details['final_score']:.2%}")
|
| 138 |
+
print(f" Method: {result.get('method', 'unknown')}")
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def batch_analyze(folder_path: str, language: str):
|
| 142 |
+
"""Analyze all audio files in a folder."""
|
| 143 |
+
from api.detector import get_detector
|
| 144 |
+
|
| 145 |
+
folder = Path(folder_path)
|
| 146 |
+
if not folder.exists():
|
| 147 |
+
print(f"Error: Folder not found: {folder_path}")
|
| 148 |
+
sys.exit(1)
|
| 149 |
+
|
| 150 |
+
# Find all audio files
|
| 151 |
+
extensions = ['.wav', '.mp3', '.m4a', '.ogg', '.flac']
|
| 152 |
+
audio_files = []
|
| 153 |
+
for ext in extensions:
|
| 154 |
+
audio_files.extend(folder.glob(f"*{ext}"))
|
| 155 |
+
|
| 156 |
+
if not audio_files:
|
| 157 |
+
print(f"No audio files found in: {folder_path}")
|
| 158 |
+
sys.exit(1)
|
| 159 |
+
|
| 160 |
+
print(f"Found {len(audio_files)} audio files")
|
| 161 |
+
print(f"Language: {language}")
|
| 162 |
+
print("=" * 60)
|
| 163 |
+
|
| 164 |
+
detector = get_detector()
|
| 165 |
+
|
| 166 |
+
ai_count = 0
|
| 167 |
+
human_count = 0
|
| 168 |
+
results = []
|
| 169 |
+
|
| 170 |
+
for audio_file in audio_files:
|
| 171 |
+
try:
|
| 172 |
+
result = detector.analyze_file(str(audio_file), language)
|
| 173 |
+
classification = result['classification']
|
| 174 |
+
confidence = result['confidenceScore']
|
| 175 |
+
|
| 176 |
+
if classification == "AI_GENERATED":
|
| 177 |
+
ai_count += 1
|
| 178 |
+
status = "[AI]"
|
| 179 |
+
else:
|
| 180 |
+
human_count += 1
|
| 181 |
+
status = "[HUMAN]"
|
| 182 |
+
|
| 183 |
+
print(f"{status} ({confidence:.0%}) - {audio_file.name}")
|
| 184 |
+
results.append(result)
|
| 185 |
+
|
| 186 |
+
except Exception as e:
|
| 187 |
+
print(f"[ERROR] {audio_file.name}: {e}")
|
| 188 |
+
|
| 189 |
+
# Summary
|
| 190 |
+
print("=" * 60)
|
| 191 |
+
print("SUMMARY:")
|
| 192 |
+
print(f" Total files: {len(audio_files)}")
|
| 193 |
+
print(f" AI detected: {ai_count}")
|
| 194 |
+
print(f" Human detected: {human_count}")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def extract_features_cli(file_path: str, output_path: str = None):
|
| 198 |
+
"""Extract and display features from audio."""
|
| 199 |
+
import json
|
| 200 |
+
from utils.audio import load_audio, preprocess_audio
|
| 201 |
+
from features.spectral import extract_spectral_features
|
| 202 |
+
from features.mfcc import extract_mfcc_features
|
| 203 |
+
from features.prosody import extract_prosodic_features
|
| 204 |
+
from config import SAMPLE_RATE
|
| 205 |
+
|
| 206 |
+
path = Path(file_path)
|
| 207 |
+
if not path.exists():
|
| 208 |
+
print(f"Error: File not found: {file_path}")
|
| 209 |
+
sys.exit(1)
|
| 210 |
+
|
| 211 |
+
print(f"Extracting features from: {path.name}")
|
| 212 |
+
print("-" * 40)
|
| 213 |
+
|
| 214 |
+
# Load and preprocess
|
| 215 |
+
audio, sr = load_audio(file_path, sr=SAMPLE_RATE)
|
| 216 |
+
audio = preprocess_audio(audio, sr)
|
| 217 |
+
|
| 218 |
+
# Extract features
|
| 219 |
+
features = {
|
| 220 |
+
"spectral": extract_spectral_features(audio, sr),
|
| 221 |
+
"mfcc": {k: v for k, v in extract_mfcc_features(audio, sr).items()
|
| 222 |
+
if "mfcc_0" in k or "mfcc_1" in k or "energy" in k},
|
| 223 |
+
"prosody": extract_prosodic_features(audio, sr)
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
if output_path:
|
| 227 |
+
with open(output_path, "w") as f:
|
| 228 |
+
json.dump(features, f, indent=2)
|
| 229 |
+
print(f"Features saved to: {output_path}")
|
| 230 |
+
else:
|
| 231 |
+
print("\nSpectral Features:")
|
| 232 |
+
for k, v in features["spectral"].items():
|
| 233 |
+
print(f" {k}: {v:.4f}")
|
| 234 |
+
|
| 235 |
+
print("\nProsodic Features:")
|
| 236 |
+
for k, v in features["prosody"].items():
|
| 237 |
+
print(f" {k}: {v:.4f}")
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def run_training(model_type: str, epochs: int):
|
| 241 |
+
"""Train the AI voice detection model."""
|
| 242 |
+
from training.trainer import train_full_pipeline
|
| 243 |
+
|
| 244 |
+
print("Starting VocalSense Training...")
|
| 245 |
+
print(f"Model: {model_type}")
|
| 246 |
+
print(f"Epochs: {epochs}")
|
| 247 |
+
|
| 248 |
+
try:
|
| 249 |
+
model, metrics = train_full_pipeline(
|
| 250 |
+
model_type=model_type,
|
| 251 |
+
epochs=epochs
|
| 252 |
+
)
|
| 253 |
+
except FileNotFoundError as e:
|
| 254 |
+
print(f"\nError: {e}")
|
| 255 |
+
print("\nMake sure you have audio files in:")
|
| 256 |
+
print(" - data/real/ (human voice samples)")
|
| 257 |
+
print(" - data/fake/ (AI/TTS voice samples)")
|
| 258 |
+
sys.exit(1)
|
| 259 |
+
except ValueError as e:
|
| 260 |
+
print(f"\nError: {e}")
|
| 261 |
+
sys.exit(1)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
main()
|
models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Models module
|
models/cnn.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CNN Model for Spectrogram-based Classification
|
| 3 |
+
Deep learning approach using Mel-spectrograms as 2D images.
|
| 4 |
+
Best for high accuracy and detecting patterns humans can't define.
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Tuple, Optional, Union
|
| 12 |
+
|
| 13 |
+
import sys
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 15 |
+
from config import CNN_INPUT_CHANNELS, CNN_HIDDEN_DIMS, CNN_DROPOUT, MODELS_DIR
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SpectrogramCNN(nn.Module):
|
| 19 |
+
"""
|
| 20 |
+
4-layer CNN for Mel-spectrogram classification.
|
| 21 |
+
|
| 22 |
+
Architecture:
|
| 23 |
+
- 4 convolutional blocks (conv + batch norm + relu + maxpool)
|
| 24 |
+
- Global average pooling
|
| 25 |
+
- Fully connected layers with dropout
|
| 26 |
+
- Binary output (human vs AI)
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
input_channels: int = CNN_INPUT_CHANNELS,
|
| 32 |
+
hidden_dims: list = None,
|
| 33 |
+
dropout: float = CNN_DROPOUT,
|
| 34 |
+
input_height: int = 128,
|
| 35 |
+
input_width: int = 128
|
| 36 |
+
):
|
| 37 |
+
"""
|
| 38 |
+
Initialize the CNN.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
input_channels: Number of input channels (1 for mono)
|
| 42 |
+
hidden_dims: List of hidden dimensions for conv layers
|
| 43 |
+
dropout: Dropout rate
|
| 44 |
+
input_height: Height of input spectrogram (n_mels)
|
| 45 |
+
input_width: Width of input spectrogram (time frames)
|
| 46 |
+
"""
|
| 47 |
+
super().__init__()
|
| 48 |
+
|
| 49 |
+
if hidden_dims is None:
|
| 50 |
+
hidden_dims = CNN_HIDDEN_DIMS # [32, 64, 128, 256]
|
| 51 |
+
|
| 52 |
+
self.hidden_dims = hidden_dims
|
| 53 |
+
self.dropout_rate = dropout
|
| 54 |
+
|
| 55 |
+
# Convolutional blocks
|
| 56 |
+
layers = []
|
| 57 |
+
in_channels = input_channels
|
| 58 |
+
|
| 59 |
+
for out_channels in hidden_dims:
|
| 60 |
+
layers.extend([
|
| 61 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
|
| 62 |
+
nn.BatchNorm2d(out_channels),
|
| 63 |
+
nn.ReLU(inplace=True),
|
| 64 |
+
nn.MaxPool2d(kernel_size=2, stride=2)
|
| 65 |
+
])
|
| 66 |
+
in_channels = out_channels
|
| 67 |
+
|
| 68 |
+
self.conv_layers = nn.Sequential(*layers)
|
| 69 |
+
|
| 70 |
+
# Calculate feature size after convolutions
|
| 71 |
+
# Each maxpool reduces size by 2, we have len(hidden_dims) pools
|
| 72 |
+
reduced_height = input_height // (2 ** len(hidden_dims))
|
| 73 |
+
reduced_width = input_width // (2 ** len(hidden_dims))
|
| 74 |
+
feature_size = hidden_dims[-1] * reduced_height * reduced_width
|
| 75 |
+
|
| 76 |
+
# Fully connected layers
|
| 77 |
+
self.fc_layers = nn.Sequential(
|
| 78 |
+
nn.Flatten(),
|
| 79 |
+
nn.Linear(feature_size, 512),
|
| 80 |
+
nn.ReLU(inplace=True),
|
| 81 |
+
nn.Dropout(dropout),
|
| 82 |
+
nn.Linear(512, 128),
|
| 83 |
+
nn.ReLU(inplace=True),
|
| 84 |
+
nn.Dropout(dropout),
|
| 85 |
+
nn.Linear(128, 2) # Binary classification
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Initialize weights
|
| 89 |
+
self._init_weights()
|
| 90 |
+
|
| 91 |
+
def _init_weights(self):
|
| 92 |
+
"""Initialize weights using He initialization."""
|
| 93 |
+
for m in self.modules():
|
| 94 |
+
if isinstance(m, nn.Conv2d):
|
| 95 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 96 |
+
if m.bias is not None:
|
| 97 |
+
nn.init.constant_(m.bias, 0)
|
| 98 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 99 |
+
nn.init.constant_(m.weight, 1)
|
| 100 |
+
nn.init.constant_(m.bias, 0)
|
| 101 |
+
elif isinstance(m, nn.Linear):
|
| 102 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 103 |
+
nn.init.constant_(m.bias, 0)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 106 |
+
"""
|
| 107 |
+
Forward pass.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
x: Input tensor (batch, channels, height, width)
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
Logits tensor (batch, 2)
|
| 114 |
+
"""
|
| 115 |
+
x = self.conv_layers(x)
|
| 116 |
+
x = self.fc_layers(x)
|
| 117 |
+
return x
|
| 118 |
+
|
| 119 |
+
def predict_proba(self, x: torch.Tensor) -> torch.Tensor:
|
| 120 |
+
"""
|
| 121 |
+
Get probability predictions.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
x: Input tensor
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
Probabilities tensor (batch, 2)
|
| 128 |
+
"""
|
| 129 |
+
logits = self.forward(x)
|
| 130 |
+
return F.softmax(logits, dim=1)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class CNNClassifier:
|
| 134 |
+
"""
|
| 135 |
+
Wrapper class for CNN-based classification.
|
| 136 |
+
Handles training, prediction, and model persistence.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def __init__(
|
| 140 |
+
self,
|
| 141 |
+
input_height: int = 128,
|
| 142 |
+
input_width: int = 128,
|
| 143 |
+
device: Optional[str] = None
|
| 144 |
+
):
|
| 145 |
+
"""
|
| 146 |
+
Initialize the CNN classifier.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
input_height: Spectrogram height
|
| 150 |
+
input_width: Spectrogram width
|
| 151 |
+
device: Device to use ('cuda', 'cpu', or None for auto)
|
| 152 |
+
"""
|
| 153 |
+
self.input_height = input_height
|
| 154 |
+
self.input_width = input_width
|
| 155 |
+
|
| 156 |
+
if device is None:
|
| 157 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 158 |
+
else:
|
| 159 |
+
self.device = torch.device(device)
|
| 160 |
+
|
| 161 |
+
self.model = SpectrogramCNN(
|
| 162 |
+
input_height=input_height,
|
| 163 |
+
input_width=input_width
|
| 164 |
+
).to(self.device)
|
| 165 |
+
|
| 166 |
+
self.is_fitted = False
|
| 167 |
+
|
| 168 |
+
def predict(
|
| 169 |
+
self,
|
| 170 |
+
spectrograms: np.ndarray
|
| 171 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 172 |
+
"""
|
| 173 |
+
Predict labels and probabilities.
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
spectrograms: Array of spectrograms (n_samples, height, width)
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
Tuple of (predictions, probabilities)
|
| 180 |
+
"""
|
| 181 |
+
self.model.eval()
|
| 182 |
+
|
| 183 |
+
# Add channel dimension if needed
|
| 184 |
+
if spectrograms.ndim == 3:
|
| 185 |
+
spectrograms = spectrograms[:, np.newaxis, :, :]
|
| 186 |
+
|
| 187 |
+
# Convert to tensor
|
| 188 |
+
x = torch.FloatTensor(spectrograms).to(self.device)
|
| 189 |
+
|
| 190 |
+
with torch.no_grad():
|
| 191 |
+
probs = self.model.predict_proba(x)
|
| 192 |
+
probs = probs.cpu().numpy()
|
| 193 |
+
|
| 194 |
+
predictions = np.argmax(probs, axis=1)
|
| 195 |
+
ai_probabilities = probs[:, 1] # P(AI)
|
| 196 |
+
|
| 197 |
+
return predictions, ai_probabilities
|
| 198 |
+
|
| 199 |
+
def predict_single(
|
| 200 |
+
self,
|
| 201 |
+
spectrogram: np.ndarray
|
| 202 |
+
) -> Tuple[int, float]:
|
| 203 |
+
"""
|
| 204 |
+
Predict for a single spectrogram.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
spectrogram: Single spectrogram (height, width) or (1, height, width)
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
Tuple of (prediction, probability)
|
| 211 |
+
"""
|
| 212 |
+
if spectrogram.ndim == 2:
|
| 213 |
+
spectrogram = spectrogram[np.newaxis, :, :]
|
| 214 |
+
|
| 215 |
+
predictions, probabilities = self.predict(spectrogram)
|
| 216 |
+
return int(predictions[0]), float(probabilities[0])
|
| 217 |
+
|
| 218 |
+
def save(self, path: Optional[Union[str, Path]] = None) -> Path:
|
| 219 |
+
"""
|
| 220 |
+
Save the trained model.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
path: Optional save path
|
| 224 |
+
|
| 225 |
+
Returns:
|
| 226 |
+
Path where model was saved
|
| 227 |
+
"""
|
| 228 |
+
if path is None:
|
| 229 |
+
path = MODELS_DIR / "cnn_model.pth"
|
| 230 |
+
|
| 231 |
+
path = Path(path)
|
| 232 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 233 |
+
|
| 234 |
+
torch.save({
|
| 235 |
+
"model_state_dict": self.model.state_dict(),
|
| 236 |
+
"input_height": self.input_height,
|
| 237 |
+
"input_width": self.input_width,
|
| 238 |
+
"is_fitted": self.is_fitted
|
| 239 |
+
}, path)
|
| 240 |
+
|
| 241 |
+
return path
|
| 242 |
+
|
| 243 |
+
@classmethod
|
| 244 |
+
def load(cls, path: Union[str, Path], device: Optional[str] = None) -> "CNNClassifier":
|
| 245 |
+
"""
|
| 246 |
+
Load a trained model.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
path: Path to saved model
|
| 250 |
+
device: Device to load to
|
| 251 |
+
|
| 252 |
+
Returns:
|
| 253 |
+
Loaded classifier
|
| 254 |
+
"""
|
| 255 |
+
checkpoint = torch.load(path, map_location=device or "cpu")
|
| 256 |
+
|
| 257 |
+
instance = cls(
|
| 258 |
+
input_height=checkpoint["input_height"],
|
| 259 |
+
input_width=checkpoint["input_width"],
|
| 260 |
+
device=device
|
| 261 |
+
)
|
| 262 |
+
instance.model.load_state_dict(checkpoint["model_state_dict"])
|
| 263 |
+
instance.is_fitted = checkpoint["is_fitted"]
|
| 264 |
+
|
| 265 |
+
return instance
|
models/ensemble.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ensemble Classifier
|
| 3 |
+
Combines traditional ML and CNN approaches for robust detection.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Dict, Tuple, Optional, Union
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 12 |
+
from config import ENSEMBLE_WEIGHTS, MODELS_DIR, AI_DETECTION_THRESHOLD
|
| 13 |
+
from models.traditional import FeatureBasedClassifier
|
| 14 |
+
from models.cnn import CNNClassifier
|
| 15 |
+
from features.spectral import extract_spectral_features
|
| 16 |
+
from features.mfcc import extract_mfcc_features, prepare_spectrogram_for_cnn
|
| 17 |
+
from features.prosody import extract_prosodic_features
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class EnsembleClassifier:
|
| 21 |
+
"""
|
| 22 |
+
Ensemble classifier combining traditional ML and deep learning.
|
| 23 |
+
|
| 24 |
+
Combines predictions from:
|
| 25 |
+
- Feature-based classifier (SVM/Random Forest)
|
| 26 |
+
- CNN classifier (spectrogram-based)
|
| 27 |
+
|
| 28 |
+
Weighted averaging produces the final prediction.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
traditional_model: Optional[FeatureBasedClassifier] = None,
|
| 34 |
+
cnn_model: Optional[CNNClassifier] = None,
|
| 35 |
+
weights: Optional[Dict[str, float]] = None,
|
| 36 |
+
threshold: float = AI_DETECTION_THRESHOLD
|
| 37 |
+
):
|
| 38 |
+
"""
|
| 39 |
+
Initialize the ensemble classifier.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
traditional_model: Pre-trained feature-based classifier
|
| 43 |
+
cnn_model: Pre-trained CNN classifier
|
| 44 |
+
weights: Weight dict {'traditional': w1, 'cnn': w2}
|
| 45 |
+
threshold: Threshold for AI classification
|
| 46 |
+
"""
|
| 47 |
+
self.traditional_model = traditional_model
|
| 48 |
+
self.cnn_model = cnn_model
|
| 49 |
+
self.weights = weights or ENSEMBLE_WEIGHTS
|
| 50 |
+
self.threshold = threshold
|
| 51 |
+
|
| 52 |
+
# Normalize weights
|
| 53 |
+
total = self.weights["traditional"] + self.weights["cnn"]
|
| 54 |
+
self.weights["traditional"] /= total
|
| 55 |
+
self.weights["cnn"] /= total
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def is_ready(self) -> bool:
|
| 59 |
+
"""Check if at least one model is available."""
|
| 60 |
+
trad_ready = self.traditional_model is not None and self.traditional_model.is_fitted
|
| 61 |
+
cnn_ready = self.cnn_model is not None and self.cnn_model.is_fitted
|
| 62 |
+
return trad_ready or cnn_ready
|
| 63 |
+
|
| 64 |
+
def analyze(
|
| 65 |
+
self,
|
| 66 |
+
audio: np.ndarray,
|
| 67 |
+
sr: int
|
| 68 |
+
) -> Dict:
|
| 69 |
+
"""
|
| 70 |
+
Analyze audio and return detailed results.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
audio: Audio waveform
|
| 74 |
+
sr: Sample rate
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
Dictionary with classification results and analysis
|
| 78 |
+
"""
|
| 79 |
+
results = {
|
| 80 |
+
"classification": "HUMAN",
|
| 81 |
+
"confidence_score": 0.5,
|
| 82 |
+
"traditional_score": None,
|
| 83 |
+
"cnn_score": None,
|
| 84 |
+
"features": {},
|
| 85 |
+
"explanation_parts": []
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# Extract features
|
| 89 |
+
spectral = extract_spectral_features(audio, sr)
|
| 90 |
+
mfcc = extract_mfcc_features(audio, sr)
|
| 91 |
+
prosody = extract_prosodic_features(audio, sr)
|
| 92 |
+
|
| 93 |
+
results["features"] = {
|
| 94 |
+
"spectral": spectral,
|
| 95 |
+
"mfcc": {k: v for k, v in mfcc.items() if "mfcc_0" in k or "energy" in k},
|
| 96 |
+
"prosody": prosody
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
scores = []
|
| 100 |
+
weights_used = []
|
| 101 |
+
|
| 102 |
+
# Traditional model prediction
|
| 103 |
+
if self.traditional_model is not None and self.traditional_model.is_fitted:
|
| 104 |
+
try:
|
| 105 |
+
feature_vector = np.concatenate([
|
| 106 |
+
np.array(list(spectral.values())),
|
| 107 |
+
np.array(list(mfcc.values())),
|
| 108 |
+
np.array(list(prosody.values()))
|
| 109 |
+
])
|
| 110 |
+
_, trad_prob = self.traditional_model.predict_single(feature_vector)
|
| 111 |
+
results["traditional_score"] = trad_prob
|
| 112 |
+
scores.append(trad_prob)
|
| 113 |
+
weights_used.append(self.weights["traditional"])
|
| 114 |
+
|
| 115 |
+
# Add explanation based on features
|
| 116 |
+
self._add_traditional_explanation(results, spectral, prosody, trad_prob)
|
| 117 |
+
except Exception as e:
|
| 118 |
+
results["traditional_error"] = str(e)
|
| 119 |
+
|
| 120 |
+
# CNN model prediction
|
| 121 |
+
if self.cnn_model is not None and self.cnn_model.is_fitted:
|
| 122 |
+
try:
|
| 123 |
+
spectrogram = prepare_spectrogram_for_cnn(audio, sr)
|
| 124 |
+
_, cnn_prob = self.cnn_model.predict_single(spectrogram)
|
| 125 |
+
results["cnn_score"] = cnn_prob
|
| 126 |
+
scores.append(cnn_prob)
|
| 127 |
+
weights_used.append(self.weights["cnn"])
|
| 128 |
+
|
| 129 |
+
self._add_cnn_explanation(results, cnn_prob)
|
| 130 |
+
except Exception as e:
|
| 131 |
+
results["cnn_error"] = str(e)
|
| 132 |
+
|
| 133 |
+
# Combine scores
|
| 134 |
+
if scores:
|
| 135 |
+
# Normalize weights for available models
|
| 136 |
+
total_weight = sum(weights_used)
|
| 137 |
+
normalized_weights = [w / total_weight for w in weights_used]
|
| 138 |
+
|
| 139 |
+
final_score = sum(s * w for s, w in zip(scores, normalized_weights))
|
| 140 |
+
results["confidence_score"] = float(final_score)
|
| 141 |
+
results["classification"] = "AI_GENERATED" if final_score >= self.threshold else "HUMAN"
|
| 142 |
+
|
| 143 |
+
# Generate final explanation
|
| 144 |
+
results["explanation"] = self._generate_explanation(results)
|
| 145 |
+
|
| 146 |
+
return results
|
| 147 |
+
|
| 148 |
+
def _add_traditional_explanation(
|
| 149 |
+
self,
|
| 150 |
+
results: Dict,
|
| 151 |
+
spectral: Dict,
|
| 152 |
+
prosody: Dict,
|
| 153 |
+
score: float
|
| 154 |
+
):
|
| 155 |
+
"""Add explanations based on traditional feature analysis."""
|
| 156 |
+
explanations = results["explanation_parts"]
|
| 157 |
+
|
| 158 |
+
# Check jitter (low jitter often indicates AI)
|
| 159 |
+
jitter = prosody.get("jitter_local", 0)
|
| 160 |
+
if jitter < 0.01:
|
| 161 |
+
explanations.append(f"Very low pitch variation (jitter={jitter:.4f})")
|
| 162 |
+
elif jitter > 0.05:
|
| 163 |
+
explanations.append(f"Natural pitch micro-variations detected")
|
| 164 |
+
|
| 165 |
+
# Check F0 coefficient of variation
|
| 166 |
+
f0_cv = prosody.get("f0_cv", 0)
|
| 167 |
+
if f0_cv < 0.1:
|
| 168 |
+
explanations.append("Unnaturally stable pitch contour")
|
| 169 |
+
|
| 170 |
+
# Check spectral characteristics
|
| 171 |
+
centroid_cv = spectral.get("centroid_cv", 0)
|
| 172 |
+
if centroid_cv < 0.1:
|
| 173 |
+
explanations.append("Spectral consistency suggests synthesized audio")
|
| 174 |
+
|
| 175 |
+
# Check rolloff patterns
|
| 176 |
+
rolloff_std = spectral.get("rolloff_std", 0)
|
| 177 |
+
if rolloff_std < 500:
|
| 178 |
+
explanations.append("Sharp frequency cutoff pattern detected")
|
| 179 |
+
|
| 180 |
+
def _add_cnn_explanation(self, results: Dict, score: float):
|
| 181 |
+
"""Add explanations based on CNN analysis."""
|
| 182 |
+
if score > 0.8:
|
| 183 |
+
results["explanation_parts"].append(
|
| 184 |
+
"Spectrogram patterns strongly match AI voice signatures"
|
| 185 |
+
)
|
| 186 |
+
elif score > 0.6:
|
| 187 |
+
results["explanation_parts"].append(
|
| 188 |
+
"Some AI-like patterns detected in spectrogram"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
def _generate_explanation(self, results: Dict) -> str:
|
| 192 |
+
"""Generate human-readable explanation."""
|
| 193 |
+
parts = results["explanation_parts"]
|
| 194 |
+
score = results["confidence_score"]
|
| 195 |
+
classification = results["classification"]
|
| 196 |
+
|
| 197 |
+
if not parts:
|
| 198 |
+
if classification == "AI_GENERATED":
|
| 199 |
+
return f"Audio shows characteristics of AI-generated speech (confidence: {score:.0%})"
|
| 200 |
+
else:
|
| 201 |
+
return f"Audio appears to be natural human speech (confidence: {1-score:.0%})"
|
| 202 |
+
|
| 203 |
+
intro = f"Analysis indicates {'AI-generated' if classification == 'AI_GENERATED' else 'human'} voice. "
|
| 204 |
+
details = " ".join(parts[:3]) # Limit to 3 explanations
|
| 205 |
+
|
| 206 |
+
return intro + details
|
| 207 |
+
|
| 208 |
+
def predict_simple(
|
| 209 |
+
self,
|
| 210 |
+
audio: np.ndarray,
|
| 211 |
+
sr: int
|
| 212 |
+
) -> Tuple[str, float]:
|
| 213 |
+
"""
|
| 214 |
+
Simple prediction returning just classification and confidence.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
audio: Audio waveform
|
| 218 |
+
sr: Sample rate
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
Tuple of (classification, confidence)
|
| 222 |
+
"""
|
| 223 |
+
results = self.analyze(audio, sr)
|
| 224 |
+
return results["classification"], results["confidence_score"]
|
| 225 |
+
|
| 226 |
+
def save(self, directory: Optional[Union[str, Path]] = None) -> Path:
|
| 227 |
+
"""
|
| 228 |
+
Save the ensemble model.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
directory: Save directory
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
Directory where models were saved
|
| 235 |
+
"""
|
| 236 |
+
if directory is None:
|
| 237 |
+
directory = MODELS_DIR / "ensemble"
|
| 238 |
+
|
| 239 |
+
directory = Path(directory)
|
| 240 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 241 |
+
|
| 242 |
+
# Save traditional model
|
| 243 |
+
if self.traditional_model is not None:
|
| 244 |
+
self.traditional_model.save(directory / "traditional.pkl")
|
| 245 |
+
|
| 246 |
+
# Save CNN model
|
| 247 |
+
if self.cnn_model is not None:
|
| 248 |
+
self.cnn_model.save(directory / "cnn.pth")
|
| 249 |
+
|
| 250 |
+
# Save config
|
| 251 |
+
config = {
|
| 252 |
+
"weights": self.weights,
|
| 253 |
+
"threshold": self.threshold,
|
| 254 |
+
"has_traditional": self.traditional_model is not None,
|
| 255 |
+
"has_cnn": self.cnn_model is not None
|
| 256 |
+
}
|
| 257 |
+
with open(directory / "config.json", "w") as f:
|
| 258 |
+
json.dump(config, f)
|
| 259 |
+
|
| 260 |
+
return directory
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
def load(
|
| 264 |
+
cls,
|
| 265 |
+
directory: Union[str, Path],
|
| 266 |
+
device: Optional[str] = None
|
| 267 |
+
) -> "EnsembleClassifier":
|
| 268 |
+
"""
|
| 269 |
+
Load an ensemble model.
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
directory: Directory containing saved models
|
| 273 |
+
device: Device for CNN
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
Loaded ensemble classifier
|
| 277 |
+
"""
|
| 278 |
+
directory = Path(directory)
|
| 279 |
+
|
| 280 |
+
# Load config
|
| 281 |
+
with open(directory / "config.json", "r") as f:
|
| 282 |
+
config = json.load(f)
|
| 283 |
+
|
| 284 |
+
traditional_model = None
|
| 285 |
+
cnn_model = None
|
| 286 |
+
|
| 287 |
+
# Load traditional model
|
| 288 |
+
if config["has_traditional"] and (directory / "traditional.pkl").exists():
|
| 289 |
+
traditional_model = FeatureBasedClassifier.load(directory / "traditional.pkl")
|
| 290 |
+
|
| 291 |
+
# Load CNN model
|
| 292 |
+
if config["has_cnn"] and (directory / "cnn.pth").exists():
|
| 293 |
+
cnn_model = CNNClassifier.load(directory / "cnn.pth", device=device)
|
| 294 |
+
|
| 295 |
+
return cls(
|
| 296 |
+
traditional_model=traditional_model,
|
| 297 |
+
cnn_model=cnn_model,
|
| 298 |
+
weights=config["weights"],
|
| 299 |
+
threshold=config["threshold"]
|
| 300 |
+
)
|
models/traditional.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Traditional ML Classifiers
|
| 3 |
+
Feature-based classification using SVM and Random Forest.
|
| 4 |
+
Best for interpretability - can explain WHY a voice is flagged as AI.
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pickle
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, Tuple, Optional, Union, List
|
| 10 |
+
from sklearn.svm import SVC
|
| 11 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 12 |
+
from sklearn.preprocessing import StandardScaler
|
| 13 |
+
from sklearn.pipeline import Pipeline
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 17 |
+
from config import SVM_KERNEL, RF_N_ESTIMATORS, MODELS_DIR
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class FeatureBasedClassifier:
|
| 21 |
+
"""
|
| 22 |
+
Traditional ML classifier for AI voice detection.
|
| 23 |
+
|
| 24 |
+
Uses extracted features (spectral, MFCC, prosodic) as input.
|
| 25 |
+
Supports SVM and Random Forest classifiers.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
classifier_type: str = "random_forest",
|
| 31 |
+
**kwargs
|
| 32 |
+
):
|
| 33 |
+
"""
|
| 34 |
+
Initialize the classifier.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
classifier_type: 'svm' or 'random_forest'
|
| 38 |
+
**kwargs: Additional classifier parameters
|
| 39 |
+
"""
|
| 40 |
+
self.classifier_type = classifier_type
|
| 41 |
+
self.scaler = StandardScaler()
|
| 42 |
+
self.is_fitted = False
|
| 43 |
+
|
| 44 |
+
if classifier_type == "svm":
|
| 45 |
+
self.classifier = SVC(
|
| 46 |
+
kernel=kwargs.get("kernel", SVM_KERNEL),
|
| 47 |
+
probability=True,
|
| 48 |
+
C=kwargs.get("C", 1.0),
|
| 49 |
+
gamma=kwargs.get("gamma", "scale"),
|
| 50 |
+
random_state=42
|
| 51 |
+
)
|
| 52 |
+
elif classifier_type == "random_forest":
|
| 53 |
+
self.classifier = RandomForestClassifier(
|
| 54 |
+
n_estimators=kwargs.get("n_estimators", RF_N_ESTIMATORS),
|
| 55 |
+
max_depth=kwargs.get("max_depth", None),
|
| 56 |
+
min_samples_split=kwargs.get("min_samples_split", 2),
|
| 57 |
+
random_state=42,
|
| 58 |
+
n_jobs=-1
|
| 59 |
+
)
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(f"Unknown classifier type: {classifier_type}")
|
| 62 |
+
|
| 63 |
+
# Create pipeline
|
| 64 |
+
self.pipeline = Pipeline([
|
| 65 |
+
("scaler", self.scaler),
|
| 66 |
+
("classifier", self.classifier)
|
| 67 |
+
])
|
| 68 |
+
|
| 69 |
+
def fit(
|
| 70 |
+
self,
|
| 71 |
+
features: np.ndarray,
|
| 72 |
+
labels: np.ndarray
|
| 73 |
+
) -> "FeatureBasedClassifier":
|
| 74 |
+
"""
|
| 75 |
+
Train the classifier.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
features: Feature matrix (n_samples, n_features)
|
| 79 |
+
labels: Binary labels (0=human, 1=AI)
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
Self
|
| 83 |
+
"""
|
| 84 |
+
self.pipeline.fit(features, labels)
|
| 85 |
+
self.is_fitted = True
|
| 86 |
+
return self
|
| 87 |
+
|
| 88 |
+
def predict(
|
| 89 |
+
self,
|
| 90 |
+
features: np.ndarray
|
| 91 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 92 |
+
"""
|
| 93 |
+
Predict labels and probabilities.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
features: Feature matrix (n_samples, n_features)
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
Tuple of (predictions, probabilities)
|
| 100 |
+
"""
|
| 101 |
+
if not self.is_fitted:
|
| 102 |
+
raise RuntimeError("Classifier not fitted. Call fit() first.")
|
| 103 |
+
|
| 104 |
+
predictions = self.pipeline.predict(features)
|
| 105 |
+
probabilities = self.pipeline.predict_proba(features)[:, 1] # P(AI)
|
| 106 |
+
|
| 107 |
+
return predictions, probabilities
|
| 108 |
+
|
| 109 |
+
def predict_single(
|
| 110 |
+
self,
|
| 111 |
+
features: np.ndarray
|
| 112 |
+
) -> Tuple[int, float]:
|
| 113 |
+
"""
|
| 114 |
+
Predict for a single sample.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
features: Feature vector (n_features,)
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
Tuple of (prediction, probability)
|
| 121 |
+
"""
|
| 122 |
+
features_2d = features.reshape(1, -1)
|
| 123 |
+
predictions, probabilities = self.predict(features_2d)
|
| 124 |
+
return int(predictions[0]), float(probabilities[0])
|
| 125 |
+
|
| 126 |
+
def get_feature_importance(self) -> Optional[Dict[str, float]]:
|
| 127 |
+
"""
|
| 128 |
+
Get feature importance (only for Random Forest).
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
Dictionary mapping feature index to importance,
|
| 132 |
+
or None if not applicable
|
| 133 |
+
"""
|
| 134 |
+
if self.classifier_type != "random_forest":
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
if not self.is_fitted:
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
importances = self.classifier.feature_importances_
|
| 141 |
+
return {f"feature_{i}": float(imp) for i, imp in enumerate(importances)}
|
| 142 |
+
|
| 143 |
+
def save(self, path: Optional[Union[str, Path]] = None) -> Path:
|
| 144 |
+
"""
|
| 145 |
+
Save the trained model.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
path: Optional save path
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
Path where model was saved
|
| 152 |
+
"""
|
| 153 |
+
if path is None:
|
| 154 |
+
path = MODELS_DIR / f"traditional_{self.classifier_type}.pkl"
|
| 155 |
+
|
| 156 |
+
path = Path(path)
|
| 157 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 158 |
+
|
| 159 |
+
with open(path, "wb") as f:
|
| 160 |
+
pickle.dump({
|
| 161 |
+
"classifier_type": self.classifier_type,
|
| 162 |
+
"pipeline": self.pipeline,
|
| 163 |
+
"is_fitted": self.is_fitted
|
| 164 |
+
}, f)
|
| 165 |
+
|
| 166 |
+
return path
|
| 167 |
+
|
| 168 |
+
@classmethod
|
| 169 |
+
def load(cls, path: Union[str, Path]) -> "FeatureBasedClassifier":
|
| 170 |
+
"""
|
| 171 |
+
Load a trained model.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
path: Path to saved model
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
Loaded classifier
|
| 178 |
+
"""
|
| 179 |
+
with open(path, "rb") as f:
|
| 180 |
+
data = pickle.load(f)
|
| 181 |
+
|
| 182 |
+
instance = cls(classifier_type=data["classifier_type"])
|
| 183 |
+
instance.pipeline = data["pipeline"]
|
| 184 |
+
instance.scaler = data["pipeline"].named_steps["scaler"]
|
| 185 |
+
instance.classifier = data["pipeline"].named_steps["classifier"]
|
| 186 |
+
instance.is_fitted = data["is_fitted"]
|
| 187 |
+
|
| 188 |
+
return instance
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def create_feature_vector(
|
| 192 |
+
spectral_features: Dict[str, float],
|
| 193 |
+
mfcc_features: Dict[str, float],
|
| 194 |
+
prosodic_features: Dict[str, float]
|
| 195 |
+
) -> np.ndarray:
|
| 196 |
+
"""
|
| 197 |
+
Combine all features into a single vector.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
spectral_features: From spectral extraction
|
| 201 |
+
mfcc_features: From MFCC extraction
|
| 202 |
+
prosodic_features: From prosodic extraction
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
Combined feature vector
|
| 206 |
+
"""
|
| 207 |
+
all_features = {}
|
| 208 |
+
all_features.update(spectral_features)
|
| 209 |
+
all_features.update(mfcc_features)
|
| 210 |
+
all_features.update(prosodic_features)
|
| 211 |
+
|
| 212 |
+
return np.array(list(all_features.values()))
|
requirements.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# VocalSense - AI Voice Detection System
|
| 2 |
+
# Core Dependencies
|
| 3 |
+
librosa>=0.10.0
|
| 4 |
+
numpy>=1.24.0
|
| 5 |
+
scipy>=1.10.0
|
| 6 |
+
scikit-learn>=1.3.0
|
| 7 |
+
torch>=2.0.0
|
| 8 |
+
torchaudio>=2.0.0
|
| 9 |
+
|
| 10 |
+
# API
|
| 11 |
+
fastapi>=0.104.0
|
| 12 |
+
uvicorn>=0.24.0
|
| 13 |
+
python-multipart>=0.0.6
|
| 14 |
+
pydantic>=2.5.0
|
| 15 |
+
|
| 16 |
+
# Audio Processing
|
| 17 |
+
soundfile>=0.12.0
|
| 18 |
+
parselmouth>=0.4.0
|
| 19 |
+
|
| 20 |
+
# Utilities
|
| 21 |
+
|
| 22 |
+
tqdm>=4.65.0
|
| 23 |
+
|
| 24 |
+
# Visualization (optional)
|
| 25 |
+
matplotlib>=3.7.0
|
| 26 |
+
seaborn>=0.12.0
|
saved_models/traditional_random_forest.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dd3fe702593fa048539af7d85c99f99a2dfeab3a13316cb3c36d7e2c5b9f1b72
|
| 3 |
+
size 3886228
|
training/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Training module
|
training/dataset.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dataset Loader for VocalSense Training
|
| 3 |
+
Loads audio files from data/real and data/fake folders.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Tuple, List, Dict, Optional
|
| 8 |
+
from sklearn.model_selection import train_test_split
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import warnings
|
| 11 |
+
warnings.filterwarnings('ignore')
|
| 12 |
+
|
| 13 |
+
import sys
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 15 |
+
|
| 16 |
+
from config import DATA_DIR, SAMPLE_RATE
|
| 17 |
+
from utils.audio import load_audio, preprocess_audio
|
| 18 |
+
from features.spectral import extract_spectral_features
|
| 19 |
+
from features.mfcc import extract_mfcc_features
|
| 20 |
+
from features.prosody import extract_prosodic_features
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class AudioDataset:
|
| 24 |
+
"""
|
| 25 |
+
Dataset loader for real/fake audio classification.
|
| 26 |
+
|
| 27 |
+
Loads audio from:
|
| 28 |
+
- data/real/ -> label 0 (human)
|
| 29 |
+
- data/fake/ -> label 1 (AI/TTS)
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
AUDIO_EXTENSIONS = {'.wav', '.mp3', '.flac', '.ogg', '.m4a'}
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
data_dir: Optional[Path] = None,
|
| 37 |
+
test_size: float = 0.1,
|
| 38 |
+
val_size: float = 0.1,
|
| 39 |
+
random_state: int = 42
|
| 40 |
+
):
|
| 41 |
+
"""
|
| 42 |
+
Initialize dataset.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
data_dir: Path to data directory (default: config.DATA_DIR)
|
| 46 |
+
test_size: Fraction for test set
|
| 47 |
+
val_size: Fraction for validation set
|
| 48 |
+
random_state: Random seed for reproducibility
|
| 49 |
+
"""
|
| 50 |
+
self.data_dir = Path(data_dir) if data_dir else DATA_DIR
|
| 51 |
+
self.real_dir = self.data_dir / "real"
|
| 52 |
+
self.fake_dir = self.data_dir / "fake"
|
| 53 |
+
self.test_size = test_size
|
| 54 |
+
self.val_size = val_size
|
| 55 |
+
self.random_state = random_state
|
| 56 |
+
|
| 57 |
+
# Check directories exist
|
| 58 |
+
if not self.real_dir.exists():
|
| 59 |
+
raise FileNotFoundError(f"Real audio directory not found: {self.real_dir}")
|
| 60 |
+
if not self.fake_dir.exists():
|
| 61 |
+
raise FileNotFoundError(f"Fake audio directory not found: {self.fake_dir}")
|
| 62 |
+
|
| 63 |
+
def _get_audio_files(self, directory: Path) -> List[Path]:
|
| 64 |
+
"""Get all audio files in a directory."""
|
| 65 |
+
files = []
|
| 66 |
+
for ext in self.AUDIO_EXTENSIONS:
|
| 67 |
+
files.extend(directory.glob(f"*{ext}"))
|
| 68 |
+
files.extend(directory.glob(f"*{ext.upper()}"))
|
| 69 |
+
return sorted(files)
|
| 70 |
+
|
| 71 |
+
def _extract_features(self, audio_path: Path) -> Optional[np.ndarray]:
|
| 72 |
+
"""Extract all features from an audio file."""
|
| 73 |
+
try:
|
| 74 |
+
# Load and preprocess
|
| 75 |
+
audio, sr = load_audio(str(audio_path), sr=SAMPLE_RATE)
|
| 76 |
+
if audio is None or len(audio) < sr: # Skip very short files
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
audio = preprocess_audio(audio, sr)
|
| 80 |
+
|
| 81 |
+
# Extract features
|
| 82 |
+
spectral = extract_spectral_features(audio, sr)
|
| 83 |
+
mfcc = extract_mfcc_features(audio, sr)
|
| 84 |
+
prosody = extract_prosodic_features(audio, sr)
|
| 85 |
+
|
| 86 |
+
# Combine into single vector
|
| 87 |
+
all_features = {}
|
| 88 |
+
all_features.update(spectral)
|
| 89 |
+
all_features.update(mfcc)
|
| 90 |
+
all_features.update(prosody)
|
| 91 |
+
|
| 92 |
+
return np.array(list(all_features.values()))
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f" Warning: Could not process {audio_path.name}: {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
def load_data(self) -> Tuple[np.ndarray, np.ndarray]:
|
| 99 |
+
"""
|
| 100 |
+
Load all audio files and extract features.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
Tuple of (features, labels)
|
| 104 |
+
"""
|
| 105 |
+
features_list = []
|
| 106 |
+
labels_list = []
|
| 107 |
+
|
| 108 |
+
# Load real (human) audio - label 0
|
| 109 |
+
real_files = self._get_audio_files(self.real_dir)
|
| 110 |
+
print(f"\nLoading {len(real_files)} real/human audio files...")
|
| 111 |
+
for audio_path in tqdm(real_files, desc="Real audio"):
|
| 112 |
+
features = self._extract_features(audio_path)
|
| 113 |
+
if features is not None:
|
| 114 |
+
features_list.append(features)
|
| 115 |
+
labels_list.append(0)
|
| 116 |
+
|
| 117 |
+
# Load fake (AI/TTS) audio - label 1
|
| 118 |
+
fake_files = self._get_audio_files(self.fake_dir)
|
| 119 |
+
print(f"\nLoading {len(fake_files)} fake/AI audio files...")
|
| 120 |
+
for audio_path in tqdm(fake_files, desc="Fake audio"):
|
| 121 |
+
features = self._extract_features(audio_path)
|
| 122 |
+
if features is not None:
|
| 123 |
+
features_list.append(features)
|
| 124 |
+
labels_list.append(1)
|
| 125 |
+
|
| 126 |
+
if len(features_list) == 0:
|
| 127 |
+
raise ValueError("No audio files found or processed successfully!")
|
| 128 |
+
|
| 129 |
+
features = np.array(features_list)
|
| 130 |
+
labels = np.array(labels_list)
|
| 131 |
+
|
| 132 |
+
print(f"\nLoaded {len(labels)} samples total:")
|
| 133 |
+
print(f" - Real/Human: {np.sum(labels == 0)}")
|
| 134 |
+
print(f" - Fake/AI: {np.sum(labels == 1)}")
|
| 135 |
+
|
| 136 |
+
return features, labels
|
| 137 |
+
|
| 138 |
+
def get_splits(self) -> Dict[str, Tuple[np.ndarray, np.ndarray]]:
|
| 139 |
+
"""
|
| 140 |
+
Load data and split into train/val/test sets.
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
Dictionary with 'train', 'val', 'test' keys,
|
| 144 |
+
each containing (features, labels) tuple
|
| 145 |
+
"""
|
| 146 |
+
features, labels = self.load_data()
|
| 147 |
+
|
| 148 |
+
# First split: separate test set
|
| 149 |
+
X_temp, X_test, y_temp, y_test = train_test_split(
|
| 150 |
+
features, labels,
|
| 151 |
+
test_size=self.test_size,
|
| 152 |
+
random_state=self.random_state,
|
| 153 |
+
stratify=labels
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# Second split: separate validation from training
|
| 157 |
+
val_ratio = self.val_size / (1 - self.test_size)
|
| 158 |
+
X_train, X_val, y_train, y_val = train_test_split(
|
| 159 |
+
X_temp, y_temp,
|
| 160 |
+
test_size=val_ratio,
|
| 161 |
+
random_state=self.random_state,
|
| 162 |
+
stratify=y_temp
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
print(f"\nData splits:")
|
| 166 |
+
print(f" - Train: {len(y_train)} samples")
|
| 167 |
+
print(f" - Val: {len(y_val)} samples")
|
| 168 |
+
print(f" - Test: {len(y_test)} samples")
|
| 169 |
+
|
| 170 |
+
return {
|
| 171 |
+
'train': (X_train, y_train),
|
| 172 |
+
'val': (X_val, y_val),
|
| 173 |
+
'test': (X_test, y_test)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def quick_test():
|
| 178 |
+
"""Quick test to verify dataset loading."""
|
| 179 |
+
print("Testing AudioDataset...")
|
| 180 |
+
try:
|
| 181 |
+
dataset = AudioDataset()
|
| 182 |
+
real_files = dataset._get_audio_files(dataset.real_dir)
|
| 183 |
+
fake_files = dataset._get_audio_files(dataset.fake_dir)
|
| 184 |
+
print(f"Found {len(real_files)} real files, {len(fake_files)} fake files")
|
| 185 |
+
return True
|
| 186 |
+
except Exception as e:
|
| 187 |
+
print(f"Error: {e}")
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
quick_test()
|
training/trainer.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Model Trainer for VocalSense
|
| 3 |
+
Trains Traditional ML and CNN models on the audio dataset.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Dict, Optional, Tuple
|
| 8 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 13 |
+
|
| 14 |
+
from config import MODELS_DIR, EPOCHS, BATCH_SIZE, LEARNING_RATE, EARLY_STOPPING_PATIENCE
|
| 15 |
+
from models.traditional import FeatureBasedClassifier
|
| 16 |
+
from training.dataset import AudioDataset
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Trainer:
|
| 20 |
+
"""
|
| 21 |
+
Trainer for VocalSense models.
|
| 22 |
+
|
| 23 |
+
Supports training:
|
| 24 |
+
- Traditional ML (Random Forest, SVM)
|
| 25 |
+
- CNN (coming soon - requires spectrogram dataset)
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
model_type: str = "random_forest",
|
| 31 |
+
epochs: int = EPOCHS,
|
| 32 |
+
save_dir: Optional[Path] = None
|
| 33 |
+
):
|
| 34 |
+
"""
|
| 35 |
+
Initialize trainer.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
model_type: 'random_forest' or 'svm'
|
| 39 |
+
epochs: Number of epochs (for future CNN training)
|
| 40 |
+
save_dir: Directory to save trained models
|
| 41 |
+
"""
|
| 42 |
+
self.model_type = model_type
|
| 43 |
+
self.epochs = epochs
|
| 44 |
+
self.save_dir = Path(save_dir) if save_dir else MODELS_DIR
|
| 45 |
+
self.save_dir.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
|
| 47 |
+
self.model = None
|
| 48 |
+
self.history = {
|
| 49 |
+
'train_acc': [],
|
| 50 |
+
'val_acc': [],
|
| 51 |
+
'train_loss': [],
|
| 52 |
+
'val_loss': []
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
def train(
|
| 56 |
+
self,
|
| 57 |
+
X_train: np.ndarray,
|
| 58 |
+
y_train: np.ndarray,
|
| 59 |
+
X_val: Optional[np.ndarray] = None,
|
| 60 |
+
y_val: Optional[np.ndarray] = None
|
| 61 |
+
) -> FeatureBasedClassifier:
|
| 62 |
+
"""
|
| 63 |
+
Train the model.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
X_train: Training features
|
| 67 |
+
y_train: Training labels
|
| 68 |
+
X_val: Validation features (optional)
|
| 69 |
+
y_val: Validation labels (optional)
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
Trained classifier
|
| 73 |
+
"""
|
| 74 |
+
print(f"\n{'='*50}")
|
| 75 |
+
print(f"Training {self.model_type.upper()} model")
|
| 76 |
+
print(f"{'='*50}")
|
| 77 |
+
print(f"Training samples: {len(y_train)}")
|
| 78 |
+
if y_val is not None:
|
| 79 |
+
print(f"Validation samples: {len(y_val)}")
|
| 80 |
+
|
| 81 |
+
start_time = time.time()
|
| 82 |
+
|
| 83 |
+
# Create and train model
|
| 84 |
+
self.model = FeatureBasedClassifier(classifier_type=self.model_type)
|
| 85 |
+
self.model.fit(X_train, y_train)
|
| 86 |
+
|
| 87 |
+
train_time = time.time() - start_time
|
| 88 |
+
print(f"\nTraining completed in {train_time:.2f} seconds")
|
| 89 |
+
|
| 90 |
+
# Evaluate on training set
|
| 91 |
+
train_preds, train_probs = self.model.predict(X_train)
|
| 92 |
+
train_acc = accuracy_score(y_train, train_preds)
|
| 93 |
+
print(f"Training accuracy: {train_acc:.4f}")
|
| 94 |
+
|
| 95 |
+
# Evaluate on validation set
|
| 96 |
+
if X_val is not None and y_val is not None:
|
| 97 |
+
val_preds, val_probs = self.model.predict(X_val)
|
| 98 |
+
val_acc = accuracy_score(y_val, val_preds)
|
| 99 |
+
print(f"Validation accuracy: {val_acc:.4f}")
|
| 100 |
+
self.history['val_acc'].append(val_acc)
|
| 101 |
+
|
| 102 |
+
self.history['train_acc'].append(train_acc)
|
| 103 |
+
|
| 104 |
+
return self.model
|
| 105 |
+
|
| 106 |
+
def evaluate(
|
| 107 |
+
self,
|
| 108 |
+
X_test: np.ndarray,
|
| 109 |
+
y_test: np.ndarray,
|
| 110 |
+
verbose: bool = True
|
| 111 |
+
) -> Dict[str, float]:
|
| 112 |
+
"""
|
| 113 |
+
Evaluate model on test set.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
X_test: Test features
|
| 117 |
+
y_test: Test labels
|
| 118 |
+
verbose: Whether to print detailed report
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
Dictionary of metrics
|
| 122 |
+
"""
|
| 123 |
+
if self.model is None:
|
| 124 |
+
raise RuntimeError("Model not trained. Call train() first.")
|
| 125 |
+
|
| 126 |
+
predictions, probabilities = self.model.predict(X_test)
|
| 127 |
+
|
| 128 |
+
metrics = {
|
| 129 |
+
'accuracy': accuracy_score(y_test, predictions),
|
| 130 |
+
'precision': precision_score(y_test, predictions, zero_division=0),
|
| 131 |
+
'recall': recall_score(y_test, predictions, zero_division=0),
|
| 132 |
+
'f1': f1_score(y_test, predictions, zero_division=0)
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
if verbose:
|
| 136 |
+
print(f"\n{'='*50}")
|
| 137 |
+
print("TEST SET EVALUATION")
|
| 138 |
+
print(f"{'='*50}")
|
| 139 |
+
print(f"Accuracy: {metrics['accuracy']:.4f}")
|
| 140 |
+
print(f"Precision: {metrics['precision']:.4f}")
|
| 141 |
+
print(f"Recall: {metrics['recall']:.4f}")
|
| 142 |
+
print(f"F1 Score: {metrics['f1']:.4f}")
|
| 143 |
+
print(f"\nClassification Report:")
|
| 144 |
+
print(classification_report(
|
| 145 |
+
y_test, predictions,
|
| 146 |
+
target_names=['Human/Real', 'AI/Fake']
|
| 147 |
+
))
|
| 148 |
+
|
| 149 |
+
return metrics
|
| 150 |
+
|
| 151 |
+
def save_model(self, filename: Optional[str] = None) -> Path:
|
| 152 |
+
"""
|
| 153 |
+
Save trained model.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
filename: Optional filename
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
Path to saved model
|
| 160 |
+
"""
|
| 161 |
+
if self.model is None:
|
| 162 |
+
raise RuntimeError("Model not trained. Call train() first.")
|
| 163 |
+
|
| 164 |
+
if filename is None:
|
| 165 |
+
filename = f"traditional_{self.model_type}.pkl"
|
| 166 |
+
|
| 167 |
+
save_path = self.save_dir / filename
|
| 168 |
+
self.model.save(save_path)
|
| 169 |
+
print(f"\nModel saved to: {save_path}")
|
| 170 |
+
|
| 171 |
+
return save_path
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def train_full_pipeline(
|
| 175 |
+
model_type: str = "random_forest",
|
| 176 |
+
epochs: int = 50,
|
| 177 |
+
data_dir: Optional[Path] = None
|
| 178 |
+
) -> Tuple[FeatureBasedClassifier, Dict[str, float]]:
|
| 179 |
+
"""
|
| 180 |
+
Full training pipeline: load data, train, evaluate, save.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
model_type: 'random_forest' or 'svm'
|
| 184 |
+
epochs: Number of epochs
|
| 185 |
+
data_dir: Data directory
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
Tuple of (trained model, test metrics)
|
| 189 |
+
"""
|
| 190 |
+
print("\n" + "="*60)
|
| 191 |
+
print(" VocalSense Training Pipeline")
|
| 192 |
+
print("="*60)
|
| 193 |
+
|
| 194 |
+
# Load dataset
|
| 195 |
+
print("\n[1/4] Loading dataset...")
|
| 196 |
+
dataset = AudioDataset(data_dir=data_dir)
|
| 197 |
+
splits = dataset.get_splits()
|
| 198 |
+
|
| 199 |
+
X_train, y_train = splits['train']
|
| 200 |
+
X_val, y_val = splits['val']
|
| 201 |
+
X_test, y_test = splits['test']
|
| 202 |
+
|
| 203 |
+
# Train model
|
| 204 |
+
print("\n[2/4] Training model...")
|
| 205 |
+
trainer = Trainer(model_type=model_type, epochs=epochs)
|
| 206 |
+
model = trainer.train(X_train, y_train, X_val, y_val)
|
| 207 |
+
|
| 208 |
+
# Evaluate
|
| 209 |
+
print("\n[3/4] Evaluating model...")
|
| 210 |
+
metrics = trainer.evaluate(X_test, y_test)
|
| 211 |
+
|
| 212 |
+
# Save
|
| 213 |
+
print("\n[4/4] Saving model...")
|
| 214 |
+
trainer.save_model()
|
| 215 |
+
|
| 216 |
+
print("\n" + "="*60)
|
| 217 |
+
print(" Training Complete!")
|
| 218 |
+
print("="*60)
|
| 219 |
+
print(f" Final Test Accuracy: {metrics['accuracy']:.2%}")
|
| 220 |
+
print("="*60 + "\n")
|
| 221 |
+
|
| 222 |
+
return model, metrics
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
if __name__ == "__main__":
|
| 226 |
+
train_full_pipeline()
|
utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Utils module
|
utils/audio.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Audio Utilities
|
| 3 |
+
Common audio processing functions for loading, preprocessing, and segmentation.
|
| 4 |
+
"""
|
| 5 |
+
import io
|
| 6 |
+
import base64
|
| 7 |
+
import numpy as np
|
| 8 |
+
import librosa
|
| 9 |
+
import soundfile as sf
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Union, Tuple, Optional
|
| 12 |
+
import tempfile
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 17 |
+
from config import SAMPLE_RATE, DURATION, TEMP_DIR
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_audio(
|
| 21 |
+
source: Union[str, Path, bytes],
|
| 22 |
+
sr: int = SAMPLE_RATE,
|
| 23 |
+
mono: bool = True
|
| 24 |
+
) -> Tuple[np.ndarray, int]:
|
| 25 |
+
"""
|
| 26 |
+
Load audio from file path, bytes, or base64 string.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
source: File path, raw bytes, or base64-encoded audio
|
| 30 |
+
sr: Target sample rate
|
| 31 |
+
mono: Convert to mono if True
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Tuple of (audio_array, sample_rate)
|
| 35 |
+
"""
|
| 36 |
+
if isinstance(source, (str, Path)):
|
| 37 |
+
# Load from file path
|
| 38 |
+
audio, sample_rate = librosa.load(source, sr=sr, mono=mono)
|
| 39 |
+
elif isinstance(source, bytes):
|
| 40 |
+
# Load from bytes
|
| 41 |
+
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
|
| 42 |
+
tmp.write(source)
|
| 43 |
+
tmp_path = tmp.name
|
| 44 |
+
try:
|
| 45 |
+
audio, sample_rate = librosa.load(tmp_path, sr=sr, mono=mono)
|
| 46 |
+
finally:
|
| 47 |
+
os.unlink(tmp_path)
|
| 48 |
+
else:
|
| 49 |
+
raise ValueError(f"Unsupported source type: {type(source)}")
|
| 50 |
+
|
| 51 |
+
return audio, sample_rate
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def decode_base64_audio(
|
| 55 |
+
audio_base64: str,
|
| 56 |
+
audio_format: str = "wav",
|
| 57 |
+
sr: int = SAMPLE_RATE,
|
| 58 |
+
mono: bool = True
|
| 59 |
+
) -> Tuple[np.ndarray, int]:
|
| 60 |
+
"""
|
| 61 |
+
Decode base64-encoded audio and load it.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
audio_base64: Base64-encoded audio string
|
| 65 |
+
audio_format: Audio format (wav, mp3, etc.)
|
| 66 |
+
sr: Target sample rate
|
| 67 |
+
mono: Convert to mono if True
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
Tuple of (audio_array, sample_rate)
|
| 71 |
+
"""
|
| 72 |
+
audio_bytes = base64.b64decode(audio_base64)
|
| 73 |
+
return load_audio(audio_bytes, sr=sr, mono=mono)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def preprocess_audio(
|
| 77 |
+
audio: np.ndarray,
|
| 78 |
+
sr: int = SAMPLE_RATE,
|
| 79 |
+
normalize: bool = True,
|
| 80 |
+
trim_silence: bool = True,
|
| 81 |
+
top_db: int = 20
|
| 82 |
+
) -> np.ndarray:
|
| 83 |
+
"""
|
| 84 |
+
Preprocess audio: normalize amplitude and optionally trim silence.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
audio: Audio array
|
| 88 |
+
sr: Sample rate
|
| 89 |
+
normalize: Normalize amplitude to [-1, 1]
|
| 90 |
+
trim_silence: Remove leading/trailing silence
|
| 91 |
+
top_db: Threshold for silence trimming
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
Preprocessed audio array
|
| 95 |
+
"""
|
| 96 |
+
# Trim silence
|
| 97 |
+
if trim_silence:
|
| 98 |
+
audio, _ = librosa.effects.trim(audio, top_db=top_db)
|
| 99 |
+
|
| 100 |
+
# Normalize
|
| 101 |
+
if normalize:
|
| 102 |
+
max_val = np.max(np.abs(audio))
|
| 103 |
+
if max_val > 0:
|
| 104 |
+
audio = audio / max_val
|
| 105 |
+
|
| 106 |
+
return audio
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def segment_audio(
|
| 110 |
+
audio: np.ndarray,
|
| 111 |
+
sr: int = SAMPLE_RATE,
|
| 112 |
+
segment_duration: float = DURATION,
|
| 113 |
+
overlap: float = 0.5
|
| 114 |
+
) -> list:
|
| 115 |
+
"""
|
| 116 |
+
Segment audio into fixed-length chunks.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
audio: Audio array
|
| 120 |
+
sr: Sample rate
|
| 121 |
+
segment_duration: Duration of each segment in seconds
|
| 122 |
+
overlap: Overlap ratio between segments (0-1)
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
List of audio segments
|
| 126 |
+
"""
|
| 127 |
+
segment_samples = int(segment_duration * sr)
|
| 128 |
+
hop_samples = int(segment_samples * (1 - overlap))
|
| 129 |
+
|
| 130 |
+
segments = []
|
| 131 |
+
start = 0
|
| 132 |
+
|
| 133 |
+
while start + segment_samples <= len(audio):
|
| 134 |
+
segment = audio[start:start + segment_samples]
|
| 135 |
+
segments.append(segment)
|
| 136 |
+
start += hop_samples
|
| 137 |
+
|
| 138 |
+
# Handle last segment if there's remaining audio
|
| 139 |
+
if start < len(audio):
|
| 140 |
+
# Pad the last segment if needed
|
| 141 |
+
last_segment = audio[start:]
|
| 142 |
+
if len(last_segment) >= segment_samples // 2: # Only if at least half length
|
| 143 |
+
padded = np.zeros(segment_samples)
|
| 144 |
+
padded[:len(last_segment)] = last_segment
|
| 145 |
+
segments.append(padded)
|
| 146 |
+
|
| 147 |
+
return segments
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def ensure_length(
|
| 151 |
+
audio: np.ndarray,
|
| 152 |
+
target_length: int,
|
| 153 |
+
pad_mode: str = "constant"
|
| 154 |
+
) -> np.ndarray:
|
| 155 |
+
"""
|
| 156 |
+
Ensure audio has exact target length by padding or truncating.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
audio: Audio array
|
| 160 |
+
target_length: Target number of samples
|
| 161 |
+
pad_mode: Padding mode ('constant', 'reflect', etc.)
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
Audio array with exact target length
|
| 165 |
+
"""
|
| 166 |
+
if len(audio) > target_length:
|
| 167 |
+
return audio[:target_length]
|
| 168 |
+
elif len(audio) < target_length:
|
| 169 |
+
padding = target_length - len(audio)
|
| 170 |
+
return np.pad(audio, (0, padding), mode=pad_mode)
|
| 171 |
+
return audio
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def get_audio_duration(audio: np.ndarray, sr: int = SAMPLE_RATE) -> float:
|
| 175 |
+
"""Get duration of audio in seconds."""
|
| 176 |
+
return len(audio) / sr
|