Spaces:
Runtime error

File size: 6,742 Bytes
ec56723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Drowsiness State Tracking Module

Implements a state machine that tracks driver alertness over time.
Uses multiple signals (eye closure duration, yawning frequency)
to make robust drowsiness determinations.

State Machine:
    ALERT -> ATTENTION -> DROWSY
    
    ALERT: Normal driving state
    ATTENTION: Initial signs of drowsiness (short eye closures or yawns)
    DROWSY: Confirmed drowsiness (prolonged eye closure or repeated yawning)
"""

import time
from enum import Enum
from dataclasses import dataclass, field
from typing import Optional
from collections import deque


class DriverState(Enum):
    """Driver alertness states."""
    ALERT = "alert"
    ATTENTION = "attention"  # Warning state
    DROWSY = "drowsy"


@dataclass
class DrowsinessMetrics:
    """Real-time drowsiness metrics for display."""
    state: DriverState = DriverState.ALERT
    ear_value: float = 0.0
    mar_value: float = 0.0
    eyes_closed: bool = False
    is_yawning: bool = False
    eyes_closed_duration: float = 0.0
    yawn_count: int = 0
    perclos: float = 0.0  # Percentage of eye closure over time
    alert_triggered: bool = False
    status_message: str = "Driver Alert"


class DrowsinessTracker:
    """
    Tracks driver drowsiness state using multiple indicators.
    
    Detection criteria:
    1. PERCLOS (Percentage of Eye Closure):
       - Measures the percentage of time eyes are closed over a window
       - >15% indicates drowsiness (NHTSA standard)
    
    2. Prolonged Eye Closure:
       - Eyes closed for more than 2 seconds = drowsy
       - Eyes closed for more than 1 second = attention needed
    
    3. Yawning Frequency:
       - Multiple yawns in a short period indicates fatigue
       - 3+ yawns in 5 minutes = drowsy
    """

    # Eye closure duration thresholds (in seconds)
    ATTENTION_EYE_CLOSE_DURATION = 1.0  # 1 second -> attention
    DROWSY_EYE_CLOSE_DURATION = 2.0     # 2 seconds -> drowsy

    # PERCLOS threshold (NHTSA standard)
    PERCLOS_THRESHOLD = 0.15  # 15% of time

    # PERCLOS calculation window (in number of frames)
    PERCLOS_WINDOW = 150  # ~5 seconds at 30fps

    # Yawning thresholds
    YAWN_COUNT_THRESHOLD = 3       # Number of yawns to trigger drowsiness
    YAWN_WINDOW_SECONDS = 300.0    # Time window for counting yawns (5 minutes)

    # Cooldown period after alert (to avoid constant triggering)
    ALERT_COOLDOWN_SECONDS = 10.0

    def __init__(self):
        """Initialize the drowsiness tracker."""
        self._state = DriverState.ALERT
        self._eyes_closed_start: Optional[float] = None
        self._eye_closure_history = deque(maxlen=self.PERCLOS_WINDOW)
        self._yawn_timestamps: list = []
        self._last_alert_time: Optional[float] = None
        self._yawn_active = False  # Track current yawn state to count transitions

    def update(
        self,
        eyes_closed: bool,
        ear_value: float,
        is_yawning: bool,
        mar_value: float,
    ) -> DrowsinessMetrics:
        """
        Update drowsiness state based on current frame detections.

        Args:
            eyes_closed: Whether eyes are currently detected as closed
            ear_value: Current EAR value
            is_yawning: Whether yawning is currently detected
            mar_value: Current MAR value

        Returns:
            DrowsinessMetrics with current state and all metrics
        """
        current_time = time.time()

        # === Track Eye Closure Duration ===
        if eyes_closed:
            if self._eyes_closed_start is None:
                self._eyes_closed_start = current_time
            eyes_closed_duration = current_time - self._eyes_closed_start
        else:
            self._eyes_closed_start = None
            eyes_closed_duration = 0.0

        # === Track PERCLOS ===
        # Record whether eyes are closed in this frame
        self._eye_closure_history.append(1 if eyes_closed else 0)

        # Calculate PERCLOS (percentage of eye closure)
        if len(self._eye_closure_history) > 0:
            perclos = sum(self._eye_closure_history) / len(self._eye_closure_history)
        else:
            perclos = 0.0

        # === Track Yawning Frequency ===
        # Detect yawn start (transition from not yawning to yawning)
        if is_yawning and not self._yawn_active:
            self._yawn_timestamps.append(current_time)
            self._yawn_active = True
        elif not is_yawning:
            self._yawn_active = False

        # Remove old yawn timestamps outside the window
        self._yawn_timestamps = [
            t for t in self._yawn_timestamps
            if current_time - t <= self.YAWN_WINDOW_SECONDS
        ]
        yawn_count = len(self._yawn_timestamps)

        # === Determine State ===
        previous_state = self._state
        alert_triggered = False

        # Check for DROWSY conditions (most severe first)
        if (
            eyes_closed_duration >= self.DROWSY_EYE_CLOSE_DURATION
            or perclos >= self.PERCLOS_THRESHOLD
            or yawn_count >= self.YAWN_COUNT_THRESHOLD
        ):
            self._state = DriverState.DROWSY
            status_message = "⚠️ DROWSY! Wake Up!"

        # Check for ATTENTION conditions
        elif (
            eyes_closed_duration >= self.ATTENTION_EYE_CLOSE_DURATION
            or is_yawning
            or perclos >= self.PERCLOS_THRESHOLD * 0.7  # 70% of threshold
        ):
            self._state = DriverState.ATTENTION
            status_message = "⚡ Attention Needed"

        else:
            self._state = DriverState.ALERT
            status_message = "✅ Driver Alert"

        # === Trigger Alert ===
        if self._state == DriverState.DROWSY:
            # Check cooldown to avoid constant alerts
            if (
                self._last_alert_time is None
                or current_time - self._last_alert_time >= self.ALERT_COOLDOWN_SECONDS
            ):
                alert_triggered = True
                self._last_alert_time = current_time

        return DrowsinessMetrics(
            state=self._state,
            ear_value=ear_value,
            mar_value=mar_value,
            eyes_closed=eyes_closed,
            is_yawning=is_yawning,
            eyes_closed_duration=eyes_closed_duration,
            yawn_count=yawn_count,
            perclos=perclos,
            alert_triggered=alert_triggered,
            status_message=status_message,
        )

    def reset(self):
        """Reset all tracking state."""
        self._state = DriverState.ALERT
        self._eyes_closed_start = None
        self._eye_closure_history.clear()
        self._yawn_timestamps.clear()
        self._last_alert_time = None
        self._yawn_active = False