Views
No views yet
1# Requires: librosa
2from transformers import AutoModelForAudioClassification, AutoFeatureExtractor
3import librosa
4import torch
5import numpy as np
6
7model_id = "Tahmid98/whisper-bn-ser-SUBESCO"
8model = AutoModelForAudioClassification.from_pretrained(model_id)
9
10feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, do_normalize=True)
11id2label = model.config.id2label
12
13def preprocess_audio(audio_path, feature_extractor, max_duration=30.0):
14 audio_array, sampling_rate = librosa.load(audio_path, sr=feature_extractor.sampling_rate)
15
16 max_length = int(feature_extractor.sampling_rate * max_duration)
17 if len(audio_array) > max_length:
18 audio_array = audio_array[:max_length]
19 else:
20 audio_array = np.pad(audio_array, (0, max_length - len(audio_array)))
21
22 inputs = feature_extractor(
23 audio_array,
24 sampling_rate=feature_extractor.sampling_rate,
25 max_length=max_length,
26 truncation=True,
27 return_tensors="pt",
28 )
29 return inputs
30
31
32def predict_emotion(audio_path, model, feature_extractor, id2label, max_duration=30.0):
33 inputs = preprocess_audio(audio_path, feature_extractor, max_duration)
34
35 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36 model = model.to(device)
37 inputs = {key: value.to(device) for key, value in inputs.items()}
38
39 with torch.no_grad():
40 outputs = model(**inputs)
41
42 logits = outputs.logits
43 predicted_id = torch.argmax(logits, dim=-1).item()
44 predicted_label = id2label[predicted_id]
45
46 return predicted_label
47
48
49audio_path = "Your audio path in the working directory"
50predicted_emotion = predict_emotion(audio_path, model, feature_extractor, id2label)
51print(f"Predicted Emotion: {predicted_emotion}")