File size: 1,898 Bytes
595bf80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
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
50
51
52
53
54
55
import gradio as gr
from speechbrain.pretrained.interfaces import foreign_class
import os

# Function to get the list of audio files in the 'rec/' directory
def get_audio_files_list(directory="rec"):
    try:
        return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    except FileNotFoundError:
        print("The 'rec' directory does not exist. Please make sure it is the correct path.")
        return []

# Loading the speechbrain emotion detection model
learner = foreign_class(
    source="speechbrain/emotion-recognition-wav2vec2-IEMOCAP",
    pymodule_file="custom_interface.py",
    classname="CustomEncoderWav2vec2Classifier"
)

# Building prediction function for Gradio
emotion_dict = {
    'sad': 'Sad',
    'hap': 'Happy',
    'ang': 'Anger',
    'fea': 'Fear',
    'sur': 'Surprised',
    'neu': 'Neutral'
}

def selected_audio(audio_file):
    if audio_file is None:
        return None, "Please select an audio file."
    file_path = os.path.join("rec", audio_file)
    audio_data = gr.Audio(file=file_path)
    out_prob, score, index, text_lab = learner.classify_file(file_path)
    emotion = emotion_dict[text_lab[0]]
    return audio_data, emotion

# Get the list of audio files for the dropdown
audio_files_list = get_audio_files_list()

# Define Gradio blocks
with gr.Blocks() as blocks:
    gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>" +
                "Audio Emotion Detection" +
                "</h1>")
    with gr.Column():
        input_audio_dropdown = gr.Dropdown(label="Select Audio", choices=audio_files_list)
        audio_ui = gr.Audio()
        output_text = gr.Textbox(label="Detected Emotion!")
        detect_btn = gr.Button("Detect Emotion")
        detect_btn.click(selected_audio, inputs=input_audio_dropdown, outputs=[audio_ui, output_text])

# Launch the Gradio blocks interface
blocks.launch()