Spaces:
Runtime error
Runtime error
Update app.py
Browse files12343 unmodified lines891011121314151617181920212223242526272 unmodified lines30313233343536373816 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929394952 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311327 unmodified lines1401411421431441451462 unmodified lines14915015115215315415514 unmodified lines1701711721731741751762 unmodified lines1791801811821831841851861871881891901911 unmodified line1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242257 unmodified lines2332342352362372382392402412422432442 unmodified lines2472482492502512522532542552562572582592602612622632642652662672682692702712722732742752 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103115 unmodified lines31731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438511 unmodified lines3973983994004014024034044054063 unmodified lines4104114124134144154164174184194204213 unmodified lines4254264274284294304314324334344354365 unmodified lines4424434444454464474484494504514524534541 unmodified line4564574584594604614624634644654664674684694704714724734744754764774784794804814824831 unmodified line4854864874884894904915 unmodified lines4974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355363 unmodified lines54054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158210 unmodified lines5935945955965975985996006016026032 unmodified lines6066076086096106116129 unmodified lines62262362462562662762862963063163263363437 unmodified lines67267367467567667767815 unmodified lines6946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487491 unmodified line7517527537547557567577587597607611 unmodified line7637647657667677687694 unmodified lines7747757767777787797801 unmodified line7827837847857867877885 unmodified lines7947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568571 unmodified line8598608618628638648655 unmodified lines871872873874875876877878879# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# IMPORTS3 unmodified linesimport cv2import timeimport waveimport structimport shutilimport tempfileimport numpy as npimport gradio as grimport mediapipe as mpfrom enum import Enumfrom pathlib import Pathfrom typing import Optional, Tuplefrom dataclasses import dataclass, fieldfrom collections import dequefrom scipy.spatial import distance as dist# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 1. DATA CLASSES2 unmodified lines@dataclassclass FaceLandmarks:"""Holds extracted facial landmark groups from MediaPipe Face Mesh."""left_eye: np.ndarray # 6 key landmarks for left eyeright_eye: np.ndarray # 6 key landmarks for right eyemouth: np.ndarray # 8 key landmarks for mouthface_bbox: Optional[Tuple[int, int, int, int]] = Noneall_landmarks: Optional[np.ndarray] = Noneconfidence: float = 0.016 unmodified linesis_yawning: bool = Falseeyes_closed_duration: float = 0.0yawn_count: int = 0perclos: float = 0.0 # Percentage of Eye CLOSurealert_triggered: bool = Falsestatus_message: str = "Driver Alert"# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 2. FACE LANDMARK DETECTOR (MediaPipe Face Mesh)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass FaceLandmarkDetector:"""Detects 468 facial landmarks with MediaPipe Face Mesh and extractsthe specific indices needed for EAR and MAR calculations.Why MediaPipe over dlib?β No external .dat model file requiredβ 468 landmarks (vs dlib's 68) β finer detailβ Better cross-platform / HF Spaces compatibilityβ Built-in iris refinement for eye tracking"""# 6 eye-contour indices per eye (needed for EAR formula)LEFT_EYE_INDICES = [362, 385, 387, 263, 373, 380]RIGHT_EYE_INDICES = [33, 160, 158, 133, 153, 144]# 8 mouth indices (vertical + horizontal for MAR formula)MOUTH_INDICES = [13, # top lip centre (upper)14, # bottom lip centre (lower)82, # upper inner left312, # upper inner right87, # lower inner left317, # lower inner right78, # left corner308, # right corner]def __init__(2 unmodified linesmin_detection_confidence: float = 0.5,min_tracking_confidence: float = 0.5,):self.mp_face_mesh = mp.solutions.face_meshself.face_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,)# ββ detection ββββββββββββββββββββββββββββββββββββββββββββββββββββββ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.shaperesults = self.face_mesh.process(rgb)if not results.multi_face_landmarks:return Noneface = results.multi_face_landmarks[0]# Convert normalised landmarks β pixel coordinatesall_pts = np.array([(lm.x * w, lm.y * h) for lm in face.landmark])left_eye = np.array([all_pts[i] for i in self.LEFT_EYE_INDICES])right_eye = np.array([all_pts[i] for i in self.RIGHT_EYE_INDICES])mouth = np.array([all_pts[i] for i in self.MOUTH_INDICES])xs, ys = all_pts[:, 0], all_pts[:, 1]bbox = (int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max()))7 unmodified linesconfidence=1.0,)# ββ visualisation helpers ββββββββββββββββββββββββββββββββββββββββββdef draw_landmarks(self,frame: np.ndarray,2 unmodified linesdraw_mouth: bool = True,draw_bbox: bool = False,) -> np.ndarray:"""Draw eye contours, mouth points, and optional bounding box."""out = frame.copy()if draw_eyes:14 unmodified linesreturn outdef cleanup(self):self.face_mesh.close()# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ2 unmodified linesclass EARCalculator:"""Eye Aspect Ratio β based on SoukupovΓ‘ & Δech (2016).EAR = (βp2βp6β + βp3βp5β) / (2 Β· βp1βp4β)Open eye β 0.25β0.35Closed eye β 0.0A 5-frame moving average smooths landmark jitter."""DEFAULT_THRESHOLD = 0.221 unmodified linedef __init__(self, threshold: float = DEFAULT_THRESHOLD):self.threshold = thresholdself._left_hist = deque(maxlen=self.SMOOTHING_WINDOW)self._right_hist = deque(maxlen=self.SMOOTHING_WINDOW)@staticmethoddef _ear(eye: np.ndarray) -> float:"""Compute EAR for one eye (6 landmarks)."""v1 = dist.euclidean(eye[1], eye[5]) # vertical 1v2 = dist.euclidean(eye[2], eye[4]) # vertical 2h = dist.euclidean(eye[0], eye[3]) # horizontalreturn (v1 + v2) / (2.0 * h) if h != 0 else 0.0def calculate(self, left_eye: np.ndarray, right_eye: np.ndarray) -> Tuple[float, float, float, bool]:"""Returns (smoothed_left, smoothed_right, avg_ear, eyes_closed)."""l_ear = self._ear(left_eye)r_ear = self._ear(right_eye)self._left_hist.append(l_ear)self._right_hist.append(r_ear)sl = float(np.mean(self._left_hist))sr = float(np.mean(self._right_hist))avg = (sl + sr) / 2.0return sl, sr, avg, avg < self.thresholddef reset(self):7 unmodified linesclass MARCalculator:"""Mouth Aspect Ratio β analogous to EAR but for yawning detection.MAR = Ξ£(vertical distances) / (2 Β· horizontal distance)Sustained high MAR over MIN_YAWN_FRAMES frames β yawn confirmed.(Short spikes from talking are filtered out.)"""DEFAULT_THRESHOLD = 0.752 unmodified linesdef __init__(self, threshold: float = DEFAULT_THRESHOLD):self.threshold = thresholdself._hist = deque(maxlen=self.SMOOTHING_WINDOW)self._yawn_count = 0@staticmethoddef _mar(mouth: np.ndarray) -> float:"""Compute MAR from 8 mouth landmarks."""v1 = dist.euclidean(mouth[0], mouth[1]) # top β bottom centrev2 = dist.euclidean(mouth[2], mouth[4]) # inner left upper β lowerv3 = dist.euclidean(mouth[3], mouth[5]) # inner right upper β lowerh = dist.euclidean(mouth[6], mouth[7]) # left β right cornerreturn (v1 + v2 + v3) / (2.0 * h) if h != 0 else 0.0def calculate(self, mouth: np.ndarray) -> Tuple[float, bool]:"""Returns (smoothed_mar, is_yawning)."""raw = self._mar(mouth)self._hist.append(raw)smoothed = float(np.mean(self._hist))if smoothed > self.threshold:self._yawn_count += 1else:self._yawn_count = 0return smoothed, self._yawn_count >= self.MIN_YAWN_FRAMESdef reset(self):2 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 5. DROWSINESS STATE TRACKER (state machine)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass DrowsinessTracker:"""Finite-state machine: ALERT βββΊ ATTENTION βββΊ DROWSYTransition criteriaβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββDROWSY : eyes closed β₯ 2 s OR PERCLOS β₯ 15 % OR β₯ 3 yawns / 5 minATTENTION: eyes closed β₯ 1 s OR active yawn OR PERCLOS β₯ 10.5 %ALERT : otherwiseA 10 s cooldown prevents alarm fatigue."""ATTN_CLOSE_DUR = 1.0 # seconds β ATTENTIONDROWSY_CLOSE_DUR = 2.0 # seconds β DROWSYPERCLOS_THRESH = 0.15 # 15 % (NHTSA standard)PERCLOS_WINDOW = 150 # frames (~5 s at 30 fps)YAWN_THRESH = 3 # yawns in windowYAWN_WINDOW_S = 300.0 # 5-minute windowALERT_COOLDOWN_S = 10.0 # seconds between alertsdef __init__(self):self._state: DriverState = DriverState.ALERTself._close_start: Optional[float] = Noneself._close_hist: deque = deque(maxlen=self.PERCLOS_WINDOW)self._yawn_times: list = []self._last_alert: Optional[float] = Noneself._yawn_active = False5 unmodified linesis_yawning: bool,mar_value: float,) -> DrowsinessMetrics:"""Feed one frame of observations; returns full metrics snapshot."""now = time.time()# ββ eye closure duration ββββββββββββββββββββββββββββββββββββββif eyes_closed:if self._close_start is None:self._close_start = nowclose_dur = now - self._close_startelse:self._close_start = Noneclose_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 = Trueelif not is_yawning:self._yawn_active = Falseself._yawn_times = [t for t in self._yawn_times if now - t <= self.YAWN_WINDOW_S]yawn_count = len(self._yawn_times)# ββ state decision ββββββββββββββββββββββββββββββββββββββββββββif (close_dur >= self.DROWSY_CLOSE_DURor perclos >= self.PERCLOS_THRESHor yawn_count >= self.YAWN_THRESH):self._state = DriverState.DROWSYmsg = "β οΈ DROWSY! Wake Up!"elif (close_dur >= self.ATTN_CLOSE_DURor is_yawningor perclos >= self.PERCLOS_THRESH * 0.7):self._state = DriverState.ATTENTIONmsg = "β‘ Attention Needed"else:self._state = DriverState.ALERTmsg = "β Driver Alert"# ββ alert trigger with cooldown βββββββββββββββββββββββββββββββalert = Falseif self._state == DriverState.DROWSY:if self._last_alert is None or now - self._last_alert >= self.ALERT_COOLDOWN_S:alert = Trueself._last_alert = nowreturn DrowsinessMetrics(state=self._state,ear_value=ear_value,mar_value=mar_value,eyes_closed=eyes_closed,is_yawning=is_yawning,eyes_closed_duration=close_dur,yawn_count=yawn_count,perclos=perclos,alert_triggered=alert,status_message=msg,)def reset(self):11 unmodified linesclass AlertManager:"""Generates and caches two WAV files at startup:1. alarm.wav β synthetic beep pattern2. voice_alert.wav β gTTS "Wake up!" (fallback: descending tones)Then combines them into combined_alert.wav."""ASSETS = Path("assets")3 unmodified linesself.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()# ββ WAV writer ββββββββββββββββββββββββββββββββββββββββββββββββββββ@staticmethoddef _write_wav(path: Path, samples: np.ndarray, sr: int = 44100):data = np.int16(np.clip(samples, -1, 1) * 32767)3 unmodified lineswf.setframerate(sr)wf.writeframes(data.tobytes())# ββ alarm beeps βββββββββββββββββββββββββββββββββββββββββββββββββββdef _make_alarm(self):if self.alarm_path.exists():returnsr = 44100samples = []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)5 unmodified lines+ 0.3 * np.sin(2 * np.pi * freq * 2 * t)+ 0.1 * np.sin(2 * np.pi * freq * 3 * t)) * envtone /= np.max(np.abs(tone)) + 1e-9tone *= 0.9samples.extend(tone)samples.extend([0.0] * int(sr * 0.08))self._write_wav(self.alarm_path, np.array(samples))# ββ voice alert βββββββββββββββββββββββββββββββββββββββββββββββββββdef _make_voice(self):if self.voice_path.exists():return1 unmodified linefrom gtts import gTTSfrom pydub import AudioSegmenttts = gTTS("Wake up! You are getting sleepy. Please take a break.", lang="en")tmp = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False)tts.save(tmp.name)audio = AudioSegment.from_mp3(tmp.name)audio = audio.set_frame_rate(44100).set_channels(1).set_sample_width(2)audio.export(str(self.voice_path), format="wav")os.unlink(tmp.name)except Exception as exc:print(f"gTTS unavailable ({exc}); generating fallback tones")samples = []sr = 44100for 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)samples.extend([0.0] * int(sr * 0.1))self._write_wav(self.voice_path, np.array(samples))# ββ combined ββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _make_combined(self):if self.combined_path.exists():return1 unmodified linefrom pydub import AudioSegmenta = 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))5 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 7. OVERLAY RENDERER (draws status HUD on frame)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef draw_overlay(frame: np.ndarray, m: DrowsinessMetrics, fps: float,ear_thresh: float) -> np.ndarray:"""Draws a heads-up display on the video frame:β’ Colour-coded status bar (green / orange / red)β’ Numeric metrics panel (EAR, MAR, PERCLOS β¦)β’ Gauge bars for EAR and MARβ’ Flashing warning banner when DROWSY"""h, w = frame.shape[:2]font = cv2.FONT_HERSHEY_SIMPLEXoverlay = frame.copy()# ββ status bar ββββββββββββββββββββββββββββββββββββββββββββββββββββif m.state == DriverState.DROWSY:bar_col = (0, 0, 255) if int(time.time() * 4) % 2 else (0, 0, 200)label = "DROWSY - WAKE UP!"elif m.state == DriverState.ATTENTION:bar_col = (0, 165, 255)label = "ATTENTION NEEDED"else:bar_col = (0, 180, 0)label = "DRIVER ALERT"cv2.rectangle(overlay, (0, 0), (w, 60), bar_col, -1)cv2.addWeighted(overlay, 0.85, frame, 0.15, 0, frame)tw = cv2.getTextSize(label, font, 1.2, 3)[0][0]cv2.putText(frame, label, ((w - tw) // 2, 42), font, 1.2,(255, 255, 255), 3, cv2.LINE_AA)# ββ metrics panel (left) ββββββββββββββββββββββββββββββββββββββββββ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 ''}",3 unmodified linesf"FPS: {fps:.1f}",]px, py, lh = 15, 75, 30panel = frame.copy()cv2.rectangle(panel, (5, py - 15), (335, py + len(lines) * lh + 5),(0, 0, 0), -1)cv2.addWeighted(panel, 0.5, frame, 0.5, 0, frame)for i, line in enumerate(lines):y = py + i * lh + lhcol = ((0, 0, 255) if "CLOSED" in lineelse (0, 165, 255) if "YAWNING" in lineelse (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 (right) ββββββββββββββββββββββββββββββββββββββββββββgx = w - 200gy = 80bw, bh = 150, 15# EAR gaugeear_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)ear_c = (0, 0, 255) if m.eyes_closed else (0, 255, 0)cv2.rectangle(frame, (gx, gy + 5),(gx + int(bw * ear_fill), gy + 5 + bh), ear_c, -1)tx = gx + int(bw * (ear_thresh / 0.4))cv2.line(frame, (tx, gy + 3), (tx, gy + 7 + bh), (255, 255, 0), 2)# MAR gaugemy2 = gy + bh + 25mar_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)mar_c = (0, 165, 255) if m.is_yawning else (0, 255, 0)cv2.rectangle(frame, (gx, my2 + 5),(gx + int(bw * mar_fill), my2 + 5 + bh), mar_c, -1)# ββ flashing bottom warning βββββββββββββββββββββββββββββββββββββββif m.state == DriverState.DROWSY and int(time.time() * 3) % 2 == 0:10 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 8. HTML STATUS PANEL (for the Gradio sidebar)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef status_html(m: Optional[DrowsinessMetrics] = None) -> str:"""Return a rich HTML card summarising the current metrics."""if m is None:return ('<div style="padding:20px;text-align:center;background:#2d2d2d;'2 unmodified lines'<p>Start your webcam to begin monitoring</p></div>')# state β colourscfg = {DriverState.DROWSY: ("π΄", "DROWSY", "#ff4444", "#4a0000", "#ff0000"),DriverState.ATTENTION: ("π‘", "ATTENTION", "#ffaa00", "#4a3500", "#ffaa00"),9 unmodified linespcl_fg = "#ff4444" if m.perclos > 0.15 else "#44ff44"yc_fg = "#ffaa00" if m.yawn_count >= 2 else "#44ff44"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>'if m.state == DriverState.DROWSY else "")return f"""<div style="padding:20px;background:#1a1a2e;border-radius:15px;37 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 9. GLOBAL COMPONENT INIT# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββprint("π Initialising Drowsiness Detection System β¦")15 unmodified linesdef process_frame(frame: np.ndarray):"""Full per-frame pipeline:frame βββΊ landmarks βββΊ EAR / MAR βββΊ state tracker βββΊ overlayReturns (annotated_bgr, metrics, 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)frame = draw_overlay(frame, dm, fps, ear_calculator.threshold)return frame, dm, False# draw landmarksframe = face_detector.draw_landmarks(frame, landmarks)# EAR_, _, avg_ear, eyes_closed = ear_calculator.calculate(landmarks.left_eye, landmarks.right_eye)# MARmar_val, is_yawning = mar_calculator.calculate(landmarks.mouth)# state machinemetrics = 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 CALLBACK# ββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββββββββββββββββββdef detect_drowsiness(image: np.ndarray, ear_thresh: float, mar_thresh: float):"""Called by Gradio for every webcam frame.Returns (annotated_rgb, html_status, alert_audio | None)."""if image is None:return np.zeros((480, 640, 3), dtype=np.uint8), status_html(None), None# apply user-adjustable thresholdsear_calculator.threshold = ear_threshmar_calculator.threshold = mar_thresh1 unmodified lineannotated, 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 for a fresh session."""ear_calculator.reset()mar_calculator.reset()drowsiness_tracker.reset()1 unmodified line# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 12. BUILD & LAUNCH GRADIO UI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef build_app() -> gr.Blocks:4 unmodified linescss=".gradio-container{max-width:1400px!important;margin:auto!important}",) as demo:# ββ header ββββββββββββββββββββββββββββββββββββββββββββββββββββgr.Markdown("""# π AI-Powered Driver Drowsiness Detection System**Real-time monitoring using Computer Vision & AI to prevent1 unmodified line| Technology | Purpose ||---|---|| MediaPipe Face Mesh | 468-point facial landmark detection || Eye Aspect Ratio (EAR) | Eye closure detection || Mouth Aspect Ratio (MAR) | Yawning detection || PERCLOS | Long-term eye-closure percentage |5 unmodified lines""")with gr.Row():# ββ left: video βββββββββββββββββββββββββββββββββββββββββββ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,)# ββ right: status + controls ββββββββββββββββββββββββββββββ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")# ββ collapsible info ββββββββββββββββββββββββββββββββββββββββββwith gr.Accordion("βΉοΈ How It Works", open=False):gr.Markdown("""### Detection Pipeline1. **Face Detection** β MediaPipe Face Mesh β 468 landmarks.2. **EAR** β `(βp2-p6β+βp3-p5β) / (2Β·βp1-p4β)`.Open β 0.25-0.35; closed < 0.22.3. **MAR** β ratio of vertical to horizontal mouth distances;sustained high MAR = yawn.4. **PERCLOS** β rolling % of frames with eyes closed(NHTSA: >15 % = drowsy).5. **State Machine** β ALERT β ATTENTION β DROWSY,with a 10 s cooldown between audio alerts.### Metrics Reference| Metric | Normal | Alert ||--------|--------|-------|1 unmodified line| 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 ββββββββββββββββββββββββββββββββββββββββββββββ5 unmodified linestime_limit=None,)reset_btn.click(fn=reset_system,inputs=[],outputs=[output_img, status_box, alert_audio],)return demo12345678910111213141516171819202122233 unmodified lines2728293031323334353637383940414243444546472 unmodified lines50515253545556575816 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131142 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571587 unmodified lines1661671681691701712 unmodified lines17417517617717817918014 unmodified lines1951961971981992002012022 unmodified lines2052062072082092102112122132142152161 unmodified line2182192202212222232242252262272282292302312322332342352362372382392402412422437 unmodified lines2512522532542552562572582 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183195 unmodified lines32532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938011 unmodified lines3923933943953963973983994004013 unmodified lines4054064074084094104114124134143 unmodified lines4184194204214224234244254264274285 unmodified lines4344354364374384394404414424434444454461 unmodified line4484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774781 unmodified line4804814824834844854864874885 unmodified lines4944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285293 unmodified lines53353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856910 unmodified lines5805815825835845855865875885895902 unmodified lines5935945955965975989 unmodified lines60860961061161261361461561661761861962062137 unmodified lines65966066166266366466515 unmodified lines6816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367371 unmodified line7397407417427437447457467477487497507517527531 unmodified line7557567577587597607614 unmodified lines7667677687697707711 unmodified line7737747757767777787795 unmodified lines7857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338341 unmodified line8368378388398408418425 unmodified lines848849850851852853854"""=============================================================================AI-Powered Driver Drowsiness Detection System β Single File Edition=============================================================================Real-time drowsiness detection via webcam using:β’ MediaPipe Face Mesh (478 facial landmarks with iris refinement)β’ Eye Aspect Ratio (EAR) β eye closure detectionβ’ Mouth Aspect Ratio (MAR) β yawning detectionβ’ PERCLOS tracking β percentage of eye closure over timeβ’ Audio + voice alerts when drowsiness is confirmedCompatible with:β’ mediapipe >= 0.10.30β’ Hugging Face Spaces (Debian Trixie)Author : Senior AI EngineerLicense: MIT============================================================================="""# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# IMPORTS3 unmodified linesimport cv2import timeimport waveimport shutilimport tempfileimport numpy as npimport gradio as grfrom enum import Enumfrom pathlib import Pathfrom typing import Optional, Tuplefrom dataclasses import dataclassfrom collections import dequefrom scipy.spatial import distance as dist# MediaPipe import β compatible with 0.10.30+import mediapipe as mp# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 1. DATA CLASSES2 unmodified lines@dataclassclass FaceLandmarks:"""Holds extracted facial landmark groups from MediaPipe Face Mesh."""left_eye: np.ndarrayright_eye: np.ndarraymouth: np.ndarrayface_bbox: Optional[Tuple[int, int, int, int]] = Noneall_landmarks: Optional[np.ndarray] = Noneconfidence: float = 0.016 unmodified linesis_yawning: bool = Falseeyes_closed_duration: float = 0.0yawn_count: int = 0perclos: float = 0.0alert_triggered: bool = Falsestatus_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 irisrefinement) and extracts specific indices for EAR and MAR.Compatibility note:mediapipe >= 0.10.30 uses the same FaceMesh API but shipsdifferent internal model versions. The landmark indices remainidentical across versions."""# 6 eye-contour indices per eye for EARLEFT_EYE_INDICES = [362, 385, 387, 263, 373, 380]RIGHT_EYE_INDICES = [33, 160, 158, 133, 153, 144]# 8 mouth indices for MARMOUTH_INDICES = [13, # top lip centre upper14, # bottom lip centre lower82, # upper inner left312, # upper inner right87, # lower inner left317, # lower inner right78, # left corner308, # right corner]def __init__(2 unmodified linesmin_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_meshself._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 performancergb.flags.writeable = Falseresults = self._mesh.process(rgb)rgb.flags.writeable = Trueif not results.multi_face_landmarks:return Noneface = results.multi_face_landmarks[0]# Normalised β pixel coordinatesall_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()))7 unmodified linesconfidence=1.0,)def draw_landmarks(self,frame: np.ndarray,2 unmodified linesdraw_mouth: bool = True,draw_bbox: bool = False,) -> np.ndarray:"""Visualise eye contours, mouth points, optional bounding box."""out = frame.copy()if draw_eyes:14 unmodified linesreturn outdef cleanup(self):"""Release MediaPipe resources."""self._mesh.close()# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ2 unmodified linesclass 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.221 unmodified linedef __init__(self, threshold: float = DEFAULT_THRESHOLD):self.threshold = thresholdself._left_hist: deque = deque(maxlen=self.SMOOTHING_WINDOW)self._right_hist: deque = deque(maxlen=self.SMOOTHING_WINDOW)@staticmethoddef _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.0def 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.0return sl, sr, avg, avg < self.thresholddef reset(self):7 unmodified linesclass MARCalculator:"""Mouth Aspect Ratio for yawning detection.Sustained high MAR over MIN_YAWN_FRAMES β yawn confirmed."""DEFAULT_THRESHOLD = 0.752 unmodified linesdef __init__(self, threshold: float = DEFAULT_THRESHOLD):self.threshold = thresholdself._hist: deque = deque(maxlen=self.SMOOTHING_WINDOW)self._yawn_count = 0@staticmethoddef _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.0def 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 += 1else:self._yawn_count = 0return smoothed, self._yawn_count >= self.MIN_YAWN_FRAMESdef reset(self):2 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 5. DROWSINESS STATE TRACKER# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass DrowsinessTracker:"""State machine: ALERT β ATTENTION β DROWSYDROWSY : eyes closed β₯ 2 s OR PERCLOS β₯ 15 % OR β₯ 3 yawns / 5 minATTENTION: eyes closed β₯ 1 s OR active yawn OR PERCLOS β₯ 10.5 %ALERT : otherwise10 s cooldown between alerts."""ATTN_CLOSE = 1.0DROWSY_CLOSE = 2.0PERCLOS_THR = 0.15PERCLOS_WIN = 150YAWN_THR = 3YAWN_WIN_S = 300.0COOLDOWN_S = 10.0def __init__(self):self._state = DriverState.ALERTself._close_start: Optional[float] = Noneself._close_hist: deque = deque(maxlen=self.PERCLOS_WIN)self._yawn_times: list = []self._last_alert: Optional[float] = Noneself._yawn_active = False5 unmodified linesis_yawning: bool,mar_value: float,) -> DrowsinessMetrics:now = time.time()# eye closure durationif eyes_closed:if self._close_start is None:self._close_start = nowdur = now - self._close_startelse:self._close_start = Nonedur = 0.0# PERCLOSself._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 frequencyif is_yawning and not self._yawn_active:self._yawn_times.append(now)self._yawn_active = Trueelif not is_yawning:self._yawn_active = Falseself._yawn_times = [t for t in self._yawn_times if now - t <= self.YAWN_WIN_S]yc = len(self._yawn_times)# state decisionif dur >= self.DROWSY_CLOSE or perclos >= self.PERCLOS_THR or yc >= self.YAWN_THR:self._state = DriverState.DROWSYmsg = "β οΈ DROWSY! Wake Up!"elif dur >= self.ATTN_CLOSE or is_yawning or perclos >= self.PERCLOS_THR * 0.7:self._state = DriverState.ATTENTIONmsg = "β‘ Attention Needed"else:self._state = DriverState.ALERTmsg = "β Driver Alert"# alert cooldownalert = Falseif self._state == DriverState.DROWSY:if self._last_alert is None or now - self._last_alert >= self.COOLDOWN_S:alert = Trueself._last_alert = nowreturn 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):11 unmodified linesclass AlertManager:"""Generates and caches alert WAV files at startup:alarm.wav β synthetic beep patternvoice_alert.wav β gTTS speech or fallback tonescombined_alert.wav β alarm + pause + voice"""ASSETS = Path("assets")3 unmodified linesself.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()@staticmethoddef _write_wav(path: Path, samples: np.ndarray, sr: int = 44100):data = np.int16(np.clip(samples, -1, 1) * 32767)3 unmodified lineswf.setframerate(sr)wf.writeframes(data.tobytes())def _make_alarm(self):if self.alarm_path.exists():returnsr = 44100samples: 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)5 unmodified lines+ 0.3 * np.sin(2 * np.pi * freq * 2 * t)+ 0.1 * np.sin(2 * np.pi * freq * 3 * t)) * envmx = np.max(np.abs(tone))if mx > 0:tone = tone / mx * 0.9samples.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():return1 unmodified linefrom gtts import gTTSfrom pydub import AudioSegmenttts = 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.nameaudio = 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 = 44100samples: 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():return1 unmodified linefrom pydub import AudioSegmenta = 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))5 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 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_SIMPLEXoverlay = 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 ''}",3 unmodified linesf"FPS: {fps:.1f}",]px, py, lh = 15, 75, 30bg = 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) * lhcol = ((0, 0, 255) if "CLOSED" in lineelse (0, 165, 255) if "YAWNING" in lineelse (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, 15ear_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 + 25mar_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:10 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 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;'2 unmodified lines'<p>Start your webcam to begin monitoring</p></div>')cfg = {DriverState.DROWSY: ("π΄", "DROWSY", "#ff4444", "#4a0000", "#ff0000"),DriverState.ATTENTION: ("π‘", "ATTENTION", "#ffaa00", "#4a3500", "#ffaa00"),9 unmodified linespcl_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;37 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 9. GLOBAL INIT# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββprint("π Initialising Drowsiness Detection System β¦")15 unmodified linesdef process_frame(frame: np.ndarray):"""Full per-frame pipeline:BGR frame β landmarks β EAR/MAR β state tracker β overlayReturns (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, Falseframe = 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_threshmar_calculator.threshold = mar_thresh1 unmodified lineannotated, 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()1 unmodified line# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 12. BUILD GRADIO UI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef build_app() -> gr.Blocks:4 unmodified linescss=".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 prevent1 unmodified line| 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 |5 unmodified lines""")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 Pipeline1. **Face Detection** β MediaPipe Face Mesh β 478 landmarks2. **EAR** β `(βp2-p6β+βp3-p5β) / (2Β·βp1-p4β)` ;open β 0.25β0.35 ; closed < 0.223. **MAR** β vertical / horizontal mouth ratio ;sustained high MAR = yawn4. **PERCLOS** β rolling % of frames with closed eyes ;NHTSA threshold: 15 %5. **State Machine** β ALERT β ATTENTION β DROWSYwith 10 s alert cooldown| Metric | Normal | Alert ||--------|--------|-------|1 unmodified line| 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 ββββββββββββββββββββββββββββββββββββββββββββββ5 unmodified linestime_limit=None,)reset_btn.click(fn=reset_system, inputs=[], outputs=[output_img, status_box, alert_audio],)return demo
app.py+239-264