import cv2
from playsound import playsound

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyes_cascade = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')
video = cv2.VideoCapture("video.avi")
frame_counter = 0
video_frames_count = video.get(cv2.CAP_PROP_FRAME_COUNT)
video_fps = video.get(cv2.CAP_PROP_FPS)
thresh_hold = 2
eyes_closed_time = 0
eyes_closed_time_sec = 0

while True:
    ret, frame = video.read()
    faces = face_cascade.detectMultiScale(frame, 1.1, 5)
    frame_counter += 1

    for (x, y, w, h) in faces:
        eyes_color = frame[y:y + h, x:x + w]
        eyes = eyes_cascade.detectMultiScale(eyes_color, 1.1, 5, minSize=(50, 50))
        if len(eyes) < 2:
            eyes_closed_time += 1
            eyes_closed_time_sec = eyes_closed_time / video_fps
            if (eyes_closed_time_sec) >= thresh_hold:
                eyes_closed_time = 0
                playsound('wakeup.mp3', False)
                print('You fall asleep.')
        else:
            eyes_closed_time = 0
            eyes_closed_time_sec = 0

    cv2.rectangle(frame, (5, 5), (215, 80), (0, 0, 0), -1)
    cv2.rectangle(frame, (10, 10), (210, 50), (255, 255, 255), -1)
    cv2.rectangle(frame, (10, 10), (int(eyes_closed_time_sec / thresh_hold * 200) + 10, 50), (0, 0, 255), -1)
    cv2.putText(frame, "Somnolence", (10, 70), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255))
    cv2.imshow('Drive control', frame)
    if frame_counter == video_frames_count:
        frame_counter = 0
        video.set(cv2.CAP_PROP_POS_FRAMES, 0)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()