Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -4,15 +4,11 @@ from fastapi import FastAPI, HTTPException, Depends, Header, Request, Body
|
|
| 4 |
from schemas import AudioInput, DetectionResult
|
| 5 |
from model_service import get_model_service, ModelService
|
| 6 |
|
| 7 |
-
app = FastAPI(
|
| 8 |
-
title="AI Voice Detection API",
|
| 9 |
-
description="Detects whether a voice sample is AI-generated or Human-spoken.",
|
| 10 |
-
version="1.0.0"
|
| 11 |
-
)
|
| 12 |
|
| 13 |
@app.on_event("startup")
|
| 14 |
async def startup_event():
|
| 15 |
-
#
|
| 16 |
print("API is starting up...")
|
| 17 |
|
| 18 |
API_KEY = "my_secret_key_123"
|
|
@@ -25,54 +21,49 @@ async def verify_api_key(x_api_key: str = Header(...)):
|
|
| 25 |
@app.post("/detect", response_model=DetectionResult)
|
| 26 |
async def detect_voice(
|
| 27 |
request: Request,
|
| 28 |
-
payload: dict = Body(..., example={"audioBase64": "
|
| 29 |
service: ModelService = Depends(get_model_service),
|
| 30 |
api_key: str = Depends(verify_api_key)
|
| 31 |
):
|
| 32 |
try:
|
| 33 |
-
# 1. Parse body manually to be flexible
|
| 34 |
audio_b64 = None
|
|
|
|
| 35 |
try:
|
| 36 |
-
# Try JSON first
|
| 37 |
body = await request.json()
|
| 38 |
-
|
| 39 |
-
for k in
|
| 40 |
if k in body and body[k]:
|
| 41 |
audio_b64 = body[k]
|
| 42 |
break
|
| 43 |
-
|
| 44 |
if not audio_b64:
|
| 45 |
for v in body.values():
|
| 46 |
if isinstance(v, str) and len(v) > 100:
|
| 47 |
audio_b64 = v
|
| 48 |
break
|
| 49 |
except Exception:
|
| 50 |
-
# FALLBACK:
|
| 51 |
raw_body = await request.body()
|
| 52 |
audio_b64 = raw_body.decode('utf-8')
|
| 53 |
|
| 54 |
if not audio_b64 or len(str(audio_b64)) < 20:
|
| 55 |
-
raise HTTPException(status_code=422, detail="No valid audio data
|
| 56 |
|
| 57 |
-
#
|
| 58 |
audio_b64 = str(audio_b64).strip().strip('"').strip("'")
|
| 59 |
if "," in audio_b64:
|
| 60 |
audio_b64 = audio_b64.split(",")[1]
|
| 61 |
|
| 62 |
-
# 3. Decode
|
| 63 |
audio_bytes = base64.b64decode(audio_b64)
|
| 64 |
-
|
| 65 |
except Exception as e:
|
| 66 |
if isinstance(e, HTTPException): raise e
|
| 67 |
-
raise HTTPException(status_code=400, detail=f"
|
| 68 |
|
| 69 |
try:
|
| 70 |
-
#
|
| 71 |
label, confidence = service.predict(audio_bytes)
|
| 72 |
return DetectionResult(label=label, confidence=confidence, message="Analysis successful")
|
| 73 |
except Exception as e:
|
| 74 |
raise HTTPException(status_code=500, detail=f"Model error: {str(e)}")
|
| 75 |
|
| 76 |
@app.get("/")
|
| 77 |
-
def read_root():
|
| 78 |
-
return {"message": "AI Voice Detection API is running. Use /detect endpoint."}
|
|
|
|
| 4 |
from schemas import AudioInput, DetectionResult
|
| 5 |
from model_service import get_model_service, ModelService
|
| 6 |
|
| 7 |
+
app = FastAPI(title="AI Voice Detection API", version="1.0.0")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
@app.on_event("startup")
|
| 10 |
async def startup_event():
|
| 11 |
+
# Fixes 504 Timeout
|
| 12 |
print("API is starting up...")
|
| 13 |
|
| 14 |
API_KEY = "my_secret_key_123"
|
|
|
|
| 21 |
@app.post("/detect", response_model=DetectionResult)
|
| 22 |
async def detect_voice(
|
| 23 |
request: Request,
|
| 24 |
+
payload: dict = Body(..., example={"audioBase64": "PASTE_HERE"}),
|
| 25 |
service: ModelService = Depends(get_model_service),
|
| 26 |
api_key: str = Depends(verify_api_key)
|
| 27 |
):
|
| 28 |
try:
|
|
|
|
| 29 |
audio_b64 = None
|
| 30 |
+
# Try JSON first (Portal vs Manual)
|
| 31 |
try:
|
|
|
|
| 32 |
body = await request.json()
|
| 33 |
+
keys = ["audioBase64", "audio_base_64", "audio", "data", "file"]
|
| 34 |
+
for k in keys:
|
| 35 |
if k in body and body[k]:
|
| 36 |
audio_b64 = body[k]
|
| 37 |
break
|
|
|
|
| 38 |
if not audio_b64:
|
| 39 |
for v in body.values():
|
| 40 |
if isinstance(v, str) and len(v) > 100:
|
| 41 |
audio_b64 = v
|
| 42 |
break
|
| 43 |
except Exception:
|
| 44 |
+
# FALLBACK: Handle if the body is just the raw Base64 string
|
| 45 |
raw_body = await request.body()
|
| 46 |
audio_b64 = raw_body.decode('utf-8')
|
| 47 |
|
| 48 |
if not audio_b64 or len(str(audio_b64)) < 20:
|
| 49 |
+
raise HTTPException(status_code=422, detail="No valid audio data.")
|
| 50 |
|
| 51 |
+
# CLEANUP: Remove quotes, spaces, and Data URI prefix
|
| 52 |
audio_b64 = str(audio_b64).strip().strip('"').strip("'")
|
| 53 |
if "," in audio_b64:
|
| 54 |
audio_b64 = audio_b64.split(",")[1]
|
| 55 |
|
|
|
|
| 56 |
audio_bytes = base64.b64decode(audio_b64)
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
if isinstance(e, HTTPException): raise e
|
| 59 |
+
raise HTTPException(status_code=400, detail=f"Parsing error: {str(e)}")
|
| 60 |
|
| 61 |
try:
|
| 62 |
+
# Inference (HUMAN or AI_GENERATED)
|
| 63 |
label, confidence = service.predict(audio_bytes)
|
| 64 |
return DetectionResult(label=label, confidence=confidence, message="Analysis successful")
|
| 65 |
except Exception as e:
|
| 66 |
raise HTTPException(status_code=500, detail=f"Model error: {str(e)}")
|
| 67 |
|
| 68 |
@app.get("/")
|
| 69 |
+
def read_root(): return {"status": "Running"}
|
|
|