Spaces:
Runtime error
Runtime error
Download app.py from knightsam/ConcreteAI: direct link, hf CLI and curl.
- Browser
- Download file 37.1 kB
-
https://huggingface.co/spaces/knightsam/ConcreteAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/knightsam/ConcreteAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/knightsam/ConcreteAI/resolve/main/app.py
37.1 kB
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 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 | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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" | |
| 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) | |
| 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 | |
| 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() | |
| 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 ( | |
| '<div style="padding:20px;text-align:center;background:#2d2d2d;' | |
| 'border-radius:10px;color:#fff;font-family:Arial">' | |
| '<h2>π Driver Drowsiness Detection</h2>' | |
| '<p>Start your webcam to begin monitoring</p></div>' | |
| ) | |
| cfg = { | |
| DriverState.DROWSY: ("π΄", "DROWSY", "#ff4444", "#4a0000", "#ff0000"), | |
| DriverState.ATTENTION: ("π‘", "ATTENTION", "#ffaa00", "#4a3500", "#ffaa00"), | |
| DriverState.ALERT: ("π’", "ALERT", "#44ff44", "#003a00", "#00ff00"), | |
| } | |
| icon, lbl, fg, bg, brd = cfg[m.state] | |
| eye_fg = "#ff4444" if m.eyes_closed else "#44ff44" | |
| eye_tx = "ποΈ Eyes Closed" if m.eyes_closed else "ποΈ Eyes Open" | |
| mar_fg = "#ffaa00" if m.is_yawning else "#44ff44" | |
| mar_tx = "π₯± Yawning" if m.is_yawning else "π Normal" | |
| dur_fg = "#ff4444" if m.eyes_closed_duration > 1.0 else "#44ff44" | |
| pcl_fg = "#ff4444" if m.perclos > 0.15 else "#44ff44" | |
| yc_fg = "#ffaa00" if m.yawn_count >= 2 else "#44ff44" | |
| warn = "" | |
| if m.state == DriverState.DROWSY: | |
| warn = ( | |
| '<div style="background:#f00;color:#fff;padding:15px;' | |
| 'border-radius:8px;text-align:center;animation:pulse 1s infinite;' | |
| 'font-size:1.2em;font-weight:bold;margin-top:12px">' | |
| 'β οΈ DROWSINESS DETECTED! PLEASE PULL OVER SAFELY! β οΈ</div>' | |
| ) | |
| return f""" | |
| <div style="padding:20px;background:#1a1a2e;border-radius:15px; | |
| border:3px solid {brd};font-family:'Segoe UI',Arial,sans-serif; | |
| color:#fff;box-shadow:0 0 20px {brd}40"> | |
| <div style="text-align:center;padding:15px;background:{bg}; | |
| border-radius:10px;margin-bottom:15px"> | |
| <h1 style="margin:0;color:{fg};font-size:2em">{icon} {lbl}</h1> | |
| <p style="margin:5px 0 0;color:#ccc;font-size:1.1em">{m.status_message}</p> | |
| </div> | |
| <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px; | |
| margin-bottom:15px"> | |
| <div style="background:#16213e;padding:12px;border-radius:8px;text-align:center"> | |
| <div style="color:#888;font-size:.85em">Eye Aspect Ratio</div> | |
| <div style="font-size:1.8em;font-weight:bold;color:{eye_fg}">{m.ear_value:.3f}</div> | |
| <div style="font-size:.8em;color:{eye_fg}">{eye_tx}</div> | |
| </div> | |
| <div style="background:#16213e;padding:12px;border-radius:8px;text-align:center"> | |
| <div style="color:#888;font-size:.85em">Mouth Aspect Ratio</div> | |
| <div style="font-size:1.8em;font-weight:bold;color:{mar_fg}">{m.mar_value:.3f}</div> | |
| <div style="font-size:.8em;color:{mar_fg}">{mar_tx}</div> | |
| </div> | |
| <div style="background:#16213e;padding:12px;border-radius:8px;text-align:center"> | |
| <div style="color:#888;font-size:.85em">Eye Closed Duration</div> | |
| <div style="font-size:1.8em;font-weight:bold;color:{dur_fg}">{m.eyes_closed_duration:.1f}s</div> | |
| </div> | |
| <div style="background:#16213e;padding:12px;border-radius:8px;text-align:center"> | |
| <div style="color:#888;font-size:.85em">PERCLOS</div> | |
| <div style="font-size:1.8em;font-weight:bold;color:{pcl_fg}">{m.perclos:.1%}</div> | |
| </div> | |
| </div> | |
| <div style="background:#16213e;padding:10px;border-radius:8px; | |
| text-align:center;margin-bottom:10px"> | |
| <span style="color:#888">Yawn Count (5 min): </span> | |
| <span style="font-size:1.3em;font-weight:bold;color:{yc_fg}">{m.yawn_count} π₯±</span> | |
| </div> | |
| {warn} | |
| </div> | |
| <style>@keyframes pulse{{0%{{opacity:1}}50%{{opacity:.5}}100%{{opacity:1}}}}</style> | |
| """ | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 9. GLOBAL INIT | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("π Initialising Drowsiness Detection System β¦") | |
| face_detector = FaceLandmarkDetector() | |
| ear_calculator = EARCalculator() | |
| mar_calculator = MARCalculator() | |
| drowsiness_tracker = DrowsinessTracker() | |
| alert_manager = AlertManager() | |
| ALERT_AUDIO_PATH = alert_manager.get_alert_path() | |
| print("β System ready.") | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 10. FRAME PROCESSING PIPELINE | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def process_frame(frame: np.ndarray): | |
| """ | |
| Full per-frame pipeline: | |
| BGR frame β landmarks β EAR/MAR β state tracker β overlay | |
| Returns (annotated_bgr, DrowsinessMetrics, alert_triggered). | |
| """ | |
| t0 = time.time() | |
| landmarks = face_detector.detect(frame) | |
| if landmarks is None: | |
| h, w = frame.shape[:2] | |
| cv2.rectangle(frame, (0, 0), (w, 60), (128, 128, 128), -1) | |
| cv2.putText(frame, "NO FACE DETECTED", (w // 2 - 180, 42), | |
| cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 3, | |
| cv2.LINE_AA) | |
| dm = DrowsinessMetrics( | |
| status_message="No Face Detected β face the camera", | |
| ) | |
| fps = 1.0 / max(time.time() - t0, 1e-6) | |
| return draw_overlay(frame, dm, fps, ear_calculator.threshold), dm, False | |
| frame = face_detector.draw_landmarks(frame, landmarks) | |
| _, _, avg_ear, eyes_closed = ear_calculator.calculate( | |
| landmarks.left_eye, landmarks.right_eye, | |
| ) | |
| mar_val, is_yawning = mar_calculator.calculate(landmarks.mouth) | |
| metrics = drowsiness_tracker.update( | |
| eyes_closed, avg_ear, is_yawning, mar_val, | |
| ) | |
| fps = 1.0 / max(time.time() - t0, 1e-6) | |
| frame = draw_overlay(frame, metrics, fps, ear_calculator.threshold) | |
| return frame, metrics, metrics.alert_triggered | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 11. GRADIO CALLBACKS | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def detect_drowsiness( | |
| image: np.ndarray, | |
| ear_thresh: float, | |
| mar_thresh: float, | |
| ): | |
| """Called by Gradio for every webcam frame.""" | |
| if image is None: | |
| return ( | |
| np.zeros((480, 640, 3), dtype=np.uint8), | |
| status_html(None), | |
| None, | |
| ) | |
| ear_calculator.threshold = ear_thresh | |
| mar_calculator.threshold = mar_thresh | |
| bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
| annotated, metrics, alert = process_frame(bgr) | |
| rgb_out = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB) | |
| return ( | |
| rgb_out, | |
| status_html(metrics), | |
| ALERT_AUDIO_PATH if alert else None, | |
| ) | |
| def reset_system(): | |
| """Reset all stateful components.""" | |
| ear_calculator.reset() | |
| mar_calculator.reset() | |
| drowsiness_tracker.reset() | |
| return None, status_html(None), None | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 12. BUILD GRADIO UI | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def build_app() -> gr.Blocks: | |
| with gr.Blocks( | |
| title="π AI Driver Drowsiness Detection", | |
| theme=gr.themes.Soft(primary_hue="blue", secondary_hue="green"), | |
| css=".gradio-container{max-width:1400px!important;margin:auto!important}", | |
| ) as demo: | |
| gr.Markdown(""" | |
| # π AI-Powered Driver Drowsiness Detection System | |
| **Real-time monitoring using Computer Vision & AI to prevent | |
| drowsy-driving accidents.** | |
| | Technology | Purpose | | |
| |---|---| | |
| | MediaPipe Face Mesh | 478-point facial landmark detection | | |
| | Eye Aspect Ratio (EAR) | Eye closure detection | | |
| | Mouth Aspect Ratio (MAR) | Yawning detection | | |
| | PERCLOS | Long-term eye-closure percentage | | |
| | gTTS + synthetic tones | Audio & voice alerts | | |
| > β οΈ **Allow camera access** when prompted. | |
| > Face the camera directly for best results. | |
| --- | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| webcam = gr.Image( | |
| sources=["webcam"], streaming=True, type="numpy", | |
| label="π· Live Camera Feed", mirror_webcam=True, | |
| height=480 | |
| ) | |
| output_img = gr.Image( | |
| type="numpy", label="π Detection Output", height=480 | |
| ) | |
| with gr.Column(scale=2): | |
| status_box = gr.HTML(value=status_html(None)) | |
| alert_audio = gr.Audio( | |
| label="π Alert Sound", autoplay=True, visible=True, | |
| elem_id="alert-audio" | |
| ) | |
| gr.Markdown("### βοΈ Detection Settings") | |
| ear_slider = gr.Slider( | |
| 0.10, 0.35, value=0.22, step=0.01, | |
| label="EAR Threshold (lower β more sensitive)", | |
| info="Eyes classified as closed below this value", | |
| ) | |
| mar_slider = gr.Slider( | |
| 0.40, 1.20, value=0.75, step=0.05, | |
| label="MAR Threshold (lower β more sensitive)", | |
| info="Yawning detected above this value", | |
| ) | |
| reset_btn = gr.Button( | |
| "π Reset Detection", variant="secondary", size="lg", | |
| ) | |
| with gr.Accordion("βΉοΈ How It Works", open=False): | |
| gr.Markdown(""" | |
| ### Detection Pipeline | |
| 1. **Face Detection** β MediaPipe Face Mesh β 478 landmarks | |
| 2. **EAR** β `(βp2-p6β+βp3-p5β) / (2Β·βp1-p4β)` ; | |
| open β 0.25β0.35 ; closed < 0.22 | |
| 3. **MAR** β vertical / horizontal mouth ratio ; | |
| sustained high MAR = yawn | |
| 4. **PERCLOS** β rolling % of frames with closed eyes ; | |
| NHTSA threshold: 15 % | |
| 5. **State Machine** β ALERT β ATTENTION β DROWSY | |
| with 10 s alert cooldown | |
| | Metric | Normal | Alert | | |
| |--------|--------|-------| | |
| | EAR | 0.25 β 0.35 | < 0.22 | | |
| | MAR | 0.0 β 0.4 | > 0.75 | | |
| | PERCLOS | < 10 % | > 15 % | | |
| | Eye closed | < 0.5 s | > 2.0 s | | |
| | Yawns / 5 min | 0β1 | β₯ 3 | | |
| """) | |
| # ββ event wiring ββββββββββββββββββββββββββββββββββββββββββββββ | |
| webcam.stream( | |
| fn=detect_drowsiness, | |
| inputs=[webcam, ear_slider, mar_slider], | |
| outputs=[output_img, status_box, alert_audio], | |
| api_name=False | |
| ) | |
| reset_btn.click( | |
| fn=reset_system, inputs=[], outputs=[output_img, status_box, alert_audio],api_name=False | |
| ) | |
| return demo | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 13. ENTRY POINT | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 13. OPENCV LIVE STREAM ENTRY POINT | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_opencv_stream(): | |
| """Runs the drowsiness detection in a native OpenCV window.""" | |
| # 1. Open the default webcam | |
| cap = cv2.VideoCapture(0) | |
| if not cap.isOpened(): | |
| print("Error: Could not access the webcam.") | |
| return | |
| print("π₯ Starting OpenCV live stream... Press 'q' to quit.") | |
| while True: | |
| # 2. Read the live frame | |
| ret, frame = cap.read() | |
| if not ret: | |
| print("Failed to grab frame. Exiting...") | |
| break | |
| # Optional: Mirror the frame so it acts like a standard webcam | |
| frame = cv2.flip(frame, 1) | |
| # 3. Pass the frame through your existing detection pipeline | |
| # process_frame handles the face mesh, EAR/MAR math, and drawing the HUD | |
| annotated_frame, metrics, alert_triggered = process_frame(frame) | |
| # 4. Display the single, annotated frame natively in OpenCV | |
| cv2.imshow("π AI Driver Drowsiness Detection", annotated_frame) | |
| # 5. Handle Audio Alerts (Print to console for now) | |
| if alert_triggered: | |
| print(f"\aβ οΈ ALERT: {metrics.status_message}") # \a triggers a system beep | |
| # 6. Listen for the 'q' key to quit the loop | |
| if cv2.waitKey(1) & 0xFF == ord('q'): | |
| break | |
| # 7. Clean up resources | |
| cap.release() | |
| cv2.destroyAllWindows() | |
| face_detector.cleanup() | |
| if __name__ == "__main__": | |
| run_opencv_stream() | |