Spaces:
Runtime error

Dev-ML12 commited on
Commit
f64d8fb
·
verified ·
1 Parent(s): b19e6a1

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import base64
3
+ import numpy as np
4
+ import audioop
5
+ from scipy.signal import resample
6
+ import onnxruntime as ort
7
+ from fastapi import FastAPI, WebSocket
8
+ import gradio as gr
9
+
10
+ app = FastAPI()
11
+
12
+ session = ort.InferenceSession("model.onnx")
13
+
14
+ @app.get("/")
15
+ def home():
16
+ return {"status": "Fraud Shield AI Engine is Active via Gradio Wrapper"}
17
+
18
+ # 3. Real-Time Telephony WebSocket Endpoint
19
+ @app.websocket("/media-stream")
20
+ async def handle_twilio_stream(websocket: WebSocket):
21
+ await websocket.accept()
22
+ print("🚀 Twilio Call Connected via Live Media Stream WebSocket")
23
+
24
+ audio_buffer = bytearray()
25
+
26
+ try:
27
+ while True:
28
+ # Twilio streams packets continuously over the WebSocket
29
+ message = await websocket.receive_text()
30
+ data = json.loads(message)
31
+
32
+ if data['event'] == 'media':
33
+ # Extract the 20ms base64 chunk
34
+ payload = data['media']['payload']
35
+ chunk = base64.b64decode(payload)
36
+
37
+ # Step A: Convert 8-bit Mu-Law telecom audio to 16-bit Linear PCM
38
+ pcm_data = audioop.ulaw2lin(chunk, 2)
39
+ audio_buffer.extend(pcm_data)
40
+
41
+ # Process audio continuously in 1-second sliding windows (16,000 bytes at 8kHz)
42
+ if len(audio_buffer) >= 16000:
43
+ raw_audio = np.frombuffer(audio_buffer, dtype=np.int16).astype(np.float32)
44
+ audio_buffer = bytearray() # Reset buffer for the next sliding frame
45
+
46
+ # Step B: Standardize the magnitude bounds
47
+ max_val = np.max(np.abs(raw_audio))
48
+ if max_val > 0:
49
+ raw_audio /= max_val
50
+
51
+ # Step C: Upsample the 8kHz Twilio track to the model's native 16kHz structure
52
+ num_samples = int(len(raw_audio) * (16000 / 8000))
53
+ resampled_audio = resample(raw_audio, num_samples).astype(np.float32)
54
+
55
+ # Step D: Run ONNX Real-Time Inference
56
+ inputs = {session.get_inputs()[0].name: np.expand_dims(resampled_audio, axis=0)}
57
+ outputs = session.run(None, inputs)
58
+ logits = outputs[0]
59
+
60
+ # Step E: Apply Softmax to extract the absolute Deepfake Confidence Score
61
+ exp_logits = np.exp(logits - np.max(logits))
62
+ probabilities = exp_logits / np.sum(exp_logits)
63
+
64
+ # Index 0 = Real (Bona Fide), Index 1 = Fake (Synthetic Deepfake)
65
+ fake_confidence = float(probabilities[0][1])
66
+
67
+ # Broadcast the real-time score out to the terminal console
68
+ verdict = "⚠️ DEEPFAKE DETECTED" if fake_confidence > 0.80 else "✅ HUMAN VERIFIED"
69
+ print(f"[{verdict}] Confidence Score: {fake_confidence * 100:.2f}%")
70
+
71
+ except Exception as e:
72
+ print(f"Call disconnected or stream ended: {e}")
73
+ finally:
74
+ await websocket.close()
75
+
76
+
77
+ with gr.Blocks() as ui:
78
+ gr.Markdown("# 🛡️ Fraud Shield Live Deepfake Detection Backend")
79
+ gr.Markdown("The background server is up and listening for Twilio WebSocket pipelines.")
80
+
81
+ app = gr.routes.mount_gradio_app(app, ui, path="/")