Spaces:
Runtime error
Runtime error
Create drowsiness_tracker.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""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 timefrom enum import Enumfrom dataclasses import dataclass, fieldfrom typing import Optionalfrom collections import deque
class DriverState(Enum): """Driver alertness states.""" ALERT = "alert" ATTENTION = "attention" # Warning state DROWSY = "drowsy"
@dataclassclass 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 = Falseutils/drowsiness_tracker.pyAdded+200