Create handler.py
Browse files- handler.py +55 -0
handler.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import torch
|
| 4 |
+
import torchaudio
|
| 5 |
+
from typing import Any, Dict
|
| 6 |
+
from transformers import AutoConfig, AutoProcessor
|
| 7 |
+
from modeling_upstream_finetune import UpstreamFinetune
|
| 8 |
+
|
| 9 |
+
class EndpointHandler():
|
| 10 |
+
def __init__(self, model_dir: str, **kwargs: Any) -> None:
|
| 11 |
+
# Load config and model with trust_remote_code
|
| 12 |
+
device = 'cuda'
|
| 13 |
+
self.emotions = ['neutral','happy','sad','angry','surprise','contempt']
|
| 14 |
+
|
| 15 |
+
self.model = UpstreamFinetune.from_pretrained(
|
| 16 |
+
model_dir,
|
| 17 |
+
device=device,
|
| 18 |
+
)
|
| 19 |
+
self.model.eval()
|
| 20 |
+
|
| 21 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 22 |
+
# Expect raw audio bytes or a base64 string in `data["inputs"]`
|
| 23 |
+
audio = data["inputs"]
|
| 24 |
+
sampling_rate = data.get("sampling_rate", 16000)
|
| 25 |
+
|
| 26 |
+
# Decode MP3/WAV bytes → waveform tensor
|
| 27 |
+
waveform, sr = torchaudio.load(io.BytesIO(audio))
|
| 28 |
+
if sr != sampling_rate:
|
| 29 |
+
waveform = torchaudio.functional.resample(waveform, sr, sampling_rate)
|
| 30 |
+
|
| 31 |
+
# Forward pass
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
cat_logits, reg_outputs = self.model(
|
| 34 |
+
waveform,
|
| 35 |
+
sampling_rate
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Convert logits to probabilities using softmax
|
| 39 |
+
emotion_probs = torch.nn.functional.softmax(cat_logits, dim=1)
|
| 40 |
+
|
| 41 |
+
# Create emotion predictions
|
| 42 |
+
emotion_predictions = []
|
| 43 |
+
for i, emotion in enumerate(self.emotions):
|
| 44 |
+
emotion_predictions.append({
|
| 45 |
+
"label": emotion,
|
| 46 |
+
"score": float(emotion_probs[0, i]) # Convert tensor to float
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
# Add arousal and valence predictions
|
| 50 |
+
result = emotion_predictions + [
|
| 51 |
+
{"label": "arousal", "score": float(reg_outputs[0, 0])},
|
| 52 |
+
{"label": "valence", "score": float(reg_outputs[0, 1])}
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
return result
|