Mrkomiljon commited on
Commit
9231d1c
·
verified ·
1 Parent(s): ed6ac85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -114
app.py CHANGED
@@ -1,114 +1,48 @@
1
- import os
2
- import torch
3
- import librosa
4
- import numpy as np
5
- from fastapi import FastAPI, File, UploadFile
6
- from model import RawNet
7
- from data_utils import pad # Import the pad function from data_utils.py
8
- import yaml
9
- import torch.nn.functional as F # For softmax
10
- from fastapi.responses import JSONResponse
11
- from tempfile import NamedTemporaryFile
12
- import uvicorn
13
- import webbrowser
14
-
15
- # Initialize FastAPI app
16
- app = FastAPI()
17
-
18
- # Load the model
19
- model_config_path = 'C:\\\\Users\\\\GOOD\\\\Desktop\\\\TEST-2024\\\\2021\\\\LA\\\\Baseline-RawNet2\\\\model_config_RawNet.yaml'
20
- model_path = 'C:\\\\Users\\\\GOOD\\\\Desktop\\\\TEST-2024\\\\2021\\\\LA\\\\Baseline-RawNet2\\\\checkpoints\\\\best_model.pth'
21
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
22
-
23
- with open(model_config_path, 'r') as f:
24
- model_config = yaml.safe_load(f)
25
-
26
- model = RawNet(model_config['model'], device).to(device)
27
- model.load_state_dict(torch.load(model_path, map_location=device))
28
- model.eval()
29
-
30
-
31
- def preprocess_audio_segment(segment, cut=64600):
32
- """
33
- Preprocess a single audio segment: pad or trim as required.
34
- """
35
- if len(segment) < cut:
36
- segment = pad(segment, max_len=cut) # Pad if shorter
37
- else:
38
- segment = segment[:cut] # Trim if longer
39
- return torch.tensor(segment, dtype=torch.float32).unsqueeze(0) # Add batch dimension
40
-
41
-
42
- def predict_with_sliding_window(waveform, model, device, window_size=64600, step_size=64600, sample_rate=16000):
43
- """
44
- Use a sliding window to predict if the audio is real or fake over the entire audio.
45
- """
46
- total_segments = []
47
- total_probabilities = []
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()