bushra1dajam commited on
Commit
86b2bd4
1 Parent(s): ef28085

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -96
app.py CHANGED
@@ -1,96 +1,149 @@
1
- import streamlit as st
2
- import cv2
3
- from ultralytics import YOLO
4
- import cvzone
5
- import math
6
- import pygame
7
-
8
- # Initialize pygame mixer
9
- pygame.mixer.init()
10
-
11
- # Load sound
12
- alert_sound = pygame.mixer.Sound('siren-alert-96052.mp3') # Using raw string
13
-
14
- # Load the model
15
- model = YOLO('best.pt')
16
-
17
- # Reading the classes
18
- classnames = ['Drowsy', 'Awake']
19
-
20
- # Streamlit UI
21
- st.title("Real-Time Drowsiness Detection")
22
-
23
- # Layout
24
- col1, col2 = st.columns(2)
25
-
26
- with col1:
27
- start_button = st.button('Start Webcam')
28
-
29
- with col2:
30
- stop_button = st.button('Stop Webcam')
31
-
32
- stframe = st.empty()
33
- status_text = st.empty()
34
- message_text = st.empty()
35
-
36
- if start_button:
37
- cap = cv2.VideoCapture(0)
38
- drowsy_count = 0 # Counter for consecutive "Drowsy" detections
39
-
40
- while cap.isOpened():
41
- ret, frame = cap.read()
42
- if not ret:
43
- status_text.write("Failed to grab frame")
44
- break
45
-
46
- frame = cv2.resize(frame, (640, 480))
47
-
48
- # Run the model on the frame
49
- result = model(frame, stream=True)
50
-
51
- # Flag to track if "Drowsy" is detected in this frame
52
- drowsy_detected = False
53
-
54
- # Getting bbox, confidence, and class name information to work with
55
- for info in result:
56
- boxes = info.boxes
57
- for box in boxes:
58
- confidence = box.conf[0]
59
- confidence = math.ceil(confidence * 100)
60
- Class = int(box.cls[0])
61
- if confidence > 50:
62
- x1, y1, x2, y2 = box.xyxy[0]
63
- x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
64
- cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
65
- cvzone.putTextRect(frame, f'{classnames[Class]} {confidence}%', [x1 + 8, y1 + 100],
66
- scale=1.5, thickness=2)
67
- if classnames[Class] == 'Drowsy':
68
- drowsy_detected = True
69
-
70
- # Increment the counter if "Drowsy" is detected, otherwise reset the counter
71
- if drowsy_detected:
72
- drowsy_count += 1
73
- status_text.write("Drowsiness detected!")
74
- else:
75
- drowsy_count = 0
76
- status_text.write("Monitoring...")
77
-
78
- # Play alert sound and send message if "Drowsy" is detected 3 or more times
79
- if drowsy_count >= 3:
80
- pygame.mixer.Sound.play(alert_sound)
81
- message_text.write("**Be careful!** Drowsiness detected multiple times!")
82
- drowsy_count = 0 # Reset the counter after playing the sound
83
-
84
- # Convert image back to RGB for Streamlit
85
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
86
-
87
- # Display the image
88
- stframe.image(frame, channels="RGB")
89
-
90
- # Check if stop button is pressed
91
- if stop_button:
92
- break
93
-
94
- cap.release()
95
- status_text.write("Webcam stopped.")
96
- message_text.write("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ from ultralytics import YOLO
4
+ import cvzone
5
+ import math
6
+ import pygame
7
+ import numpy as np
8
+
9
+ # Initialize pygame mixer
10
+ pygame.mixer.init()
11
+
12
+ # Load sound
13
+ alert_sound = pygame.mixer.Sound('alarm.mp3')
14
+
15
+ # Load the model
16
+ model = YOLO('best.pt')
17
+
18
+ # Reading the classes
19
+ classnames = ['Drowsy', 'Awake']
20
+
21
+ # Streamlit UI
22
+ st.set_page_config(layout="wide") # Set wide layout
23
+
24
+ # Add the logo to the sidebar
25
+ logo_path = "logo.png" # Use the uploaded file path
26
+ st.sidebar.empty() # Add empty space
27
+ st.sidebar.image(logo_path, use_column_width=True)
28
+
29
+ # Create a sidebar for navigation
30
+ st.sidebar.title("Options")
31
+ page = st.sidebar.selectbox("Choose a page", ["Webcam Detection", "Image Upload"])
32
+
33
+ st.title("Drowsiness Detection")
34
+
35
+ if page == "Webcam Detection":
36
+ st.header("Real-Time Drowsiness Detection")
37
+
38
+ # Layout
39
+ col1, col2 = st.columns(2)
40
+
41
+ with col1:
42
+ start_button = st.button('Start Webcam')
43
+
44
+ with col2:
45
+ stop_button = st.button('Stop Webcam')
46
+
47
+ alert_placeholder = st.empty() # Placeholder for alerts
48
+ stframe = st.empty()
49
+ status_text = st.empty()
50
+ message_text = st.empty()
51
+
52
+ if start_button:
53
+ cap = cv2.VideoCapture(0)
54
+ drowsy_count = 0 # Counter for consecutive "Drowsy" detections
55
+
56
+ while cap.isOpened():
57
+ ret, frame = cap.read()
58
+ if not ret:
59
+ status_text.write("Failed to grab frame")
60
+ break
61
+
62
+ frame = cv2.resize(frame, (640, 480))
63
+
64
+ # Run the model on the frame
65
+ result = model(frame, stream=True)
66
+
67
+ # Flag to track if "Drowsy" is detected in this frame
68
+ drowsy_detected = False
69
+
70
+ # Getting bbox, confidence, and class name information to work with
71
+ for info in result:
72
+ boxes = info.boxes
73
+ for box in boxes:
74
+ confidence = box.conf[0]
75
+ confidence = math.ceil(confidence * 100)
76
+ Class = int(box.cls[0])
77
+ if confidence > 50:
78
+ x1, y1, x2, y2 = box.xyxy[0]
79
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
80
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
81
+ cvzone.putTextRect(frame, f'{classnames[Class]} {confidence}%', [x1 + 8, y1 + 100],
82
+ scale=1.5, thickness=2)
83
+ if classnames[Class] == 'Drowsy':
84
+ drowsy_detected = True
85
+
86
+ # Increment the counter if "Drowsy" is detected, otherwise reset the counter
87
+ if drowsy_detected:
88
+ drowsy_count += 1
89
+ status_text.write("Drowsiness detected!")
90
+ else:
91
+ drowsy_count = 0
92
+ status_text.write("Monitoring...")
93
+
94
+ # Play alert sound and send message if "Drowsy" is detected 3 or more times
95
+ if drowsy_count >= 3:
96
+ pygame.mixer.Sound.play(alert_sound)
97
+ alert_placeholder.markdown(
98
+ f'<div style="color: red; font-size: 24px; border: 2px solid red; padding: 10px;">**Be careful! Drowsiness detected!**</div>',
99
+ unsafe_allow_html=True,
100
+ )
101
+ drowsy_count = 0 # Reset the counter after playing the sound
102
+
103
+ # Convert image back to RGB for Streamlit
104
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
105
+
106
+ # Display the image
107
+ stframe.image(frame, channels="RGB")
108
+
109
+ # Check if stop button is pressed
110
+ if stop_button:
111
+ break
112
+
113
+ cap.release()
114
+ status_text.write("Webcam stopped.")
115
+ message_text.write("")
116
+ alert_placeholder.empty()
117
+
118
+ elif page == "Image Upload":
119
+ st.header("Drowsiness Detection on Image")
120
+
121
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
122
+
123
+ if uploaded_file is not None:
124
+ # Read the image
125
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
126
+ frame = cv2.imdecode(file_bytes, 1)
127
+
128
+ # Perform prediction
129
+ results = model(frame, stream=True)
130
+
131
+ # Process the results
132
+ for result in results:
133
+ boxes = result.boxes
134
+ for box in boxes:
135
+ confidence = box.conf[0]
136
+ confidence = math.ceil(confidence * 100)
137
+ Class = int(box.cls[0])
138
+ if confidence > 50:
139
+ x1, y1, x2, y2 = box.xyxy[0]
140
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
141
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
142
+ cv2.putText(frame, f'{classnames[Class]} {confidence}%', (x1 + 8, y1 + 100),
143
+ cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2, cv2.LINE_AA)
144
+
145
+ # Convert image back to RGB for Streamlit
146
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
147
+
148
+ # Display the image
149
+ st.image(frame, channels="RGB")