Spaces:
No application file
No application file
Create emotion_engine.py
Browse files- emotion_engine.py +51 -0
emotion_engine.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
|
| 4 |
+
print("Loading models...")
|
| 5 |
+
|
| 6 |
+
model_a = pipeline(
|
| 7 |
+
"audio-classification",
|
| 8 |
+
model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
model_b = pipeline(
|
| 12 |
+
"audio-classification",
|
| 13 |
+
model="superb/wav2vec2-base-superb-er"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
print("Models ready")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def fuse_results(results_a, results_b):
|
| 20 |
+
|
| 21 |
+
combined = {}
|
| 22 |
+
|
| 23 |
+
for item in results_a:
|
| 24 |
+
combined[item["label"]] = item["score"]
|
| 25 |
+
|
| 26 |
+
for item in results_b:
|
| 27 |
+
|
| 28 |
+
if item["label"] in combined:
|
| 29 |
+
combined[item["label"]] += item["score"]
|
| 30 |
+
else:
|
| 31 |
+
combined[item["label"]] = item["score"]
|
| 32 |
+
|
| 33 |
+
final = []
|
| 34 |
+
|
| 35 |
+
for emotion, score in combined.items():
|
| 36 |
+
final.append({
|
| 37 |
+
"emotion": emotion,
|
| 38 |
+
"confidence": float(score / 2)
|
| 39 |
+
})
|
| 40 |
+
|
| 41 |
+
final = sorted(final, key=lambda x: x["confidence"], reverse=True)
|
| 42 |
+
|
| 43 |
+
return final
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def predict_emotion(audio):
|
| 47 |
+
|
| 48 |
+
res_a = model_a(audio)
|
| 49 |
+
res_b = model_b(audio)
|
| 50 |
+
|
| 51 |
+
return fuse_results(res_a, res_b)
|