SERTEST / main.py
MohamedSamir030's picture
Upload main.py
e751c2a verified
Raw History Blame Contribute Delete
1.93 kB
import gradio as gr
import numpy as np
import librosa
from keras.models import load_model
from sklearn.preprocessing import OneHotEncoder
# Load the trained model
model_path = r"C:\Users\user\Downloads\D__zidio2_emotion_recognition_model.h5" # Update with your path
model = load_model(model_path)
# Define the emotions
emotions = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'ps', 'sad']
enc = OneHotEncoder(categories=[emotions], sparse_output=False)
enc.fit([[emotion] for emotion in emotions]) # Fit the encoder with the emotion categories
# Feature extraction function
def extract_features(filename):
y, sr = librosa.load(filename, duration=3, offset=0.5)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)
mfcc_delta = librosa.feature.delta(mfcc)
mfcc_delta2 = librosa.feature.delta(mfcc, order=2)
chroma = librosa.feature.chroma_stft(y=y, sr=sr)
mfcc_mean = np.mean(mfcc, axis=1)
mfcc_delta_mean = np.mean(mfcc_delta, axis=1)
mfcc_delta2_mean = np.mean(mfcc_delta2, axis=1)
chroma_mean = np.mean(chroma, axis=1)
features = np.hstack([mfcc_mean, mfcc_delta_mean, mfcc_delta2_mean, chroma_mean])
return features
# Prediction function
def predict_emotion(audio_path):
features = extract_features(audio_path)
features = np.expand_dims(features, axis=0)
features = np.expand_dims(features, axis=-1)
prediction = model.predict(features)
predicted_emotion = enc.inverse_transform(prediction)
return predicted_emotion[0][0]
# Gradio interface
def classify_audio(audio):
return predict_emotion(audio)
# Gradio interface setup
interface = gr.Interface(
fn=classify_audio,
inputs=gr.Audio(type="filepath"),
outputs="text",
title="Speech Emotion Recognition",
description="Upload or record an audio file to classify its emotion."
)
interface.launch(share=True)