File size: 2,359 Bytes
05fbb64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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