elucidator8918 commited on
Commit
993db33
·
verified ·
1 Parent(s): 8d1d10d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from tensorflow.keras.models import load_model
4
+ import gradio as gr
5
+ import tempfile
6
+ import os
7
+
8
+ # Load your pre-trained model
9
+ model = load_model('cnn_lstm1.h5')
10
+
11
+ # Function to preprocess each frame
12
+ def preprocess_frame(frame):
13
+ resized_frame = cv2.resize(frame, (224, 224)) # Adjust size based on your model's input shape
14
+ normalized_frame = resized_frame / 255.0
15
+ return np.expand_dims(normalized_frame, axis=0) # Add batch dimension
16
+
17
+ # Function to process the video and make predictions
18
+ def predict_drowsiness(video_path):
19
+ # Open the video file
20
+ cap = cv2.VideoCapture(video_path)
21
+ frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
22
+ frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
23
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
24
+
25
+ # Create a temporary file for the output video
26
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_output:
27
+ temp_output_path = temp_output.name
28
+
29
+ # Output video settings
30
+ out = cv2.VideoWriter(temp_output_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height))
31
+
32
+ while cap.isOpened():
33
+ ret, frame = cap.read()
34
+ if not ret:
35
+ break
36
+
37
+ # Preprocess frame
38
+ preprocessed_frame = preprocess_frame(frame)
39
+
40
+ # Use the model to predict drowsiness
41
+ prediction = model.predict(preprocessed_frame)
42
+ drowsiness = np.argmax(prediction)
43
+
44
+ # Add label to frame
45
+ label = 'Drowsy' if drowsiness == 0 else 'Alert'
46
+ cv2.putText(frame, label, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
47
+
48
+ # Write the frame with label to the output video
49
+ out.write(frame)
50
+
51
+ # Release resources
52
+ cap.release()
53
+ out.release()
54
+
55
+ return temp_output_path # Return the path to the temporary output video
56
+
57
+ # Gradio interface
58
+ interface = gr.Interface(
59
+ fn=predict_drowsiness,
60
+ inputs=gr.Video(), # Video input from webcam or upload
61
+ outputs="video", # Return a playable video with predictions
62
+ title="Drowsiness Detection in Video",
63
+ description="Upload a video or record one, and this tool will detect if the person is drowsy.",
64
+ )
65
+
66
+ # Launch the app
67
+ if __name__ == "__main__":
68
+ interface.launch()