File size: 1,491 Bytes
98a69c9
5759877
c7bc375
1253b4a
98a69c9
1253b4a
 
5759877
98a69c9
25fbd7f
 
 
 
 
 
98a69c9
 
 
 
 
 
c7bc375
98a69c9
 
 
 
 
 
 
 
 
25fbd7f
 
98a69c9
 
5759877
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
import torch
import torchaudio
import gradio as gr
from transformers import Wav2Vec2FeatureExtractor,AutoConfig,pipeline

config = AutoConfig.from_pretrained("SeyedAli/Persian-Speech-Emotion-HuBert-V1")
model = Wav2Vec2FeatureExtractor.from_pretrained("SeyedAli/Persian-Speech-Emotion-HuBert-V1")

def speech_file_to_array_fn(path, sampling_rate):
   with tempfile.NamedTemporaryFile(suffix=".wav") as temp_audio_file:
    # Copy the contents of the uploaded audio file to the temporary file
    temp_audio_file.write(open(path, "rb").read())
    temp_audio_file.flush()
    # Load the audio file using torchaudio
    speech_array, _sampling_rate = torchaudio.load(temp_audio_file.name)
    resampler = torchaudio.transforms.Resample(_sampling_rate)
    speech = resampler(speech_array).squeeze().numpy()
    return speech

def predict(path, sampling_rate):
    speech = speech_file_to_array_fn(path, sampling_rate)
    inputs = model(speech, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
    inputs = {key: inputs[key].to(device) for key in inputs}

    with torch.no_grad():
        logits = model(**inputs).logits

    scores = F.softmax(logits, dim=1).detach().cpu().numpy()[0]
    outputs = [{"Label": config.id2label[i], "Score": f"{round(score * 100, 3):.1f}%"} for i, score in enumerate(scores)]
    return outputs

def SER(audio):
    return predict(audio,model.sampling_rate)

iface = gr.Interface(fn=SER, inputs="audio", outputs="text")
iface.launch(share=False)