File size: 10,704 Bytes
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a75a0
ef79c08
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a75a0
ef79c08
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94d29ee
0468ff5
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"""
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)