Update app.py
Browse files
app.py
CHANGED
|
@@ -1,114 +1,48 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
from
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
# Sliding window processing
|
| 50 |
-
for start in range(0, len(waveform), step_size):
|
| 51 |
-
end = start + window_size
|
| 52 |
-
segment = waveform[start:end]
|
| 53 |
-
|
| 54 |
-
# Preprocess the segment
|
| 55 |
-
audio_tensor = preprocess_audio_segment(segment).to(device)
|
| 56 |
-
|
| 57 |
-
# Perform inference
|
| 58 |
-
with torch.no_grad():
|
| 59 |
-
output = model(audio_tensor)
|
| 60 |
-
probabilities = F.softmax(output, dim=1) # Compute probabilities
|
| 61 |
-
prediction = torch.argmax(probabilities, dim=1)
|
| 62 |
-
|
| 63 |
-
# Store the results
|
| 64 |
-
predicted_class = "Human voice" if prediction.item() == 1 else "AI generated voice (TTS)"
|
| 65 |
-
probability = probabilities[0, prediction.item()].item() * 100
|
| 66 |
-
total_segments.append(predicted_class)
|
| 67 |
-
total_probabilities.append(probability)
|
| 68 |
-
|
| 69 |
-
# Final aggregation
|
| 70 |
-
majority_class = max(set(total_segments), key=total_segments.count) # Majority voting
|
| 71 |
-
avg_probability = np.mean(total_probabilities) # Average probability
|
| 72 |
-
|
| 73 |
-
return majority_class, avg_probability
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
@app.post("/predict")
|
| 77 |
-
async def predict_audio(file: UploadFile = File(...)):
|
| 78 |
-
"""
|
| 79 |
-
Endpoint to process audio and predict using the RawNet model.
|
| 80 |
-
"""
|
| 81 |
-
try:
|
| 82 |
-
# Save uploaded file to a temporary file
|
| 83 |
-
with NamedTemporaryFile(delete=False) as temp_file:
|
| 84 |
-
temp_file.write(await file.read())
|
| 85 |
-
temp_filename = temp_file.name
|
| 86 |
-
|
| 87 |
-
# Load audio file
|
| 88 |
-
waveform, _ = librosa.load(temp_filename, sr=16000)
|
| 89 |
-
|
| 90 |
-
# Perform prediction
|
| 91 |
-
result, avg_probability = predict_with_sliding_window(waveform, model, device)
|
| 92 |
-
|
| 93 |
-
# Clean up temporary file
|
| 94 |
-
os.remove(temp_filename)
|
| 95 |
-
|
| 96 |
-
return JSONResponse({
|
| 97 |
-
"Your audio": result,
|
| 98 |
-
"average_probability": f"{avg_probability:.2f}%"
|
| 99 |
-
})
|
| 100 |
-
|
| 101 |
-
except Exception as e:
|
| 102 |
-
return JSONResponse({"error": str(e)}, status_code=500)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
@app.get("/")
|
| 106 |
-
async def root():
|
| 107 |
-
return {"message": "RawNet Sliding Window Prediction API"}
|
| 108 |
-
|
| 109 |
-
# Automatically open docs or print URL when server starts
|
| 110 |
-
if __name__ == "__main__":
|
| 111 |
-
url = "http://127.0.0.1:8000/docs"
|
| 112 |
-
print(f"API docs available at: {url}")
|
| 113 |
-
webbrowser.open(url) # Open in the default browser
|
| 114 |
-
uvicorn.run(app, host="127.0.0.1", port=8000)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import librosa
|
| 3 |
+
import numpy as np
|
| 4 |
+
import onnxruntime as ort
|
| 5 |
+
from data_utils import pad
|
| 6 |
+
|
| 7 |
+
# Preprocess a single audio segment
|
| 8 |
+
def preprocess_audio_segment(segment, cut=64600):
|
| 9 |
+
if len(segment) < cut:
|
| 10 |
+
segment = pad(segment, max_len=cut)
|
| 11 |
+
else:
|
| 12 |
+
segment = segment[:cut]
|
| 13 |
+
return np.expand_dims(np.array(segment, dtype=np.float32), axis=0)
|
| 14 |
+
|
| 15 |
+
# Sliding window prediction function
|
| 16 |
+
def predict(audio_path, onnx_model_path="RawNet_model.onnx", window_size=64600, step_size=64600, sample_rate=16000):
|
| 17 |
+
# Load ONNX model
|
| 18 |
+
ort_session = ort.InferenceSession(onnx_model_path)
|
| 19 |
+
waveform, _ = librosa.load(audio_path, sr=sample_rate)
|
| 20 |
+
total_segments = []
|
| 21 |
+
total_probabilities = []
|
| 22 |
+
|
| 23 |
+
for start in range(0, len(waveform), step_size):
|
| 24 |
+
end = start + window_size
|
| 25 |
+
segment = waveform[start:end]
|
| 26 |
+
audio_tensor = preprocess_audio_segment(segment)
|
| 27 |
+
inputs = {ort_session.get_inputs()[0].name: audio_tensor}
|
| 28 |
+
outputs = ort_session.run(None, inputs)
|
| 29 |
+
probabilities = np.exp(outputs[0])
|
| 30 |
+
prediction = np.argmax(probabilities)
|
| 31 |
+
|
| 32 |
+
predicted_class = "Real" if prediction == 1 else "Fake"
|
| 33 |
+
total_segments.append(predicted_class)
|
| 34 |
+
|
| 35 |
+
majority_class = max(set(total_segments), key=total_segments.count)
|
| 36 |
+
return f"Prediction: {majority_class}"
|
| 37 |
+
|
| 38 |
+
# Gradio interface
|
| 39 |
+
interface = gr.Interface(
|
| 40 |
+
fn=predict,
|
| 41 |
+
inputs=[gr.Audio(source="upload", type="filepath")],
|
| 42 |
+
outputs="text",
|
| 43 |
+
title="Audio Spoof Detection",
|
| 44 |
+
description="Upload an audio file to determine if it is Real or Fake using an ONNX model."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|