Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import librosa
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# Load the saved model
|
| 7 |
+
model = tf.keras.models.load_model("voice_authentication_model.keras")
|
| 8 |
+
|
| 9 |
+
# Function to extract features from audio
|
| 10 |
+
def extract_features(file_path):
|
| 11 |
+
try:
|
| 12 |
+
# Load the audio file
|
| 13 |
+
audio, sample_rate = librosa.load(file_path, res_type='kaiser_fast', duration=3, sr=None)
|
| 14 |
+
|
| 15 |
+
# Extract MFCC features (13 MFCC coefficients)
|
| 16 |
+
mfcc = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=13)
|
| 17 |
+
mfcc = np.mean(mfcc.T, axis=0) # Taking the mean over time
|
| 18 |
+
|
| 19 |
+
return mfcc
|
| 20 |
+
except Exception as e:
|
| 21 |
+
print(f"Error encountered while parsing file: {file_path}. Error: {e}")
|
| 22 |
+
return None
|
| 23 |
+
|
| 24 |
+
# Prediction function for user vs non-user
|
| 25 |
+
def predict_user_or_nonuser(audio):
|
| 26 |
+
# Extract features from the uploaded audio
|
| 27 |
+
feature = extract_features(audio.name) # Audio file is passed as Gradio interface's input
|
| 28 |
+
if feature is None:
|
| 29 |
+
return "Error: Unable to process audio"
|
| 30 |
+
|
| 31 |
+
# Reshape feature to match the model's input format (1, time_steps, 1)
|
| 32 |
+
feature = feature.reshape(1, feature.shape[0], 1)
|
| 33 |
+
|
| 34 |
+
# Make prediction
|
| 35 |
+
prediction = model.predict(feature)
|
| 36 |
+
|
| 37 |
+
# Return result: User or Non-User
|
| 38 |
+
return "User" if prediction > 0.5 else "Non-User"
|
| 39 |
+
|
| 40 |
+
# Create a Gradio interface for the app
|
| 41 |
+
iface = gr.Interface(
|
| 42 |
+
fn=predict_user_or_nonuser, # Function to call for prediction
|
| 43 |
+
inputs=gr.Audio(source="upload", type="file"), # Audio input
|
| 44 |
+
outputs="text", # Output: Text label ("User" or "Non-User")
|
| 45 |
+
title="Voice Authentication",
|
| 46 |
+
description="This application can authenticate users based on their voice. Upload an audio file to check if it's from the user or a non-user."
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Launch the Gradio app
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
iface.launch()
|