-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalert_module.py
More file actions
381 lines (329 loc) Β· 14.9 KB
/
alert_module.py
File metadata and controls
381 lines (329 loc) Β· 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# import smtplib
# import cv2
# import numpy as np
# import os
# import time
# import sqlite3
# import json
# from datetime import datetime
# from email.mime.multipart import MIMEMultipart
# from email.mime.text import MIMEText
# from email.mime.base import MIMEBase
# from email import encoders
# import plyer
# # πΉ Global settings
# ALERT_INTERVAL = 60
# last_alert_time = {}
# # πΉ Load Camera Settings
# def load_camera_settings():
# if os.path.exists("camera_settings.json"):
# with open("camera_settings.json", "r") as f:
# data = json.load(f)
# if data and isinstance(data[0], str):
# return [{"source": src, "detections": ["motion", "object", "face"]} for src in data]
# return data
# else:
# return [{"source": "0", "detections": ["motion", "object", "face"]}]
# # πΉ Capture Frame Function
# def capture_frame(cam_id):
# cap = cv2.VideoCapture(cam_id , cv2.CAP_DSHOW)
# if not cap.isOpened():
# print(f"[ERROR] Could not access camera {cam_id}")
# return None
# ret, frame = cap.read()
# cap.release()
# if ret:
# image_path = f"alert_frame_cam{cam_id}.jpg"
# cv2.imwrite(image_path, frame)
# print(f"[INFO] Frame captured: {image_path}")
# return image_path
# else:
# print("[ERROR] Failed to capture frame.")
# return None
# # πΉ Send Email with Attachment
# def send_email_notification(subject, message, attachment_path=None):
# sender_email = "shafaqali.3101@gmail.com"
# receiver_email = "khuninha0109@gmail.com"
# password = "rryc jjyi hcrx pdqg"
# msg = MIMEMultipart()
# msg['From'] = sender_email
# msg['To'] = receiver_email
# msg['Subject'] = subject
# msg.attach(MIMEText(message, 'plain'))
# if attachment_path and os.path.exists(attachment_path):
# with open(attachment_path, "rb") as attachment:
# part = MIMEBase("application", "octet-stream")
# part.set_payload(attachment.read())
# encoders.encode_base64(part)
# part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(attachment_path)}")
# msg.attach(part)
# print(f"[INFO] Image attached: {attachment_path}")
# else:
# print("[WARNING] No image attached.")
# try:
# server = smtplib.SMTP('smtp.gmail.com', 587)
# server.starttls()
# server.login(sender_email, password)
# server.sendmail(sender_email, receiver_email, msg.as_string())
# server.quit()
# print("[INFO] Email sent successfully.")
# except Exception as e:
# print(f"[ERROR] Failed to send email: {e}")
# # πΉ Send Local Notification
# def send_local_notification(title, message):
# plyer.notification.notify(
# title=title,
# message=message,
# app_name='Alert System',
# timeout=10
# )
# # πΉ Store Alert in SQLite
# def store_alert(camera, location, message, severity):
# db_path = os.path.join(os.getcwd(), 'alerts.db')
# conn = sqlite3.connect(db_path)
# c = conn.cursor()
# c.execute('''
# CREATE TABLE IF NOT EXISTS alerts (
# id INTEGER PRIMARY KEY AUTOINCREMENT,
# camera TEXT,
# location TEXT,
# time TEXT,
# message TEXT,
# severity TEXT
# )
# ''')
# alert_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# c.execute("INSERT INTO alerts (camera, location, time, message, severity) VALUES (?, ?, ?, ?, ?)",
# (camera, location, alert_time, message, severity))
# conn.commit()
# conn.close()
# print(f"[INFO] Alert stored: {camera}, {location}, {alert_time}, {message}, {severity}")
# # πΉ Check Alert Interval
# def can_trigger_alert(cam_id):
# global last_alert_time
# current_time = time.time()
# if cam_id not in last_alert_time or (current_time - last_alert_time[cam_id] >= ALERT_INTERVAL):
# last_alert_time[cam_id] = current_time
# return True
# else:
# print(f"[DEBUG] Skipping alert for Camera {cam_id} due to time restriction.")
# return False
# # πΉ Main Alert Processing Function
# def alert_process(object_queue, face_queue, motion_queue):
# while True:
# camera_settings = load_camera_settings()
# # π₯ Motion Detection Alerts
# if not motion_queue.empty():
# motion_alert = motion_queue.get()
# cam_id = motion_alert.get("cam_id")
# detection_type = motion_alert.get("detection_type", "motion")
# if cam_id is not None and cam_id < len(camera_settings):
# detections_enabled = camera_settings[cam_id].get("detections", [])
# if detection_type in detections_enabled and can_trigger_alert(cam_id):
# image_path = capture_frame(cam_id) # Capture frame
# store_alert(f"Camera {cam_id}", "Motion Detection",
# motion_alert.get('message', 'Motion detected'),
# motion_alert.get('severity', 'medium'))
# send_email_notification("Motion Detected", motion_alert.get('message', 'Motion detected.'), image_path)
# send_local_notification("Motion Detected", motion_alert.get('message', 'Motion detected.'))
# # π₯ Object Detection Alerts
# if not object_queue.empty():
# obj_event = object_queue.get()
# cam_id = obj_event.get("cam_id")
# detection_type = obj_event.get("detection_type", "object")
# print("[DEBUG] Object event received:", obj_event) # Debugging log
# if cam_id is not None and cam_id < len(camera_settings):
# detections_enabled = camera_settings[cam_id].get("detections", [])
# detections = obj_event.get("detections", [])
# if not detections:
# print(f"[DEBUG] No objects detected in Camera {cam_id}.")
# continue
# if detections_enabled:
# detected_objects = ", ".join(obj.get('label', 'Unknown') for obj in detections)
# image_path = capture_frame(cam_id) # Capture frame
# store_alert(f"Camera {cam_id}", "Object Detection",
# f"Objects detected: {detected_objects}", "high")
# send_email_notification("Object Detected", f"Objects detected: {detected_objects}", image_path)
# send_local_notification("Object Detected", f"Objects detected: {detected_objects}")
# # π₯ Face Recognition Alerts
# if not face_queue.empty():
# face_event = face_queue.get()
# cam_id = face_event.get("cam_id")
# detection_type = face_event.get("detection_type", "face")
# if cam_id is not None and cam_id < len(camera_settings):
# detections_enabled = camera_settings[cam_id].get("detections", [])
# if detection_type in detections_enabled and can_trigger_alert(cam_id):
# detected_name = face_event.get('name', 'Unknown')
# image_path = capture_frame(cam_id) # Capture frame
# alert_message = f"Face detected: {detected_name}"
# store_alert(f"Camera {cam_id}", "Face Recognition", alert_message, "high")
# send_email_notification("Face Detected", alert_message, image_path)
# send_local_notification("Face Detected", alert_message)
# time.sleep(ALERT_INTERVAL)
import smtplib
import cv2
import numpy as np
import os
import time
import sqlite3
import json
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import plyer
# πΉ Global settings
ALERT_INTERVAL = 60
last_alert_time = {}
# πΉ Load Camera Settings
def load_camera_settings():
if os.path.exists("camera_settings.json"):
with open("camera_settings.json", "r") as f:
data = json.load(f)
if data and isinstance(data[0], str):
return [{"source": src, "detections": ["motion", "object", "face"]} for src in data]
return data
else:
return [{"source": "0", "detections": ["motion", "object", "face"]}]
# πΉ Capture Frame Function (β
FIXED)
def capture_frame(cam_id):
cap = cv2.VideoCapture(cam_id, cv2.CAP_DSHOW)
time.sleep(2) # β
Allow camera to adjust
if not cap.isOpened():
print(f"[ERROR] Could not access camera {cam_id}")
return None
ret, frame = cap.read()
cap.release()
if ret and frame is not None:
image_path = f"alert_frame_cam{cam_id}.jpg"
cv2.imwrite(image_path, frame)
# β
Ensure the image is valid before returning
if os.path.exists(image_path) and os.path.getsize(image_path) > 0:
print(f"[INFO] Frame captured successfully: {image_path}")
return image_path
else:
print("[ERROR] Captured image is empty or corrupted.")
return None
else:
print("[ERROR] Failed to capture frame.")
return None
# πΉ Send Email with Attachment (β
FIXED)
def send_email_notification(subject, message, attachment_path=None):
sender_email = "@gmail.com"
receiver_email = "@gmail.com"
password = ""
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
if attachment_path and os.path.exists(attachment_path) and os.path.getsize(attachment_path) > 0:
with open(attachment_path, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(attachment_path)}")
msg.attach(part)
print(f"[INFO] Image attached: {attachment_path}")
else:
print("[WARNING] No valid image attached.")
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
server.quit()
print("[INFO] Email sent successfully.")
except Exception as e:
print(f"[ERROR] Failed to send email: {e}")
# πΉ Send Local Notification
def send_local_notification(title, message):
plyer.notification.notify(
title=title,
message=message,
app_name='Alert System',
timeout=10
)
# πΉ Store Alert in SQLite
def store_alert(camera, location, message, severity):
db_path = os.path.join(os.getcwd(), 'alerts.db')
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
camera TEXT,
location TEXT,
time TEXT,
message TEXT,
severity TEXT
)
''')
alert_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
c.execute("INSERT INTO alerts (camera, location, time, message, severity) VALUES (?, ?, ?, ?, ?)",
(camera, location, alert_time, message, severity))
conn.commit()
conn.close()
print(f"[INFO] Alert stored: {camera}, {location}, {alert_time}, {message}, {severity}")
# πΉ Check Alert Interval
def can_trigger_alert(cam_id):
global last_alert_time
current_time = time.time()
if cam_id not in last_alert_time or (current_time - last_alert_time[cam_id] >= ALERT_INTERVAL):
last_alert_time[cam_id] = current_time
return True
else:
print(f"[DEBUG] Skipping alert for Camera {cam_id} due to time restriction.")
return False
# πΉ Main Alert Processing Function (β
FIXED)
def alert_process(object_queue, face_queue, motion_queue):
while True:
camera_settings = load_camera_settings()
# π₯ Motion Detection Alerts
if not motion_queue.empty():
motion_alert = motion_queue.get()
cam_id = motion_alert.get("cam_id")
detection_type = motion_alert.get("detection_type", "motion")
if cam_id is not None and cam_id < len(camera_settings):
detections_enabled = camera_settings[cam_id].get("detections", [])
if detection_type in detections_enabled and can_trigger_alert(cam_id):
image_path = capture_frame(cam_id)
if image_path:
store_alert(f"Camera {cam_id}", "Motion Detection",
motion_alert.get('message', 'Motion detected'),
motion_alert.get('severity', 'medium'))
send_email_notification("Motion Detected", motion_alert.get('message', 'Motion detected.'), image_path)
send_local_notification("Motion Detected", motion_alert.get('message', 'Motion detected.'))
else:
print("[ERROR] No valid image captured. Skipping email alert.")
# π₯ Object Detection Alerts
if not object_queue.empty():
obj_event = object_queue.get()
cam_id = obj_event.get("cam_id")
detections = obj_event.get("detections", [])
if cam_id is not None and cam_id < len(camera_settings) and detections:
detected_objects = ", ".join(obj.get('label', 'Unknown') for obj in detections)
image_path = capture_frame(cam_id)
if image_path:
store_alert(f"Camera {cam_id}", "Object Detection",
f"Objects detected: {detected_objects}", "high")
send_email_notification("Object Detected", f"Objects detected: {detected_objects}", image_path)
send_local_notification("Object Detected", f"Objects detected: {detected_objects}")
else:
print("[ERROR] No valid image captured. Skipping email alert.")
# π₯ Face Recognition Alerts
if not face_queue.empty():
face_event = face_queue.get()
cam_id = face_event.get("cam_id")
detected_name = face_event.get('name', 'Unknown')
if cam_id is not None and cam_id < len(camera_settings):
image_path = capture_frame(cam_id)
if image_path:
alert_message = f"Face detected: {detected_name}"
store_alert(f"Camera {cam_id}", "Face Recognition", alert_message, "high")
send_email_notification("Face Detected", alert_message, image_path)
send_local_notification("Face Detected", alert_message)
else:
print("[ERROR] No valid image captured. Skipping email alert.")
time.sleep(ALERT_INTERVAL)