# ═══════════════════════════════════════════════════════════════════════════ # IMPORTS # ═══════════════════════════════════════════════════════════════════════════ import os import cv2 import time import wave import shutil import tempfile import numpy as np import gradio as gr from enum import Enum from pathlib import Path from typing import Optional, Tuple from dataclasses import dataclass from collections import deque from scipy.spatial import distance as dist # MediaPipe import — compatible with 0.10.30+ import mediapipe as mp # ═══════════════════════════════════════════════════════════════════════════ # 1. DATA CLASSES # ═══════════════════════════════════════════════════════════════════════════ @dataclass class FaceLandmarks: """Holds extracted facial landmark groups from MediaPipe Face Mesh.""" left_eye: np.ndarray right_eye: np.ndarray mouth: np.ndarray face_bbox: Optional[Tuple[int, int, int, int]] = None all_landmarks: Optional[np.ndarray] = None confidence: float = 0.0 class DriverState(Enum): """Three-level driver alertness classification.""" ALERT = "alert" ATTENTION = "attention" DROWSY = "drowsy" @dataclass class DrowsinessMetrics: """Snapshot of all drowsiness-related metrics for the current frame.""" 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 alert_triggered: bool = False status_message: str = "Driver Alert" # ═══════════════════════════════════════════════════════════════════════════ # 2. FACE LANDMARK DETECTOR (MediaPipe Face Mesh — v0.10.30+ compatible) # ═══════════════════════════════════════════════════════════════════════════ class FaceLandmarkDetector: """ Detects 478 facial landmarks with MediaPipe Face Mesh (with iris refinement) and extracts specific indices for EAR and MAR. Compatibility note: mediapipe >= 0.10.30 uses the same FaceMesh API but ships different internal model versions. The landmark indices remain identical across versions. """ # 6 eye-contour indices per eye for EAR LEFT_EYE_INDICES = [362, 385, 387, 263, 373, 380] RIGHT_EYE_INDICES = [33, 160, 158, 133, 153, 144] # 8 mouth indices for MAR MOUTH_INDICES = [ 13, # top lip centre upper 14, # bottom lip centre lower 82, # upper inner left 312, # upper inner right 87, # lower inner left 317, # lower inner right 78, # left corner 308, # right corner ] def __init__( self, max_num_faces: int = 1, min_detection_confidence: float = 0.5, min_tracking_confidence: float = 0.5, ): """Initialise MediaPipe FaceMesh with iris refinement enabled.""" self._mp_face_mesh = mp.solutions.face_mesh self._mesh = self._mp_face_mesh.FaceMesh( max_num_faces=max_num_faces, refine_landmarks=True, min_detection_confidence=min_detection_confidence, min_tracking_confidence=min_tracking_confidence, ) def detect(self, frame: np.ndarray) -> Optional[FaceLandmarks]: """ Run face-mesh inference on a BGR frame. Returns FaceLandmarks if a face is found, else None. """ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w = frame.shape[:2] # Mark image as non-writeable for performance rgb.flags.writeable = False results = self._mesh.process(rgb) rgb.flags.writeable = True if not results.multi_face_landmarks: return None face = results.multi_face_landmarks[0] # Normalised → pixel coordinates all_pts = np.array( [(lm.x * w, lm.y * h) for lm in face.landmark], dtype=np.float64, ) left_eye = all_pts[self.LEFT_EYE_INDICES] right_eye = all_pts[self.RIGHT_EYE_INDICES] mouth = all_pts[self.MOUTH_INDICES] xs, ys = all_pts[:, 0], all_pts[:, 1] bbox = (int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())) return FaceLandmarks( left_eye=left_eye, right_eye=right_eye, mouth=mouth, face_bbox=bbox, all_landmarks=all_pts, confidence=1.0, ) def draw_landmarks( self, frame: np.ndarray, landmarks: FaceLandmarks, draw_eyes: bool = True, draw_mouth: bool = True, draw_bbox: bool = False, ) -> np.ndarray: """Visualise eye contours, mouth points, optional bounding box.""" out = frame.copy() if draw_eyes: for eye_pts in (landmarks.left_eye, landmarks.right_eye): pts = eye_pts.astype(np.int32) cv2.polylines(out, [pts], True, (0, 255, 0), 2) for pt in pts: cv2.circle(out, tuple(pt), 2, (0, 255, 0), -1) if draw_mouth: for pt in landmarks.mouth.astype(np.int32): cv2.circle(out, tuple(pt), 3, (255, 0, 0), -1) if draw_bbox and landmarks.face_bbox: x1, y1, x2, y2 = landmarks.face_bbox cv2.rectangle(out, (x1, y1), (x2, y2), (255, 255, 0), 2) return out def cleanup(self): """Release MediaPipe resources.""" self._mesh.close() # ═══════════════════════════════════════════════════════════════════════════ # 3. EAR CALCULATOR # ═══════════════════════════════════════════════════════════════════════════ class EARCalculator: """ Eye Aspect Ratio — Soukupová & Čech (2016). EAR = (‖p2−p6‖ + ‖p3−p5‖) / (2 · ‖p1−p4‖) Open eye ≈ 0.25–0.35 ; closed → 0. 5-frame moving average smooths landmark jitter. """ DEFAULT_THRESHOLD = 0.22 SMOOTHING_WINDOW = 5 def __init__(self, threshold: float = DEFAULT_THRESHOLD): self.threshold = threshold self._left_hist: deque = deque(maxlen=self.SMOOTHING_WINDOW) self._right_hist: deque = deque(maxlen=self.SMOOTHING_WINDOW) @staticmethod def _ear(eye: np.ndarray) -> float: v1 = dist.euclidean(eye[1], eye[5]) v2 = dist.euclidean(eye[2], eye[4]) h = dist.euclidean(eye[0], eye[3]) return (v1 + v2) / (2.0 * h) if h > 0 else 0.0 def calculate( self, left_eye: np.ndarray, right_eye: np.ndarray, ) -> Tuple[float, float, float, bool]: l = self._ear(left_eye) r = self._ear(right_eye) self._left_hist.append(l) self._right_hist.append(r) sl = float(np.mean(self._left_hist)) sr = float(np.mean(self._right_hist)) avg = (sl + sr) / 2.0 return sl, sr, avg, avg < self.threshold def reset(self): self._left_hist.clear() self._right_hist.clear() # ═══════════════════════════════════════════════════════════════════════════ # 4. MAR CALCULATOR # ═══════════════════════════════════════════════════════════════════════════ class MARCalculator: """ Mouth Aspect Ratio for yawning detection. Sustained high MAR over MIN_YAWN_FRAMES ⇒ yawn confirmed. """ DEFAULT_THRESHOLD = 0.75 SMOOTHING_WINDOW = 5 MIN_YAWN_FRAMES = 8 def __init__(self, threshold: float = DEFAULT_THRESHOLD): self.threshold = threshold self._hist: deque = deque(maxlen=self.SMOOTHING_WINDOW) self._yawn_count = 0 @staticmethod def _mar(mouth: np.ndarray) -> float: v1 = dist.euclidean(mouth[0], mouth[1]) v2 = dist.euclidean(mouth[2], mouth[4]) v3 = dist.euclidean(mouth[3], mouth[5]) h = dist.euclidean(mouth[6], mouth[7]) return (v1 + v2 + v3) / (2.0 * h) if h > 0 else 0.0 def calculate(self, mouth: np.ndarray) -> Tuple[float, bool]: raw = self._mar(mouth) self._hist.append(raw) smoothed = float(np.mean(self._hist)) if smoothed > self.threshold: self._yawn_count += 1 else: self._yawn_count = 0 return smoothed, self._yawn_count >= self.MIN_YAWN_FRAMES def reset(self): self._hist.clear() self._yawn_count = 0 # ═══════════════════════════════════════════════════════════════════════════ # 5. DROWSINESS STATE TRACKER # ═══════════════════════════════════════════════════════════════════════════ class DrowsinessTracker: """ State machine: ALERT → ATTENTION → DROWSY DROWSY : eyes closed ≥ 2 s OR PERCLOS ≥ 15 % OR ≥ 3 yawns / 5 min ATTENTION: eyes closed ≥ 1 s OR active yawn OR PERCLOS ≥ 10.5 % ALERT : otherwise 10 s cooldown between alerts. """ ATTN_CLOSE = 1.0 DROWSY_CLOSE = 2.0 PERCLOS_THR = 0.15 PERCLOS_WIN = 150 YAWN_THR = 3 YAWN_WIN_S = 300.0 COOLDOWN_S = 10.0 def __init__(self): self._state = DriverState.ALERT self._close_start: Optional[float] = None self._close_hist: deque = deque(maxlen=self.PERCLOS_WIN) self._yawn_times: list = [] self._last_alert: Optional[float] = None self._yawn_active = False def update( self, eyes_closed: bool, ear_value: float, is_yawning: bool, mar_value: float, ) -> DrowsinessMetrics: now = time.time() # eye closure duration if eyes_closed: if self._close_start is None: self._close_start = now dur = now - self._close_start else: self._close_start = None dur = 0.0 # PERCLOS self._close_hist.append(1 if eyes_closed else 0) perclos = ( sum(self._close_hist) / len(self._close_hist) if self._close_hist else 0.0 ) # yawn frequency if is_yawning and not self._yawn_active: self._yawn_times.append(now) self._yawn_active = True elif not is_yawning: self._yawn_active = False self._yawn_times = [t for t in self._yawn_times if now - t <= self.YAWN_WIN_S] yc = len(self._yawn_times) # state decision if dur >= self.DROWSY_CLOSE or perclos >= self.PERCLOS_THR or yc >= self.YAWN_THR: self._state = DriverState.DROWSY msg = "⚠️ DROWSY! Wake Up!" elif dur >= self.ATTN_CLOSE or is_yawning or perclos >= self.PERCLOS_THR * 0.7: self._state = DriverState.ATTENTION msg = "⚡ Attention Needed" else: self._state = DriverState.ALERT msg = "✅ Driver Alert" # alert cooldown alert = False if self._state == DriverState.DROWSY: if self._last_alert is None or now - self._last_alert >= self.COOLDOWN_S: alert = True self._last_alert = now return DrowsinessMetrics( state=self._state, ear_value=ear_value, mar_value=mar_value, eyes_closed=eyes_closed, is_yawning=is_yawning, eyes_closed_duration=dur, yawn_count=yc, perclos=perclos, alert_triggered=alert, status_message=msg, ) def reset(self): self._state = DriverState.ALERT self._close_start = None self._close_hist.clear() self._yawn_times.clear() self._last_alert = None self._yawn_active = False # ═══════════════════════════════════════════════════════════════════════════ # 6. ALERT MANAGER (audio generation) # ═══════════════════════════════════════════════════════════════════════════ class AlertManager: """ Generates and caches alert WAV files at startup: alarm.wav — synthetic beep pattern voice_alert.wav — gTTS speech or fallback tones combined_alert.wav — alarm + pause + voice """ ASSETS = Path("assets") def __init__(self): self.ASSETS.mkdir(exist_ok=True) self.alarm_path = self.ASSETS / "alarm.wav" self.voice_path = self.ASSETS / "voice_alert.wav" self.combined_path = self.ASSETS / "combined_alert.wav" self._make_alarm() self._make_voice() self._make_combined() @staticmethod def _write_wav(path: Path, samples: np.ndarray, sr: int = 44100): data = np.int16(np.clip(samples, -1, 1) * 32767) with wave.open(str(path), "w") as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sr) wf.writeframes(data.tobytes()) def _make_alarm(self): if self.alarm_path.exists(): return sr = 44100 samples: list = [] for freq in [880, 1100, 880, 1100, 880, 1100]: t = np.linspace(0, 0.15, int(sr * 0.15), endpoint=False) env = np.ones_like(t) fade = int(0.01 * sr) env[:fade] = np.linspace(0, 1, fade) env[-fade:] = np.linspace(1, 0, fade) tone = ( 0.8 * np.sin(2 * np.pi * freq * t) + 0.3 * np.sin(2 * np.pi * freq * 2 * t) + 0.1 * np.sin(2 * np.pi * freq * 3 * t) ) * env mx = np.max(np.abs(tone)) if mx > 0: tone = tone / mx * 0.9 samples.extend(tone.tolist()) samples.extend([0.0] * int(sr * 0.08)) self._write_wav(self.alarm_path, np.array(samples, dtype=np.float64)) def _make_voice(self): if self.voice_path.exists(): return try: from gtts import gTTS from pydub import AudioSegment tts = gTTS( "Wake up! You are getting sleepy. Please take a break.", lang="en", ) with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp: tts.save(tmp.name) tmp_path = tmp.name audio = AudioSegment.from_mp3(tmp_path) audio = audio.set_frame_rate(44100).set_channels(1).set_sample_width(2) audio.export(str(self.voice_path), format="wav") os.unlink(tmp_path) except Exception as exc: print(f"gTTS unavailable ({exc}); generating fallback tones") sr = 44100 samples: list = [] for freq in [660, 550, 440]: t = np.linspace(0, 0.4, int(sr * 0.4), endpoint=False) env = np.ones_like(t) fade = int(0.02 * sr) env[:fade] = np.linspace(0, 1, fade) env[-fade:] = np.linspace(1, 0, fade) samples.extend((0.7 * np.sin(2 * np.pi * freq * t) * env).tolist()) samples.extend([0.0] * int(sr * 0.1)) self._write_wav(self.voice_path, np.array(samples, dtype=np.float64)) def _make_combined(self): if self.combined_path.exists(): return try: from pydub import AudioSegment a = AudioSegment.from_wav(str(self.alarm_path)) v = AudioSegment.from_wav(str(self.voice_path)) (a + AudioSegment.silent(300) + v).export( str(self.combined_path), format="wav", ) except Exception: shutil.copy2(str(self.alarm_path), str(self.combined_path)) def get_alert_path(self) -> str: for p in (self.combined_path, self.alarm_path): if p.exists(): return str(p) return "" # ═══════════════════════════════════════════════════════════════════════════ # 7. OVERLAY RENDERER # ═══════════════════════════════════════════════════════════════════════════ def draw_overlay( frame: np.ndarray, m: DrowsinessMetrics, fps: float, ear_thresh: float, ) -> np.ndarray: """Draw colour-coded HUD: status bar, metrics panel, gauges, warnings.""" h, w = frame.shape[:2] font = cv2.FONT_HERSHEY_SIMPLEX overlay = frame.copy() # ── status bar ──────────────────────────────────────────────────── if m.state == DriverState.DROWSY: bar = (0, 0, 255) if int(time.time() * 4) % 2 else (0, 0, 200) lbl = "DROWSY - WAKE UP!" elif m.state == DriverState.ATTENTION: bar, lbl = (0, 165, 255), "ATTENTION NEEDED" else: bar, lbl = (0, 180, 0), "DRIVER ALERT" cv2.rectangle(overlay, (0, 0), (w, 60), bar, -1) cv2.addWeighted(overlay, 0.85, frame, 0.15, 0, frame) tw = cv2.getTextSize(lbl, font, 1.2, 3)[0][0] cv2.putText(frame, lbl, ((w - tw) // 2, 42), font, 1.2, (255, 255, 255), 3, cv2.LINE_AA) # ── metrics panel ───────────────────────────────────────────────── lines = [ f"EAR: {m.ear_value:.3f} {'[CLOSED]' if m.eyes_closed else '[OPEN]'}", f"MAR: {m.mar_value:.3f} {'[YAWNING]' if m.is_yawning else ''}", f"Eye Closed: {m.eyes_closed_duration:.1f}s", f"Yawn Count: {m.yawn_count}", f"PERCLOS: {m.perclos:.1%}", f"FPS: {fps:.1f}", ] px, py, lh = 15, 75, 30 bg = frame.copy() cv2.rectangle(bg, (5, py - 15), (335, py + len(lines) * lh + 5), (0, 0, 0), -1) cv2.addWeighted(bg, 0.5, frame, 0.5, 0, frame) for i, line in enumerate(lines): y = py + (i + 1) * lh col = ((0, 0, 255) if "CLOSED" in line else (0, 165, 255) if "YAWNING" in line else (255, 255, 255)) cv2.putText(frame, line, (px + 1, y + 1), font, 0.6, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(frame, line, (px, y), font, 0.6, col, 1, cv2.LINE_AA) # ── gauge bars ──────────────────────────────────────────────────── gx, gy, bw, bh = w - 200, 80, 150, 15 ear_fill = min(m.ear_value / 0.4, 1.0) cv2.putText(frame, "EAR", (gx, gy), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA) cv2.rectangle(frame, (gx, gy + 5), (gx + bw, gy + 5 + bh), (100, 100, 100), -1) cv2.rectangle(frame, (gx, gy + 5), (gx + int(bw * ear_fill), gy + 5 + bh), (0, 0, 255) if m.eyes_closed else (0, 255, 0), -1) tx = gx + int(bw * min(ear_thresh / 0.4, 1.0)) cv2.line(frame, (tx, gy + 3), (tx, gy + 7 + bh), (255, 255, 0), 2) my2 = gy + bh + 25 mar_fill = min(m.mar_value / 1.5, 1.0) cv2.putText(frame, "MAR", (gx, my2), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA) cv2.rectangle(frame, (gx, my2 + 5), (gx + bw, my2 + 5 + bh), (100, 100, 100), -1) cv2.rectangle(frame, (gx, my2 + 5), (gx + int(bw * mar_fill), my2 + 5 + bh), (0, 165, 255) if m.is_yawning else (0, 255, 0), -1) # ── flashing bottom warning ─────────────────────────────────────── if m.state == DriverState.DROWSY and int(time.time() * 3) % 2 == 0: txt = "!!! DROWSINESS DETECTED - PULL OVER SAFELY !!!" tsz = cv2.getTextSize(txt, font, 0.8, 2)[0] wy = h - 30 wo = frame.copy() cv2.rectangle(wo, (0, wy - 35), (w, h), (0, 0, 255), -1) cv2.addWeighted(wo, 0.7, frame, 0.3, 0, frame) cv2.putText(frame, txt, ((w - tsz[0]) // 2, wy), font, 0.8, (255, 255, 255), 2, cv2.LINE_AA) return frame # ═══════════════════════════════════════════════════════════════════════════ # 8. HTML STATUS PANEL # ═══════════════════════════════════════════════════════════════════════════ def status_html(m: Optional[DrowsinessMetrics] = None) -> str: """Rich HTML card summarising current metrics for Gradio sidebar.""" if m is None: return ( '
Start your webcam to begin monitoring
{m.status_message}