Views
No views yet
microsoft/wavlm-base-plus model for
7-class speech emotion recognition.1import onnxruntime as ort
2import numpy as np
3import librosa
4from transformers import AutoFeatureExtractor # Needed for feature extraction
5
6# Define constants (should match training config)
7SAMPLE_RATE = {config_data.get("sample_rate", 16000)}
8MAX_DURATION = {config_data.get("max_duration", 4.0)}
9MAX_LEN = int(SAMPLE_RATE * MAX_DURATION)
10EMOTIONS = {emotions!r} # ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise'] will be replaced by actual list
11
12# Load ONNX model
13session = ort.InferenceSession("ser_wavlm.onnx", providers=['CPUExecutionProvider'])
14feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base-plus")
15
16def load_and_preprocess(path: str) -> np.ndarray:
17 y, sr = librosa.load(path, sr=SAMPLE_RATE, mono=True, duration=MAX_DURATION + 1.0)
18 if len(y) < 100:
19 return np.zeros(MAX_LEN, dtype=np.float32)
20 y_trim, _ = librosa.effects.trim(y, top_db=25)
21 if len(y_trim) > 100:
22 y = y_trim
23 if len(y) >= MAX_LEN:
24 start = (len(y) - MAX_LEN) // 2
25 y = y[start: start + MAX_LEN]
26 else:
27 pad = MAX_LEN - len(y)
28 y = np.pad(y, (pad // 2, pad - pad // 2), mode="reflect" if len(y) > 1 else "constant")
29 rms = np.sqrt(np.mean(y ** 2)) + 1e-9
30 y = (y / rms) * 0.1
31 return y.astype(np.float32)
32
33def predict_onnx(audio_path: str):
34 waveform = load_and_preprocess(audio_path)
35 inputs = feature_extractor(
36 waveform,
37 sampling_rate=SAMPLE_RATE,
38 return_tensors="np", # ONNX Runtime expects numpy arrays
39 padding="max_length",
40 max_length=MAX_LEN,
41 truncation=True,
42 )
43 onnx_inputs = {"input_values": inputs["input_values"].astype(np.float32)}
44 onnx_outputs = session.run(None, onnx_inputs)
45 logits = onnx_outputs[0]
46 probs = np.exp(logits) / np.sum(np.exp(logits), axis=1, keepdims=True)
47 predicted_id = np.argmax(probs, axis=1)[0]
48 return EMOTIONS[predicted_id], probs[0, predicted_id]
49
50# Example Usage:
51# emotion, confidence = predict_onnx("path/to/your/audio.wav")
52# print(f"Predicted emotion: {emotion} with confidence {confidence:.2f}")
53