Devved11/RestAPI_AI_VOICE_DETECTION
0
1from fastapi import FastAPI, Header, HTTPException
2from pydantic import BaseModel
3import base64
4import numpy as np
5import pydub
6import tempfile
7import os
8from dotenv import load_dotenv
9load_dotenv()
10
11from models import detect_audio
12
13app = FastAPI(title="AI-Generated Voice Detection API - GUVI Hackathon")
14
15API_KEY = os.getenv("API_KEY")
16
17
18class AudioInput(BaseModel):
19 language: str
20 audioFormat: str
21 audioBase64: str
22
23
24@app.post("/api/voice-detection")
25def detect_voice(
26 input_data: AudioInput,
27 x_api_key: str = Header(None, alias="x-api-key")
28):
29 if x_api_key != API_KEY:
30 raise HTTPException(status_code=401, detail="Invalid API key")
31
32 if input_data.audioFormat.lower() != "mp3":
33 raise HTTPException(status_code=400, detail="Only mp3 supported")
34
35 try:
36 audio_bytes = base64.b64decode(input_data.audioBase64)
37
38 with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp:
39 tmp.write(audio_bytes)
40 tmp_path = tmp.name
41
42 try:
43 segment = pydub.AudioSegment.from_file(tmp_path, format="mp3")
44 finally:
45 os.remove(tmp_path)
46
47 segment = segment.set_channels(1).set_frame_rate(16000)
48 samples = segment.get_array_of_samples()
49 y = np.array(samples, dtype=np.float32) / 32768.0
50
51 classification, confidence, explanation = detect_audio(y)
52
53 return {
54 "status": "success",
55 "languageProvided": input_data.language,
56 "classification": classification,
57 "confidenceScore": confidence,
58 "explanation": explanation
59 }
60
61 except Exception as e:
62 raise HTTPException(status_code=400, detail=str(e))
63
64
65@app.get("/health")
66def health():
67 return {"status": "healthy"}
68
69
70@app.get("/")
71def root():
72 return {"message": "AI Voice Detection API - Ready"}
73 