Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011122 unmodified lines151617181920212223242526272829303132333435363 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import cv2import mediapipe as mpimport numpy as npimport gradio as grimport os# =========================# CONFIG# =========================EAR_THRESHOLD = 0.25EAR_FRAMES = 202 unmodified linescounter = 0status = "Driver Alert"# =========================# Alert File Check# =========================ALERT_FILE = "alert.mp3"if not os.path.exists(ALERT_FILE):ALERT_FILE = None # If no audio file available# =========================# Mediapipe Setup# =========================mp_face_mesh = mp.solutions.face_meshface_mesh = mp_face_mesh.FaceMesh(static_image_mode=False,max_num_faces=1,refine_landmarks=True3 unmodified linesRIGHT_EYE = [362,385,387,263,373,380]MOUTH = [78,81,13,311,308,402,14,178,88,95,78]# =========================# EAR Calculation# =========================def eye_aspect_ratio(eye):A = np.linalg.norm(eye[1] - eye[5])B = np.linalg.norm(eye[2] - eye[4])C = np.linalg.norm(eye[0] - eye[3])return (A + B) / (2.0 * C)# =========================# MAR Calculation# =========================def mouth_aspect_ratio(mouth):A = np.linalg.norm(mouth[2] - mouth[10])B = np.linalg.norm(mouth[4] - mouth[8])C = np.linalg.norm(mouth[0] - mouth[6])return (A + B) / (2.0 * C)# =========================# Detection Function# =========================def detect(frame):global counterglobal statusif frame is None:return None, "No Camera Input", "Please enable your webcam.", Noneframe = cv2.flip(frame,1)rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)results = face_mesh.process(rgb)alert_audio = Nonewarning_text = ""if results.multi_face_landmarks:for face_landmarks in results.multi_face_landmarks:h,w,_ = frame.shapecoords = []for lm in face_landmarks.landmark:x = int(lm.x*w)y = int(lm.y*h)coords.append((x,y))coords = np.array(coords)left_eye = coords[LEFT_EYE]right_eye = coords[RIGHT_EYE]mouth = coords[MOUTH]leftEAR = eye_aspect_ratio(left_eye)rightEAR = eye_aspect_ratio(right_eye)ear = (leftEAR + rightEAR)/2mar = mouth_aspect_ratio(mouth)# -----------------# Drowsiness logic# -----------------if ear < EAR_THRESHOLD:counter += 1if counter > EAR_FRAMES:status = "Driver Drowsy"warning_text = "⚠️ WARNING: Driver appears drowsy!"if ALERT_FILE:alert_audio = ALERT_FILEelse:counter = 0status = "Driver Alert"# -----------------# Yawn detection# -----------------if mar > MAR_THRESHOLD:status = "Yawning Detected"warning_text = "⚠️ Driver is yawning."# -----------------# Display metrics# -----------------cv2.putText(frame,f"EAR:{ear:.2f}",(30,40),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)cv2.putText(frame,f"MAR:{mar:.2f}",(30,80),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)cv2.putText(frame,status,(30,120),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3)frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)return frame, status, warning_text, alert_audio# =========================# Gradio Interface# =========================with gr.Blocks() as demo:gr.Markdown("# 🚗 AI Driver Drowsiness Detection System")gr.Markdown("Use **webcam, mobile camera image, or upload a frame** to detect driver drowsiness.")camera = gr.Image(sources=["webcam","upload"],streaming=True,label="Camera Input")output = gr.Image(label="Processed Feed")status_box = gr.Textbox(label="Driver Status")warning_box = gr.Textbox(label="Warning")audio = gr.Audio(label="Alert", autoplay=True)camera.stream(detect,inputs=camera,outputs=[output,status_box,warning_box,audio])demo.launch()12345678910112 unmodified lines14151617181920212223243 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import cv2import numpy as npimport gradio as grfrom mediapipe.python.solutions import face_mesh# ======================# CONFIG# ======================EAR_THRESHOLD = 0.25EAR_FRAMES = 202 unmodified linescounter = 0status = "Driver Alert"# ======================# Face Mesh# ======================mesh = face_mesh.FaceMesh(static_image_mode=False,max_num_faces=1,refine_landmarks=True3 unmodified linesRIGHT_EYE = [362,385,387,263,373,380]MOUTH = [78,81,13,311,308,402,14,178,88,95,78]# ======================# EAR# ======================def eye_aspect_ratio(eye):A = np.linalg.norm(eye[1] - eye[5])B = np.linalg.norm(eye[2] - eye[4])C = np.linalg.norm(eye[0] - eye[3])return (A+B)/(2*C)# ======================# MAR# ======================def mouth_aspect_ratio(mouth):A = np.linalg.norm(mouth[2]-mouth[10])B = np.linalg.norm(mouth[4]-mouth[8])C = np.linalg.norm(mouth[0]-mouth[6])return (A+B)/(2*C)# ======================# Detection# ======================def detect(frame):global counter, statusif frame is None:return None, "No Camera", ""frame = cv2.flip(frame,1)rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)results = mesh.process(rgb)warning=""if results.multi_face_landmarks:h,w,_ = frame.shapefor face_landmarks in results.multi_face_landmarks:coords=[]for lm in face_landmarks.landmark:coords.append((int(lm.x*w), int(lm.y*h)))coords=np.array(coords)left=coords[LEFT_EYE]right=coords[RIGHT_EYE]mouth=coords[MOUTH]ear=(eye_aspect_ratio(left)+eye_aspect_ratio(right))/2mar=mouth_aspect_ratio(mouth)if ear<EAR_THRESHOLD:counter+=1if counter>EAR_FRAMES:status="Driver Drowsy"warning="⚠️ Driver appears drowsy"else:counter=0status="Driver Alert"if mar>MAR_THRESHOLD:status="Yawning"cv2.putText(frame,f"EAR:{ear:.2f}",(20,40),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)cv2.putText(frame,status,(20,80),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)return frame,status,warning# ======================# UI# ======================with gr.Blocks() as demo:gr.Markdown("# 🚗 AI Driver Drowsiness Detection")cam = gr.Image(sources=["webcam"], streaming=True)out = gr.Image()status = gr.Textbox(label="Driver Status")warn = gr.Textbox(label="Warning")cam.stream(detect,inputs=cam,outputs=[out,status,warn])demo.launch()
app.py+60-117