ROSHANNN123 commited on
Commit
3ca298d
·
verified ·
1 Parent(s): 14fb181

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +26 -26
main.py CHANGED
@@ -12,7 +12,7 @@ app = FastAPI(
12
 
13
  @app.on_event("startup")
14
  async def startup_event():
15
- # EXTREMELY IMPORTANT: Instant startup to prevent 504 Timeout
16
  print("API is starting up...")
17
 
18
  API_KEY = "my_secret_key_123"
@@ -25,34 +25,37 @@ 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
- # This line ensures the "Request body" box appears in your /docs test page
29
  payload: dict = Body(..., example={"audioBase64": "PASTE_BASE64_HERE"}),
30
  service: ModelService = Depends(get_model_service),
31
  api_key: str = Depends(verify_api_key)
32
  ):
33
  try:
34
- # 1. Flexible parsing for portal compatibility (audioBase64, audio_base_64, etc.)
35
- body = await request.json()
36
  audio_b64 = None
37
-
38
- # Check all possible key variants including camelCase for the portal
39
- possible_keys = ["audioBase64", "audio_base_64", "audio_base64", "audio", "data", "file"]
40
- for k in possible_keys:
41
- if k in body and body[k]:
42
- audio_b64 = body[k]
43
- break
44
-
45
- # Fallback: search for any long string value
46
- if not audio_b64:
47
- for v in body.values():
48
- if isinstance(v, str) and len(v) > 100:
49
- audio_b64 = v
50
  break
 
 
 
 
 
 
 
 
 
 
51
 
52
- if not audio_b64:
53
- raise HTTPException(status_code=422, detail="No audio data found.")
54
 
55
- # 2. Cleanup (Remove Data URI prefix like "data:audio/mp3;base64,")
 
56
  if "," in audio_b64:
57
  audio_b64 = audio_b64.split(",")[1]
58
 
@@ -60,16 +63,13 @@ async def detect_voice(
60
  audio_bytes = base64.b64decode(audio_b64)
61
 
62
  except Exception as e:
 
63
  raise HTTPException(status_code=400, detail=f"Request parsing error: {str(e)}")
64
 
65
  try:
66
- # 4. AI Inference (Returns label: HUMAN/AI_GENERATED and score)
67
  label, confidence = service.predict(audio_bytes)
68
- return DetectionResult(
69
- label=label,
70
- confidence=confidence,
71
- message="Analysis successful"
72
- )
73
  except Exception as e:
74
  raise HTTPException(status_code=500, detail=f"Model error: {str(e)}")
75
 
 
12
 
13
  @app.on_event("startup")
14
  async def startup_event():
15
+ # Instant startup to prevent 504 Timeout
16
  print("API is starting up...")
17
 
18
  API_KEY = "my_secret_key_123"
 
25
  @app.post("/detect", response_model=DetectionResult)
26
  async def detect_voice(
27
  request: Request,
 
28
  payload: dict = Body(..., example={"audioBase64": "PASTE_BASE64_HERE"}),
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
+ possible_keys = ["audioBase64", "audio_base_64", "audio", "data", "file"]
39
+ for k in possible_keys:
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: If not JSON, the body might be the raw Base64 string
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 found.")
56
 
57
+ # 2. Cleanup whitespace or quotes from copy-pasting
58
+ audio_b64 = str(audio_b64).strip().strip('"').strip("'")
59
  if "," in audio_b64:
60
  audio_b64 = audio_b64.split(",")[1]
61
 
 
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"Request parsing error: {str(e)}")
68
 
69
  try:
70
+ # 4. AI Inference
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