File size: 1,855 Bytes
4500af5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from transformers import HubertForSequenceClassification, HubertConfig, Wav2Vec2FeatureExtractor
import torch
import soundfile as sf

# Load model and tokenizer
model_name = "model_hubert_finetuned_nopeft.pth"  # Replace with your model path or Hugging Face model hub path
config = HubertConfig.from_pretrained(model_name)
config.id2label = {0: 'neu', 1: 'hap', 2: 'ang', 3: 'sad', 4: 'dis', 5: 'sur', 6: 'fea', 7: 'cal'}
config.label2id = {"neu": 0, "hap": 1, "ang": 2, "sad": 3, "dis": 4, "sur": 5, "fea": 6, "cal": 7}
config.num_labels = 8  # Set it to the number of classes in your SER task

# Load the pre-trained model with the modified configuration
model = HubertForSequenceClassification.from_pretrained(model_name, config=config, ignore_mismatched_sizes=True)
model.to('cuda' if torch.cuda.is_available() else 'cpu')
model.eval()

# Load feature extractor
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("superb/hubert-large-superb-er")

st.title("Speech Emotion Recognition Model")

uploaded_file = st.file_uploader("Upload an audio file", type=["wav"])

if uploaded_file is not None:
    # Load audio file
    audio_input, sampling_rate = sf.read(uploaded_file)
    
    # Preprocess audio input
    inputs = feature_extractor(audio_input, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
    inputs = {key: value.to('cuda' if torch.cuda.is_available() else 'cpu') for key, value in inputs.items()}
    
    # Get prediction
    with torch.no_grad():
        outputs = model(**inputs)
        logits = outputs.logits
        probabilities = torch.softmax(logits, dim=-1)
        predicted_class = torch.argmax(probabilities, dim=1).item()
    
    # Display prediction
    st.write(f"Predicted class: {config.id2label[predicted_class]}")
    st.write(f"Class probabilities: {probabilities}")