Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines3456783 unmodified lines121314151617181920214 unmodified lines26272829303132333417 unmodified lines525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596971 unmodified line991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491 unmodified line1511521531541551561572 unmodified linesimport mediapipe as mpimport numpy as npimport osfrom gtts import gTTS# -----------------------------------------------------------------------------3 unmodified linesEAR_THRESHOLD = 0.22MAR_THRESHOLD = 0.50CONSECUTIVE_FRAMES = 15AUDIO_FILE = "wake_up_alarm.mp3"if not os.path.exists(AUDIO_FILE):tts = gTTS(text="Wake up! You are getting sleepy.", lang='en', slow=False)tts.save(AUDIO_FILE)mp_face_mesh = mp.solutions.face_mesh4 unmodified linesmin_tracking_confidence=0.5)LEFT_EYE = [362, 385, 387, 263, 373, 380]RIGHT_EYE = [33, 160, 158, 133, 153, 144]MOUTH = [61, 291, 13, 14]# -----------------------------------------------------------------------------# 2. Mathematical Functions17 unmodified linesh = euclidean_distance(left, right)return euclidean_distance(top, bottom) / h if h > 0 else 0# -----------------------------------------------------------------------------# 3. Core Processing Loop# -----------------------------------------------------------------------------def process_frame(frame, state):if frame is None:return None, state, gr.skip()# FIX: Make a writable copy of the incoming read-only frameframe = frame.copy()# Expand state to include yawn trackingif not state:state = {'drowsy_frames': 0,'alarm_on': False,'total_yawns': 0,'is_yawning': False}h, w, _ = frame.shapergb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)results = face_mesh.process(rgb_frame)audio_update = gr.skip()if results.multi_face_landmarks:landmarks = results.multi_face_landmarks[0].landmarkleft_ear = calculate_ear(landmarks, LEFT_EYE, w, h)right_ear = calculate_ear(landmarks, RIGHT_EYE, w, h)ear_avg = (left_ear + right_ear) / 2.0mar = calculate_mar(landmarks, w, h)# Check for Drowsiness (Sleeping Detected)if ear_avg < EAR_THRESHOLD:state['drowsy_frames'] += 1if state['drowsy_frames'] >= CONSECUTIVE_FRAMES:if not state['alarm_on']:state['alarm_on'] = Trueaudio_update = AUDIO_FILEelse:state['drowsy_frames'] = 01 unmodified linestate['alarm_on'] = Falseaudio_update = None# Check for Yawningif mar > MAR_THRESHOLD:cv2.putText(frame, "YAWNING DETECTED", (10, h - 40),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 165, 255), 2)# Only count as a new yawn if they weren't already yawning in the last frameif not state['is_yawning']:state['total_yawns'] += 1state['is_yawning'] = Trueelse:state['is_yawning'] = False# -------------------------------------------------------------------------# 5. UI Rendering on Video Frame# -------------------------------------------------------------------------# Draw Yawn Countercv2.putText(frame, f"Total Yawns: {state['total_yawns']}", (10, 40),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)# Draw Sleeping/Alert Statusif state['alarm_on']:cv2.putText(frame, "SLEEPING DETECTED!", (10, 80),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)cv2.rectangle(frame, (0, 0), (w, h), (0, 0, 255), 10)cv2.putText(frame, "WAKE UP!", (max(10, w//2 - 100), h//2),cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 4)else:cv2.putText(frame, "Driver Alert", (10, 80),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)return frame, state, audio_update# -----------------------------------------------------------------------------# 4. Gradio Interface# -----------------------------------------------------------------------------with gr.Blocks(theme=gr.themes.Default()) as demo:gr.Markdown("# π AI Driver Drowsiness Detection System")gr.Markdown("**Instructions:** Allow webcam access. If your eyes remain closed for a prolonged period, an audio alert will play natively through your browser.")with gr.Row():with gr.Column():in_video = gr.Image(sources=["webcam"], streaming=True, label="Live Camera Feed")with gr.Column():out_video = gr.Image(label="Monitoring Status")alarm_audio = gr.Audio(autoplay=True, visible=False)session_state = gr.State()1 unmodified linein_video.stream(fn=process_frame,inputs=[in_video, session_state],outputs=[out_video, session_state, alarm_audio])if __name__ == "__main__":2 unmodified lines34567893 unmodified lines13141516171819202122234 unmodified lines282930313233343536373839404142434445464717 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681 unmodified line1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422431 unmodified line2452462472482492502512 unmodified linesimport mediapipe as mpimport numpy as npimport osimport mathfrom gtts import gTTS# -----------------------------------------------------------------------------3 unmodified linesEAR_THRESHOLD = 0.22MAR_THRESHOLD = 0.50CONSECUTIVE_FRAMES = 15DISTRACTION_FRAMES = 20AUDIO_FILE = "wake_up_alarm.mp3"if not os.path.exists(AUDIO_FILE):tts = gTTS(text="Wake up! Pay attention to the road.", lang='en', slow=False)tts.save(AUDIO_FILE)mp_face_mesh = mp.solutions.face_mesh4 unmodified linesmin_tracking_confidence=0.5)# Landmark IndicesLEFT_EYE = [362, 385, 387, 263, 373, 380]RIGHT_EYE = [33, 160, 158, 133, 153, 144]MOUTH_OUTLINE = [61, 291, 39, 181, 0, 17, 269, 405] # Broader outline for bounding box# 3D Model Points for Head Pose EstimationFACE_3D_MODEL_POINTS = np.array([(0.0, 0.0, 0.0), # Nose tip (1)(0.0, -330.0, -65.0), # Chin (152)(-225.0, 170.0, -135.0), # Left eye left corner (33)(225.0, 170.0, -135.0), # Right eye right corner (263)(-150.0, -150.0, -125.0), # Left Mouth corner (61)(150.0, -150.0, -125.0) # Right mouth corner (291)], dtype=np.float64)# -----------------------------------------------------------------------------# 2. Mathematical Functions17 unmodified linesh = euclidean_distance(left, right)return euclidean_distance(top, bottom) / h if h > 0 else 0def get_head_pose(landmarks, img_w, img_h):# Get 2D image points mapping to the 3D modelimage_points = np.array([(landmarks[1].x * img_w, landmarks[1].y * img_h),(landmarks[152].x * img_w, landmarks[152].y * img_h),(landmarks[33].x * img_w, landmarks[33].y * img_h),(landmarks[263].x * img_w, landmarks[263].y * img_h),(landmarks[61].x * img_w, landmarks[61].y * img_h),(landmarks[291].x * img_w, landmarks[291].y * img_h)], dtype=np.float64)focal_length = img_wcenter = (img_w / 2, img_h / 2)camera_matrix = np.array([[focal_length, 0, center[0]],[0, focal_length, center[1]],[0, 0, 1]], dtype=np.float64)dist_coeffs = np.zeros((4, 1))success, rotation_vector, translation_vector = cv2.solvePnP(FACE_3D_MODEL_POINTS, image_points, camera_matrix, dist_coeffs)rotation_matrix, _ = cv2.Rodrigues(rotation_vector)proj_matrix = np.hstack((rotation_matrix, translation_vector))euler_angles = cv2.decomposeProjectionMatrix(proj_matrix)[6]pitch, yaw, roll = [a[0] for a in euler_angles]return pitch, yaw, rolldef get_bounding_box(landmarks, indices, img_w, img_h):pts = np.array([[int(landmarks[i].x * img_w), int(landmarks[i].y * img_h)] for i in indices])x, y, w, h = cv2.boundingRect(pts)return x, y, w, hdef get_full_face_box(landmarks, img_w, img_h):pts = np.array([[int(lm.x * img_w), int(lm.y * img_h)] for lm in landmarks])x, y, w, h = cv2.boundingRect(pts)return x, y, w, h# -----------------------------------------------------------------------------# 3. Core Processing Loop# -----------------------------------------------------------------------------def process_frame(frame, state):if frame is None:return None, state, gr.skip(), "Waiting for camera..."frame = frame.copy()h, w, _ = frame.shape# Initialize stateif not state:state = {'drowsy_frames': 0,'distracted_frames': 0,'alarm_on': False,'total_yawns': 0,'sleep_alerts': 0,'distraction_alerts': 0,'is_yawning': False}rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)results = face_mesh.process(rgb_frame)audio_update = gr.skip()# Default Dashboard Valuescurrent_status = "π’ ACTIVE & FOCUSED"pitch, yaw = 0.0, 0.0ear_avg, mar = 0.0, 0.0if results.multi_face_landmarks:landmarks = results.multi_face_landmarks[0].landmark# Calculationsleft_ear = calculate_ear(landmarks, LEFT_EYE, w, h)right_ear = calculate_ear(landmarks, RIGHT_EYE, w, h)ear_avg = (left_ear + right_ear) / 2.0mar = calculate_mar(landmarks, w, h)pitch, yaw, roll = get_head_pose(landmarks, w, h)# -------------------------------------------------------------------------# Logic & Bounding Boxes# -------------------------------------------------------------------------face_x, face_y, face_w, face_h = get_full_face_box(landmarks, w, h)# 1. Check Drowsiness (Sleeping)if ear_avg < EAR_THRESHOLD:state['drowsy_frames'] += 1if state['drowsy_frames'] >= CONSECUTIVE_FRAMES:current_status = "π΄ SLEEPING DETECTED"cv2.rectangle(frame, (face_x, face_y), (face_x + face_w, face_y + face_h), (0, 0, 255), 3)cv2.putText(frame, "SLEEPING!", (face_x, face_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)if not state['alarm_on']:state['alarm_on'] = Truestate['sleep_alerts'] += 1audio_update = AUDIO_FILEelse:state['drowsy_frames'] = 01 unmodified linestate['alarm_on'] = Falseaudio_update = None# 2. Check Distraction (Not looking front)# Using thresholds: Yaw > 25 degrees (looking side) or Pitch > 20 / < -20 (looking up/down)if abs(yaw) > 25 or pitch > 20 or pitch < -20:state['distracted_frames'] += 1if state['distracted_frames'] >= DISTRACTION_FRAMES and not state['alarm_on']:current_status = "π‘ DISTRACTED (LOOKING AWAY)"cv2.rectangle(frame, (face_x, face_y), (face_x + face_w, face_y + face_h), (0, 255, 255), 3)cv2.putText(frame, "DISTRACTED!", (face_x, face_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)state['distraction_alerts'] += 1else:state['distracted_frames'] = 0# 3. Check Yawningif mar > MAR_THRESHOLD:if not state['alarm_on'] and state['distracted_frames'] < DISTRACTION_FRAMES:current_status = "π YAWNING DETECTED"mouth_x, mouth_y, mouth_w, mouth_h = get_bounding_box(landmarks, MOUTH_OUTLINE, w, h)cv2.rectangle(frame, (mouth_x, mouth_y), (mouth_x + mouth_w, mouth_y + mouth_h), (0, 165, 255), 2)cv2.putText(frame, "YAWN", (mouth_x, mouth_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 165, 255), 2)if not state['is_yawning']:state['total_yawns'] += 1state['is_yawning'] = Trueelse:state['is_yawning'] = Falseelse:current_status = "βͺ NO FACE DETECTED"# -------------------------------------------------------------------------# Analytics Dashboard Output String# -------------------------------------------------------------------------dashboard_text = f"""### π Live Driver Analytics**Current Status:** {current_status}**Metrics:*** **Eye Aspect Ratio (EAR):** {ear_avg:.2f} *(Threshold: {EAR_THRESHOLD})** **Mouth Aspect Ratio (MAR):** {mar:.2f} *(Threshold: {MAR_THRESHOLD})** **Head Yaw (Left/Right):** {yaw:.1f}Β°* **Head Pitch (Up/Down):** {pitch:.1f}Β°**Session Statistics:*** **Total Sleep Warnings:** {state['sleep_alerts']}* **Total Distraction Warnings:** {state['distraction_alerts']}* **Total Yawns Counted:** {state['total_yawns']}"""return frame, state, audio_update, dashboard_text# -----------------------------------------------------------------------------# 4. Gradio Interface# -----------------------------------------------------------------------------with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# π Ultra AI Driver Drowsiness & Distraction Monitor")with gr.Row():with gr.Column(scale=2):out_video = gr.Image(label="Live Intelligent Monitoring Feed")# Hide the raw input webcam feed inside an accordion to keep the UI cleanwith gr.Accordion("Raw Webcam Settings (Keep Open to Stream)", open=False):in_video = gr.Image(sources=["webcam"], streaming=True, label="Raw Feed")with gr.Column(scale=1):analytics_board = gr.Markdown("Waiting for camera data...")alarm_audio = gr.Audio(autoplay=True, visible=False)session_state = gr.State()1 unmodified linein_video.stream(fn=process_frame,inputs=[in_video, session_state],outputs=[out_video, session_state, alarm_audio, analytics_board])if __name__ == "__main__":
app.py+132-38