emotion-recognition-api / model /emotion_state.py
Digambar29's picture
Don't really know the changes
05fbb64
import time
from collections import deque
class EmotionState:
def __init__(
self,
confidence_threshold=0.6,
window_size=5,
decay_seconds=2.0
):
self.confidence_threshold = confidence_threshold
self.window_size = window_size
self.decay_seconds = decay_seconds
self.recent_emotions = deque(maxlen=window_size)
self.current_emotion = None
self.current_confidence = 0.0
self.last_confident_ts = None
def update(self, prediction: dict):
"""
prediction = {
'emotion': str,
'confidence': float
}
"""
now = time.time()
confidence = prediction["confidence"]
emotion = prediction["emotion"]
# Case 1: confident prediction
if confidence >= self.confidence_threshold:
self.recent_emotions.append(emotion)
dominant_emotion = max(
set(self.recent_emotions),
key=self.recent_emotions.count
)
self.current_emotion = dominant_emotion
self.current_confidence = confidence
self.last_confident_ts = now
return self._stable_response()
# Case 2: uncertain prediction, but within decay window
if self.last_confident_ts and (now - self.last_confident_ts <= self.decay_seconds):
return self._uncertain_response(confidence)
# Case 3: decay expired
self._reset_state()
return self._unknown_response()
def _stable_response(self):
return {
"state": "stable",
"emotion": self.current_emotion,
"confidence": self.current_confidence,
"is_confident": True
}
def _uncertain_response(self, confidence):
return {
"state": "uncertain",
"emotion": self.current_emotion,
"confidence": confidence,
"is_confident": False
}
def _unknown_response(self):
return {
"state": "unknown",
"emotion": None,
"confidence": 0.0,
"is_confident": False
}
def _reset_state(self):
self.recent_emotions.clear()
self.current_emotion = None
self.current_confidence = 0.0
self.last_confident_ts = None