ROSHANNN123 commited on
Commit
8208813
·
verified ·
1 Parent(s): b8a1c24

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +76 -87
main.py CHANGED
@@ -1,87 +1,76 @@
1
- import base64
2
- import binascii
3
- from fastapi import FastAPI, HTTPException, Depends, Header
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
- # Initialize model on startup
16
- get_model_service()
17
-
18
- API_KEY = "my_secret_key_123" # Simple hardcoded key for submission
19
-
20
- async def verify_api_key(x_api_key: str = Header(...)):
21
- if x_api_key != API_KEY:
22
- raise HTTPException(status_code=401, detail="Invalid API Key")
23
- return x_api_key
24
-
25
- from fastapi import FastAPI, HTTPException, Depends, Header, Request
26
-
27
- # ... (Previous imports stay, schema can stay unused or updated)
28
-
29
- @app.post("/detect", response_model=DetectionResult)
30
- async def detect_voice(
31
- request: Request,
32
- service: ModelService = Depends(get_model_service),
33
- api_key: str = Depends(verify_api_key)
34
- ):
35
- try:
36
- # 1. Parse JSON body manually to be flexible
37
- body = await request.json()
38
- print(f"DEBUG: Received Body Keys: {list(body.keys())}")
39
-
40
- # 2. Look for the base64 string in common keys using a priority list
41
- # OR just grab the first string value that looks like base64
42
- audio_b64 = None
43
-
44
- # Check specific keys first
45
- possible_keys = ["audio_base64", "audio", "data", "file", "encoded_audio", "mp3"]
46
- for k in possible_keys:
47
- if k in body and body[k]:
48
- audio_b64 = body[k]
49
- print(f"DEBUG: Found audio in key: '{k}'")
50
- break
51
-
52
- # Fallback: Search ALL values for a long string
53
- if not audio_b64:
54
- for k, v in body.items():
55
- if isinstance(v, str) and len(v) > 100:
56
- audio_b64 = v
57
- print(f"DEBUG: Found audio in generic key: '{k}'")
58
- break
59
-
60
- if not audio_b64:
61
- raise HTTPException(status_code=422, detail=f"Could not find audio data. Received keys: {list(body.keys())}")
62
-
63
- # Decode Base64 string
64
- # Handle data URI scheme if present (e.g. "data:audio/mp3;base64,...")
65
- if "," in audio_b64:
66
- audio_b64 = audio_b64.split(",")[1]
67
-
68
- audio_bytes = base64.b64decode(audio_b64)
69
- except Exception as e:
70
- print(f"Error parsing request: {e}")
71
- raise HTTPException(status_code=400, detail=f"Invalid Request: {str(e)}")
72
-
73
- try:
74
- label, confidence = service.predict(audio_bytes)
75
- return DetectionResult(
76
- label=label,
77
- confidence=confidence,
78
- message="Analysis successful"
79
- )
80
- except ValueError as ve:
81
- raise HTTPException(status_code=400, detail=str(ve))
82
- except Exception as e:
83
- raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
84
-
85
- @app.get("/")
86
- def read_root():
87
- return {"message": "AI Voice Detection API is running. Use /detect endpoint."}
 
1
+ import base64
2
+ import binascii
3
+ 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
+ # Pre-load model on startup
16
+ get_model_service()
17
+
18
+ API_KEY = "my_secret_key_123"
19
+
20
+ async def verify_api_key(x_api_key: str = Header(...)):
21
+ if x_api_key != API_KEY:
22
+ raise HTTPException(status_code=401, detail="Invalid API Key")
23
+ return x_api_key
24
+
25
+ @app.post("/detect", response_model=DetectionResult)
26
+ async def detect_voice(
27
+ # 'Body' forces the input box to appear in Swagger/Docs
28
+ body: dict = Body(..., example={"audio_base64": "PASTE_YOUR_BASE64_HERE"}),
29
+ service: ModelService = Depends(get_model_service),
30
+ api_key: str = Depends(verify_api_key)
31
+ ):
32
+ try:
33
+ # 1. Universal Search: find the base64 string in the body
34
+ audio_b64 = None
35
+ possible_keys = ["audio_base64", "audio", "data", "file", "encoded_audio", "mp3"]
36
+
37
+ # Check priority keys
38
+ for k in possible_keys:
39
+ if k in body and body[k]:
40
+ audio_b64 = body[k]
41
+ break
42
+
43
+ # Fallback: search all values for a long string if no common key is found
44
+ if not audio_b64:
45
+ for k, v in body.items():
46
+ if isinstance(v, str) and len(v) > 100:
47
+ audio_b64 = v
48
+ break
49
+
50
+ if not audio_b64:
51
+ raise HTTPException(status_code=422, detail="Could not find audio data in your request.")
52
+
53
+ # 2. Cleanup Base64 (remove data URI prefixes if they exist)
54
+ if "," in audio_b64:
55
+ audio_b64 = audio_b64.split(",")[1]
56
+
57
+ # 3. Decode
58
+ audio_bytes = base64.b64decode(audio_b64)
59
+
60
+ except Exception as e:
61
+ raise HTTPException(status_code=400, detail=f"Request formatting error: {str(e)}")
62
+
63
+ try:
64
+ # 4. Predict
65
+ label, confidence = service.predict(audio_bytes)
66
+ return DetectionResult(
67
+ label=label,
68
+ confidence=confidence,
69
+ message="Analysis successful"
70
+ )
71
+ except Exception as e:
72
+ raise HTTPException(status_code=500, detail=f"Model error: {str(e)}")
73
+
74
+ @app.get("/")
75
+ def read_root():
76
+ return {"message": "AI Voice Detection API is running. Use /detect endpoint."}