vs / api /app.py
Madu Murugesh
.
ef79c08 verified
Raw History Blame Contribute Delete
10.7 kB
"""
VocalSense FastAPI Application
REST API for AI voice detection with two endpoints:
- POST /api/v1/analyze/base64 - Accept base64-encoded audio
- POST /api/v1/analyze/file - Accept file upload
"""
import os
import tempfile
import logging
from pathlib import Path
from typing import Optional
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Depends, Header, UploadFile, File, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, validator
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import (
API_VERSION, API_KEY, SUPPORTED_LANGUAGES,
ALLOWED_AUDIO_FORMATS, MAX_FILE_SIZE_MB
)
from api.detector import get_detector, VoiceDetector
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# =============================================================================
# Pydantic Models
# =============================================================================
class Base64AudioRequest(BaseModel):
"""Request model for base64-encoded audio."""
language: str = Field(..., description="Language of the audio")
audioFormat: str = Field(..., description="Audio format (wav, mp3, etc.)")
audioBase64: str = Field(..., description="Base64-encoded audio data")
@validator("language")
def validate_language(cls, v):
if v not in SUPPORTED_LANGUAGES:
raise ValueError(f"Unsupported language. Must be one of: {SUPPORTED_LANGUAGES}")
return v
@validator("audioFormat")
def validate_format(cls, v):
v_lower = v.lower()
if v_lower not in ALLOWED_AUDIO_FORMATS:
raise ValueError(f"Unsupported format. Must be one of: {ALLOWED_AUDIO_FORMATS}")
return v_lower
class AnalysisResponse(BaseModel):
"""Successful analysis response."""
status: str = "success"
language: str
classification: str # "AI_GENERATED" or "HUMAN"
confidenceScore: float
explanation: str
class ErrorResponse(BaseModel):
"""Error response model."""
status: str = "error"
message: str
# =============================================================================
# Dependency Injection
# =============================================================================
async def verify_api_key(x_api_key: str = Header(..., alias="X-API-Key")) -> str:
"""
Verify the API key from request headers.
Args:
x_api_key: API key from X-API-Key header
Returns:
The validated API key
Raises:
HTTPException: If API key is invalid or missing
"""
if not x_api_key:
raise HTTPException(
status_code=401,
detail={"status": "error", "message": "API key is required"}
)
if x_api_key != API_KEY:
raise HTTPException(
status_code=403,
detail={"status": "error", "message": "Invalid API key"}
)
return x_api_key
def validate_language(language: str) -> str:
"""Validate language parameter."""
if language not in SUPPORTED_LANGUAGES:
raise HTTPException(
status_code=400,
detail={
"status": "error",
"message": f"Unsupported language '{language}'. Supported languages: {', '.join(SUPPORTED_LANGUAGES)}"
}
)
return language
# =============================================================================
# Lifespan Events
# =============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan events."""
# Startup
logger.info("Starting VocalSense API...")
logger.info(f"Supported languages: {SUPPORTED_LANGUAGES}")
logger.info(f"API Version: {API_VERSION}")
# Initialize detector
detector = get_detector()
logger.info("Voice detector initialized")
yield
# Shutdown
logger.info("Shutting down VocalSense API...")
# =============================================================================
# FastAPI Application
# =============================================================================
app = FastAPI(
title="VocalSense API",
description="AI Voice Detection System - Detect AI-generated voices using spectral analysis",
version="1.0.0",
lifespan=lifespan
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# =============================================================================
# Exception Handlers
# =============================================================================
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
"""Handle HTTP exceptions with proper error format."""
if isinstance(exc.detail, dict):
return JSONResponse(status_code=exc.status_code, content=exc.detail)
return JSONResponse(
status_code=exc.status_code,
content={"status": "error", "message": str(exc.detail)}
)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
"""Handle unexpected exceptions."""
logger.exception(f"Unexpected error: {exc}")
return JSONResponse(
status_code=500,
content={"status": "error", "message": "Internal server error"}
)
# =============================================================================
# API Endpoints
# =============================================================================
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy", "version": API_VERSION}
@app.post(
f"/api/voice-detection",
response_model=AnalysisResponse,
responses={
400: {"model": ErrorResponse, "description": "Bad request"},
401: {"model": ErrorResponse, "description": "Missing API key"},
403: {"model": ErrorResponse, "description": "Invalid API key"},
500: {"model": ErrorResponse, "description": "Internal server error"}
}
)
async def analyze_base64_audio(
request: Base64AudioRequest,
api_key: str = Depends(verify_api_key)
):
"""
Analyze base64-encoded audio for AI voice detection.
Requires X-API-Key header for authentication.
**Request Body:**
- language: Language of the audio (Hindi, Tamil, Telugu, Malayalam, English)
- audioFormat: Audio format (wav, mp3, flac, ogg, m4a)
- audioBase64: Base64-encoded audio data
**Response:**
- status: "success"
- language: The input language
- classification: "AI_GENERATED" or "HUMAN"
- confidenceScore: Confidence score (0-1)
- explanation: Human-readable explanation
"""
try:
detector = get_detector()
result = detector.analyze_base64(
audio_base64=request.audioBase64,
audio_format=request.audioFormat,
language=request.language
)
return result
except ValueError as e:
raise HTTPException(
status_code=400,
detail={"status": "error", "message": str(e)}
)
except Exception as e:
logger.exception(f"Error analyzing base64 audio: {e}")
raise HTTPException(
status_code=500,
detail={"status": "error", "message": "Failed to analyze audio"}
)
@app.post(
f"/api/analyze/file",
response_model=AnalysisResponse,
responses={
400: {"model": ErrorResponse, "description": "Bad request"},
401: {"model": ErrorResponse, "description": "Missing API key"},
403: {"model": ErrorResponse, "description": "Invalid API key"},
413: {"model": ErrorResponse, "description": "File too large"},
500: {"model": ErrorResponse, "description": "Internal server error"}
}
)
async def analyze_file_upload(
language: str = Form(..., description="Language of the audio"),
file: UploadFile = File(..., description="Audio file to analyze"),
api_key: str = Depends(verify_api_key)
):
"""
Analyze uploaded audio file for AI voice detection.
Requires X-API-Key header for authentication.
**Form Data:**
- language: Language of the audio (Hindi, Tamil, Telugu, Malayalam, English)
- file: Audio file (multipart/form-data)
**Response:**
- status: "success"
- language: The input language
- classification: "AI_GENERATED" or "HUMAN"
- confidenceScore: Confidence score (0-1)
- explanation: Human-readable explanation
"""
# Validate language
validate_language(language)
# Check file size
content = await file.read()
file_size_mb = len(content) / (1024 * 1024)
if file_size_mb > MAX_FILE_SIZE_MB:
raise HTTPException(
status_code=413,
detail={
"status": "error",
"message": f"File too large. Maximum size is {MAX_FILE_SIZE_MB}MB"
}
)
# Get file extension
filename = file.filename or "audio.wav"
extension = Path(filename).suffix.lower().lstrip(".")
if extension not in ALLOWED_AUDIO_FORMATS:
raise HTTPException(
status_code=400,
detail={
"status": "error",
"message": f"Unsupported file format. Allowed: {', '.join(ALLOWED_AUDIO_FORMATS)}"
}
)
try:
# Save to temp file and analyze
with tempfile.NamedTemporaryFile(suffix=f".{extension}", delete=False) as tmp:
tmp.write(content)
tmp_path = tmp.name
try:
detector = get_detector()
result = detector.analyze_file(tmp_path, language)
return result
finally:
# Clean up temp file
os.unlink(tmp_path)
except ValueError as e:
raise HTTPException(
status_code=400,
detail={"status": "error", "message": str(e)}
)
except Exception as e:
logger.exception(f"Error analyzing uploaded file: {e}")
raise HTTPException(
status_code=500,
detail={"status": "error", "message": "Failed to analyze audio"}
)
# =============================================================================
# Run with Uvicorn
# =============================================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)