Spaces:
Sleeping
Sleeping
TheKnight115
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,36 @@
|
|
1 |
import streamlit as st
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
-
from ultralytics import YOLO
|
5 |
import tempfile
|
6 |
import time
|
|
|
7 |
from huggingface_hub import hf_hub_download
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
# Color mapping for different classes
|
11 |
class_colors = {
|
@@ -17,176 +42,177 @@ class_colors = {
|
|
17 |
5: (0, 255, 255), # Yellow (Person)
|
18 |
}
|
19 |
|
|
|
|
|
|
|
20 |
|
|
|
|
|
21 |
def run_yolo(image):
|
22 |
-
# Run the model on the image and get results
|
23 |
results = model(image)
|
24 |
return results
|
25 |
|
|
|
|
|
26 |
def process_results(results, image):
|
27 |
-
|
28 |
-
boxes = results[0].boxes # Get boxes from results
|
29 |
for box in boxes:
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
cv2.
|
39 |
-
cv2.putText(image, f"{label} {conf:.2f}", (x1, y1 - 10),
|
40 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
41 |
-
|
42 |
return image
|
43 |
|
44 |
|
|
|
45 |
def process_image(uploaded_file):
|
46 |
-
# Read the image file
|
47 |
image = np.array(cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1))
|
48 |
-
|
49 |
-
# Run YOLO model on the image
|
50 |
results = run_yolo(image)
|
51 |
-
|
52 |
-
# Process the results and draw boxes on the image
|
53 |
processed_image = process_results(results, image)
|
54 |
-
|
55 |
-
# Convert the image from BGR to RGB before displaying it
|
56 |
processed_image_rgb = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
|
57 |
-
|
58 |
-
# Display the processed image in Streamlit
|
59 |
st.image(processed_image_rgb, caption='Detected Image', use_column_width=True)
|
60 |
|
61 |
-
|
|
|
62 |
@st.cache_data
|
63 |
def process_video_and_save(uploaded_file):
|
64 |
-
# Create a temporary file to save the uploaded video
|
65 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_file:
|
66 |
temp_file.write(uploaded_file.read())
|
67 |
-
temp_file_path = temp_file.name
|
68 |
|
69 |
-
# Read the video file
|
70 |
video = cv2.VideoCapture(temp_file_path)
|
71 |
-
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
72 |
frames = []
|
73 |
-
|
74 |
current_frame = 0
|
75 |
-
start_time = time.time()
|
76 |
|
77 |
-
# Initialize the progress bar in Streamlit
|
78 |
progress_bar = st.progress(0)
|
79 |
progress_text = st.empty()
|
80 |
|
81 |
while True:
|
82 |
ret, frame = video.read()
|
83 |
if not ret:
|
84 |
-
break
|
85 |
-
|
86 |
-
# Run YOLO model on the current frame
|
87 |
results = run_yolo(frame)
|
88 |
-
|
89 |
-
# Process the results and draw boxes on the current frame
|
90 |
processed_frame = process_results(results, frame)
|
91 |
-
|
92 |
-
# Convert the frame from BGR to RGB before displaying
|
93 |
processed_frame_rgb = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
|
94 |
-
frames.append(processed_frame_rgb)
|
95 |
|
96 |
current_frame += 1
|
97 |
-
|
98 |
-
# Update progress bar and percentage text
|
99 |
progress_percentage = int((current_frame / total_frames) * 100)
|
100 |
progress_bar.progress(progress_percentage)
|
101 |
progress_text.text(f"Processing frame {current_frame}/{total_frames} ({progress_percentage}%)")
|
102 |
|
103 |
video.release()
|
104 |
-
|
105 |
-
# Create a video writer to save the processed frames
|
106 |
-
height, width, _ = frames[0].shape
|
107 |
output_path = 'processed_video.mp4'
|
|
|
108 |
out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 30, (width, height))
|
109 |
|
110 |
for frame in frames:
|
111 |
-
# Convert back to BGR for saving the video
|
112 |
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
113 |
-
out.write(frame_bgr)
|
114 |
|
115 |
out.release()
|
116 |
-
|
117 |
-
# Return the path of the processed video
|
118 |
return output_path
|
119 |
|
120 |
|
|
|
121 |
def live_video_feed():
|
122 |
-
stframe = st.empty()
|
123 |
-
video = cv2.VideoCapture(0)
|
124 |
-
start_time = time.time()
|
125 |
|
126 |
while True:
|
127 |
ret, frame = video.read()
|
128 |
if not ret:
|
129 |
break
|
130 |
|
131 |
-
# Run YOLO model on the current frame
|
132 |
results = run_yolo(frame)
|
133 |
-
|
134 |
-
# Process the results and draw boxes on the current frame
|
135 |
processed_frame = process_results(results, frame)
|
136 |
-
|
137 |
-
# Convert the frame from BGR to RGB before displaying
|
138 |
processed_frame_rgb = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
|
139 |
-
|
140 |
-
# Display the processed frame in the Streamlit app
|
141 |
stframe.image(processed_frame_rgb, channels="RGB", use_column_width=True)
|
142 |
|
143 |
-
# Display the timer (elapsed time)
|
144 |
elapsed_time = time.time() - start_time
|
145 |
st.write(f"Elapsed Time: {elapsed_time:.2f} seconds")
|
146 |
|
147 |
-
# Stop the live feed when the user clicks the "Stop" button
|
148 |
if st.button("Stop"):
|
149 |
break
|
150 |
|
151 |
video.release()
|
152 |
-
st.stop()
|
153 |
-
|
154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
def main():
|
156 |
model_file = hf_hub_download(repo_id="TheKnight115/Yolov8m", filename="yolov8_Medium.pt")
|
157 |
-
|
158 |
global model
|
159 |
model = YOLO(model_file)
|
160 |
|
161 |
st.title("Motorbike Violation Detection")
|
162 |
|
163 |
-
# Create a selection box for input type
|
164 |
input_type = st.selectbox("Select Input Type", ("Image", "Video", "Live Feed"))
|
165 |
|
166 |
-
# Image or video file uploader
|
167 |
if input_type == "Image":
|
168 |
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
169 |
if uploaded_file is not None:
|
170 |
-
# Process the image
|
171 |
process_image(uploaded_file)
|
172 |
|
173 |
elif input_type == "Video":
|
174 |
uploaded_file = st.file_uploader("Choose a video...", type=["mp4", "mov"])
|
175 |
if uploaded_file is not None:
|
176 |
-
# Process and save the video
|
177 |
output_path = process_video_and_save(uploaded_file)
|
178 |
-
|
179 |
-
# Display the processed video
|
180 |
st.video(output_path)
|
181 |
|
182 |
-
# Provide a download button for the processed video
|
183 |
-
with open(output_path, 'rb') as f:
|
184 |
-
video_bytes = f.read()
|
185 |
-
st.download_button(label='Download Processed Video',
|
186 |
-
data=video_bytes, file_name='processed_video.mp4', mime='video/mp4')
|
187 |
-
|
188 |
elif input_type == "Live Feed":
|
189 |
-
st.write("Live video feed from webcam. Press 'Stop' to stop the feed.")
|
190 |
live_video_feed()
|
191 |
|
192 |
|
|
|
1 |
import streamlit as st
|
2 |
import cv2
|
3 |
import numpy as np
|
|
|
4 |
import tempfile
|
5 |
import time
|
6 |
+
from ultralytics import YOLO
|
7 |
from huggingface_hub import hf_hub_download
|
8 |
+
from email.mime.text import MIMEText
|
9 |
+
from email.mime.multipart import MIMEMultipart
|
10 |
+
from email.mime.base import MIMEBase
|
11 |
+
from email import encoders
|
12 |
+
import os
|
13 |
+
import smtplib
|
14 |
+
from transformers import AutoModel, AutoProcessor
|
15 |
+
from PIL import Image, ImageDraw, ImageFont
|
16 |
+
import re
|
17 |
+
import torch
|
18 |
+
|
19 |
+
# Email credentials
|
20 |
+
FROM_EMAIL = "Fares5675@gmail.com"
|
21 |
+
EMAIL_PASSWORD = "cawxqifzqiwjufde" # App-Specific Password
|
22 |
+
TO_EMAIL = "Fares5675@gmail.com"
|
23 |
+
SMTP_SERVER = 'smtp.gmail.com'
|
24 |
+
SMTP_PORT = 465
|
25 |
+
|
26 |
+
# Arabic dictionary for converting license plate text
|
27 |
+
arabic_dict = {
|
28 |
+
"0": "٠", "1": "١", "2": "٢", "3": "٣", "4": "٤", "5": "٥",
|
29 |
+
"6": "٦", "7": "٧", "8": "٨", "9": "٩", "A": "ا", "B": "ب",
|
30 |
+
"J": "ح", "D": "د", "R": "ر", "S": "س", "X": "ص", "T": "ط",
|
31 |
+
"E": "ع", "G": "ق", "K": "ك", "L": "ل", "Z": "م", "N": "ن",
|
32 |
+
"H": "ه", "U": "و", "V": "ي", " ": " "
|
33 |
+
}
|
34 |
|
35 |
# Color mapping for different classes
|
36 |
class_colors = {
|
|
|
42 |
5: (0, 255, 255), # Yellow (Person)
|
43 |
}
|
44 |
|
45 |
+
# Load the OCR model
|
46 |
+
processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR2_0", trust_remote_code=True)
|
47 |
+
model_ocr = AutoModel.from_pretrained("stepfun-ai/GOT-OCR2_0", trust_remote_code=True).to('cuda')
|
48 |
|
49 |
+
|
50 |
+
# YOLO inference function
|
51 |
def run_yolo(image):
|
|
|
52 |
results = model(image)
|
53 |
return results
|
54 |
|
55 |
+
|
56 |
+
# Function to process YOLO results and draw bounding boxes
|
57 |
def process_results(results, image):
|
58 |
+
boxes = results[0].boxes
|
|
|
59 |
for box in boxes:
|
60 |
+
x1, y1, x2, y2 = map(int, box.xyxy[0])
|
61 |
+
conf = box.conf[0]
|
62 |
+
cls = int(box.cls[0])
|
63 |
+
label = model.names[cls]
|
64 |
+
color = class_colors.get(cls, (255, 255, 255))
|
65 |
+
|
66 |
+
# Draw rectangle and label
|
67 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
|
68 |
+
cv2.putText(image, f"{label} {conf:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
|
|
|
|
|
|
69 |
return image
|
70 |
|
71 |
|
72 |
+
# Process uploaded images
|
73 |
def process_image(uploaded_file):
|
|
|
74 |
image = np.array(cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1))
|
|
|
|
|
75 |
results = run_yolo(image)
|
|
|
|
|
76 |
processed_image = process_results(results, image)
|
|
|
|
|
77 |
processed_image_rgb = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
|
|
|
|
|
78 |
st.image(processed_image_rgb, caption='Detected Image', use_column_width=True)
|
79 |
|
80 |
+
|
81 |
+
# Process and save uploaded videos
|
82 |
@st.cache_data
|
83 |
def process_video_and_save(uploaded_file):
|
|
|
84 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_file:
|
85 |
temp_file.write(uploaded_file.read())
|
86 |
+
temp_file_path = temp_file.name
|
87 |
|
|
|
88 |
video = cv2.VideoCapture(temp_file_path)
|
89 |
+
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
90 |
frames = []
|
|
|
91 |
current_frame = 0
|
92 |
+
start_time = time.time()
|
93 |
|
|
|
94 |
progress_bar = st.progress(0)
|
95 |
progress_text = st.empty()
|
96 |
|
97 |
while True:
|
98 |
ret, frame = video.read()
|
99 |
if not ret:
|
100 |
+
break
|
|
|
|
|
101 |
results = run_yolo(frame)
|
|
|
|
|
102 |
processed_frame = process_results(results, frame)
|
|
|
|
|
103 |
processed_frame_rgb = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
|
104 |
+
frames.append(processed_frame_rgb)
|
105 |
|
106 |
current_frame += 1
|
|
|
|
|
107 |
progress_percentage = int((current_frame / total_frames) * 100)
|
108 |
progress_bar.progress(progress_percentage)
|
109 |
progress_text.text(f"Processing frame {current_frame}/{total_frames} ({progress_percentage}%)")
|
110 |
|
111 |
video.release()
|
|
|
|
|
|
|
112 |
output_path = 'processed_video.mp4'
|
113 |
+
height, width, _ = frames[0].shape
|
114 |
out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 30, (width, height))
|
115 |
|
116 |
for frame in frames:
|
|
|
117 |
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
118 |
+
out.write(frame_bgr)
|
119 |
|
120 |
out.release()
|
|
|
|
|
121 |
return output_path
|
122 |
|
123 |
|
124 |
+
# Live video feed processing
|
125 |
def live_video_feed():
|
126 |
+
stframe = st.empty()
|
127 |
+
video = cv2.VideoCapture(0)
|
128 |
+
start_time = time.time()
|
129 |
|
130 |
while True:
|
131 |
ret, frame = video.read()
|
132 |
if not ret:
|
133 |
break
|
134 |
|
|
|
135 |
results = run_yolo(frame)
|
|
|
|
|
136 |
processed_frame = process_results(results, frame)
|
|
|
|
|
137 |
processed_frame_rgb = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
|
|
|
|
|
138 |
stframe.image(processed_frame_rgb, channels="RGB", use_column_width=True)
|
139 |
|
|
|
140 |
elapsed_time = time.time() - start_time
|
141 |
st.write(f"Elapsed Time: {elapsed_time:.2f} seconds")
|
142 |
|
|
|
143 |
if st.button("Stop"):
|
144 |
break
|
145 |
|
146 |
video.release()
|
147 |
+
st.stop()
|
148 |
+
|
149 |
+
|
150 |
+
# Function to filter license plate text
|
151 |
+
def filter_license_plate_text(license_plate_text):
|
152 |
+
license_plate_text = re.sub(r'[^A-Z0-9]+', "", license_plate_text)
|
153 |
+
match = re.search(r'(\d{3,4})\s*([A-Z]{2})', license_plate_text)
|
154 |
+
return f"{match.group(1)} {match.group(2)}" if match else None
|
155 |
+
|
156 |
+
|
157 |
+
# Function to convert license plate text to Arabic
|
158 |
+
def convert_to_arabic(license_plate_text):
|
159 |
+
return "".join(arabic_dict.get(char, char) for char in license_plate_text)
|
160 |
+
|
161 |
+
|
162 |
+
# Function to send email notification with image attachment
|
163 |
+
def send_email(license_text, violation_image_path, violation_type):
|
164 |
+
if violation_type == 'no_helmet':
|
165 |
+
subject = 'تنبيه مخالفة: عدم ارتداء خوذة'
|
166 |
+
body = f"لعدم ارتداء الخوذة ({license_text}) تم تغريم دراجة نارية التي تحمل لوحة."
|
167 |
+
elif violation_type == 'in_red_lane':
|
168 |
+
subject = 'تنبيه مخالفة: دخول المسار الأيسر'
|
169 |
+
body = f"لدخولها المسار الأيسر ({license_text}) تم تغريم دراجة نارية التي تحمل لوحة."
|
170 |
+
elif violation_type == 'no_helmet_in_red_lane':
|
171 |
+
subject = 'تنبيه مخالفة: عدم ارتداء خوذة ودخول المسار الأيسر'
|
172 |
+
body = f"لعدم ارتداء الخوذة ولدخولها المسار الأيسر ({license_text}) تم تغريم دراجة نارية التي تحمل لوحة."
|
173 |
+
|
174 |
+
msg = MIMEMultipart()
|
175 |
+
msg['From'] = FROM_EMAIL
|
176 |
+
msg['To'] = TO_EMAIL
|
177 |
+
msg['Subject'] = subject
|
178 |
+
msg.attach(MIMEText(body, 'plain'))
|
179 |
+
|
180 |
+
if os.path.exists(violation_image_path):
|
181 |
+
with open(violation_image_path, 'rb') as attachment_file:
|
182 |
+
part = MIMEBase('application', 'octet-stream')
|
183 |
+
part.set_payload(attachment_file.read())
|
184 |
+
encoders.encode_base64(part)
|
185 |
+
part.add_header('Content-Disposition', f'attachment; filename={os.path.basename(violation_image_path)}')
|
186 |
+
msg.attach(part)
|
187 |
+
|
188 |
+
with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
|
189 |
+
server.login(FROM_EMAIL, EMAIL_PASSWORD)
|
190 |
+
server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())
|
191 |
+
print("Email with attachment sent successfully!")
|
192 |
+
|
193 |
+
|
194 |
+
# Streamlit app main function
|
195 |
def main():
|
196 |
model_file = hf_hub_download(repo_id="TheKnight115/Yolov8m", filename="yolov8_Medium.pt")
|
|
|
197 |
global model
|
198 |
model = YOLO(model_file)
|
199 |
|
200 |
st.title("Motorbike Violation Detection")
|
201 |
|
|
|
202 |
input_type = st.selectbox("Select Input Type", ("Image", "Video", "Live Feed"))
|
203 |
|
|
|
204 |
if input_type == "Image":
|
205 |
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
206 |
if uploaded_file is not None:
|
|
|
207 |
process_image(uploaded_file)
|
208 |
|
209 |
elif input_type == "Video":
|
210 |
uploaded_file = st.file_uploader("Choose a video...", type=["mp4", "mov"])
|
211 |
if uploaded_file is not None:
|
|
|
212 |
output_path = process_video_and_save(uploaded_file)
|
|
|
|
|
213 |
st.video(output_path)
|
214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
elif input_type == "Live Feed":
|
|
|
216 |
live_video_feed()
|
217 |
|
218 |
|