Views
No views yet
Wav2Vec2ForSequenceClassification).angry, calm, disgust, fear, happy, neutral, sad, surprise.facebook/wav2vec2-base-960h fine‑tuned for emotion classification.confit/cremad-parquet).1import torch, numpy as np, soundfile as sf, librosa
2from transformers import Wav2Vec2ForSequenceClassification, AutoFeatureExtractor
3
4model_dir = "path/to/best_model" # local directory or Hub repo id
5model = Wav2Vec2ForSequenceClassification.from_pretrained(model_dir)
6fe = AutoFeatureExtractor.from_pretrained(model_dir)
7model.eval()
8
9def load_audio(path, sr=fe.sampling_rate):
10 y, s = sf.read(path, always_2d=False)
11 if isinstance(y, np.ndarray):
12 if y.ndim > 1:
13 y = np.mean(y, axis=1)
14 if s != sr:
15 y = librosa.resample(y.astype(np.float32), orig_sr=s, target_sr=sr)
16 y = y.astype(np.float32)
17 else:
18 y = np.array(y, dtype=np.float32)
19 if y.size < sr // 10:
20 y = np.pad(y, (0, max(0, sr - y.size)))
21 return y
22
23audio = load_audio("sample.wav")
24inputs = fe(audio, sampling_rate=fe.sampling_rate, return_tensors="pt")
25with torch.no_grad():
26 logits = model(**inputs).logits
27probs = torch.softmax(logits, dim=-1)[0].cpu().numpy()
28labels = [model.config.id2label[str(i)] if isinstance(list(model.config.id2label.keys())[0], str) else model.config.id2label[i] for i in range(len(probs))]
29pairs = sorted(zip(labels, probs), key=lambda x: x[1], reverse=True)
30print(pairs[:3])POST /predict and returns sorted label probabilities and the dominant emotion.wav, mp3, m4a, etc.). Internally converted to 16 kHz mono.1{
2 "results": [{ "label": "happy", "score": 0.81 }, ...],
3 "dominant": { "label": "happy", "score": 0.81 }
4}