Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,77 +1,80 @@
|
|
|
|
1 |
import librosa
|
2 |
import numpy as np
|
3 |
import torch
|
|
|
4 |
import logging
|
5 |
-
from transformers import
|
6 |
-
import gradio as gr
|
7 |
|
|
|
8 |
logging.basicConfig(level=logging.INFO)
|
9 |
|
10 |
-
#
|
11 |
-
|
12 |
-
|
13 |
-
model = Wav2Vec2ForSequenceClassification.from_pretrained(model_path)
|
14 |
-
processor = Wav2Vec2Processor.from_pretrained(model_path)
|
15 |
-
logging.info("Model and processor loaded successfully.")
|
16 |
-
except Exception as e:
|
17 |
-
logging.error(f"Loading model and processor failed: {e}")
|
18 |
-
raise e
|
19 |
|
20 |
-
def
|
21 |
"""
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
"""
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
|
29 |
-
sr = 16000
|
30 |
-
return audio, sr
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
|
|
38 |
|
39 |
-
|
|
|
|
|
|
|
40 |
"""
|
41 |
-
|
|
|
|
|
|
|
|
|
42 |
"""
|
43 |
try:
|
44 |
-
|
45 |
-
input_values = audio_to_features(audio, sr)
|
46 |
-
|
47 |
-
# Inference
|
48 |
with torch.no_grad():
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
# Assuming you have a binary classification model for simplicity
|
55 |
-
# Modify this part based on your actual number of classes and labels
|
56 |
-
labels = ['Class 0', 'Class 1'] # Example labels
|
57 |
-
predictions = dict(zip(labels, probabilities[0]))
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
return prediction_output
|
62 |
except Exception as e:
|
63 |
-
|
64 |
-
|
|
|
|
|
65 |
|
66 |
-
# Gradio interface
|
67 |
iface = gr.Interface(
|
68 |
-
fn=
|
69 |
-
inputs=gr.
|
70 |
-
outputs="
|
71 |
-
title="
|
72 |
-
description="Upload an audio file to
|
73 |
)
|
74 |
|
75 |
-
#
|
76 |
-
|
77 |
-
iface.launch()
|
|
|
1 |
+
import gradio as gr
|
2 |
import librosa
|
3 |
import numpy as np
|
4 |
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
import logging
|
7 |
+
from transformers import AutoModelForAudioClassification
|
|
|
8 |
|
9 |
+
# Configure logging for debugging and information
|
10 |
logging.basicConfig(level=logging.INFO)
|
11 |
|
12 |
+
# Model loading from the specified local path
|
13 |
+
local_model_path = "./"
|
14 |
+
model = AutoModelForAudioClassification.from_pretrained(local_model_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
def custom_feature_extraction(audio_file_path, sr=16000, n_mels=128, n_fft=2048, hop_length=512, target_length=1024):
|
17 |
"""
|
18 |
+
Custom feature extraction using Mel spectrogram, tailored for models trained on datasets like AudioSet.
|
19 |
+
Args:
|
20 |
+
audio_file_path: Path to the audio file for prediction.
|
21 |
+
sr: Target sampling rate for the audio file.
|
22 |
+
n_mels: Number of Mel bands to generate.
|
23 |
+
n_fft: Length of the FFT window.
|
24 |
+
hop_length: Number of samples between successive frames.
|
25 |
+
target_length: Expected length of the Mel spectrogram in the time dimension.
|
26 |
+
Returns:
|
27 |
+
A tensor representation of the Mel spectrogram features.
|
28 |
"""
|
29 |
+
waveform, sample_rate = librosa.load(audio_file_path, sr=sr)
|
30 |
+
S = librosa.feature.melspectrogram(y=waveform, sr=sample_rate, n_mels=n_mels, n_fft=n_fft, hop_length=hop_length)
|
31 |
+
S_DB = librosa.power_to_db(S, ref=np.max)
|
32 |
+
mel_tensor = torch.tensor(S_DB).float()
|
|
|
|
|
|
|
33 |
|
34 |
+
# Ensure the tensor matches the expected sequence length
|
35 |
+
current_length = mel_tensor.shape[1]
|
36 |
+
if current_length > target_length:
|
37 |
+
mel_tensor = mel_tensor[:, :target_length] # Truncate if longer
|
38 |
+
elif current_length < target_length:
|
39 |
+
padding = target_length - current_length
|
40 |
+
mel_tensor = F.pad(mel_tensor, (0, padding), "constant", 0) # Pad if shorter
|
41 |
|
42 |
+
mel_tensor = mel_tensor.unsqueeze(0) # Add batch dimension for compatibility with model
|
43 |
+
return mel_tensor
|
44 |
+
|
45 |
+
def predict_voice(audio_file_path):
|
46 |
"""
|
47 |
+
Predicts the audio class using a pre-trained model and custom feature extraction.
|
48 |
+
Args:
|
49 |
+
audio_file_path: Path to the audio file for prediction.
|
50 |
+
Returns:
|
51 |
+
A string containing the predicted class and confidence level.
|
52 |
"""
|
53 |
try:
|
54 |
+
features = custom_feature_extraction(audio_file_path)
|
|
|
|
|
|
|
55 |
with torch.no_grad():
|
56 |
+
outputs = model(features)
|
57 |
+
logits = outputs.logits
|
58 |
+
predicted_index = logits.argmax()
|
59 |
+
label = model.config.id2label[predicted_index.item()]
|
60 |
+
confidence = torch.softmax(logits, dim=1).max().item() * 100
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
result = f"The voice is classified as '{label}' with a confidence of {confidence:.2f}%."
|
63 |
+
logging.info("Prediction successful.")
|
|
|
64 |
except Exception as e:
|
65 |
+
result = f"Error during processing: {e}"
|
66 |
+
logging.error(result)
|
67 |
+
|
68 |
+
return result
|
69 |
|
70 |
+
# Setting up the Gradio interface
|
71 |
iface = gr.Interface(
|
72 |
+
fn=predict_voice,
|
73 |
+
inputs=gr.Audio(label="Upload Audio File", type="filepath"),
|
74 |
+
outputs=gr.Textbox(label="Prediction"),
|
75 |
+
title="Voice Authenticity Detection",
|
76 |
+
description="Detects whether a voice is real or AI-generated. Upload an audio file to see the results."
|
77 |
)
|
78 |
|
79 |
+
# Launching the interface
|
80 |
+
iface.launch()
|
|