forked from TEAM-5-PROJECTS/Wildlife_Monitoring_System
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1034 lines (866 loc) · 45.4 KB
/
app.py
File metadata and controls
1034 lines (866 loc) · 45.4 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ==========================================
# 0. CRITICAL HARDWARE CONFIGURATION
# ==========================================
import os
# This forces the Roboflow/ONNX package to completely ignore your GPU.
os.environ["ONNXRUNTIME_EXECUTION_PROVIDERS"] = "CPUExecutionProvider"
# Standard library imports
import shutil
import base64
import json
import time
import uuid
# Third-party imports
import cv2
import torch
import requests
import paho.mqtt.client as mqtt
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_cors import CORS
from threading import Lock, Thread
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import joinedload
from datetime import datetime
from dotenv import load_dotenv
# AI Model imports
from ultralytics import YOLO
from flask_socketio import SocketIO
# ==========================================
# 1. INITIALIZATION & SETUP
# ==========================================
# Load hidden secrets (like Telegram tokens) from a .env file
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')
ROBOFLOW_API_KEY = os.getenv('ROBOFLOW_API_KEY')
# --- Dynamic Application Settings (Defaults) ---
APP_CONFIG = {
"sensor_cooldown": 5, # Wait 5 seconds before repeating sensor alerts
"weapon_confidence_threshold": 0.50, # Minimum confidence for weapon detection
"species_confidence_threshold": 0.55, # Minimum confidence for wildlife in video smart filter
"time_gap_threshold": 5, # Spam prevention gap per species in video processing
"esp_timeout": 60 , #esp32 disconect time
"gunshot_alert_duration": 3, # How many seconds the gunshot alert stays RED
"node1_triggers_main": False,
# --- NEW: DEFAULT LOCATIONS ---
"location_main": "Unassigned",
"location_node1": "Unassigned"
}
# --- Define Folder Paths ---
BASE_DIR = os.getcwd()
MODEL_FOLDER = os.path.join(BASE_DIR, "speciesnet_model")
CACHE_DIR = os.path.join(BASE_DIR, ".cache")
DETECTIONS_DIR = os.path.join(BASE_DIR, "static", "detections")
VIDEO_DIR = os.path.join(BASE_DIR, "uploads", "videos")
TEMP_DIR = os.path.join(BASE_DIR, "temp_inference", "frames")
UPLOAD_DIR = os.path.join(BASE_DIR, "uploads")
# Tell PyTorch and SpeciesNet to use our custom cache folder
os.environ["XDG_CACHE_HOME"] = CACHE_DIR
os.environ["SPECIESNET_CACHE"] = CACHE_DIR
os.environ["TORCH_HOME"] = CACHE_DIR
# Create all necessary folders if they don't exist yet
for folder in [DETECTIONS_DIR, VIDEO_DIR, TEMP_DIR, UPLOAD_DIR, os.path.join(BASE_DIR, "templates")]:
os.makedirs(folder, exist_ok=True)
# Initialize the Flask Web App
app = Flask(__name__)
CORS(app) # Allows front-end to talk to back-end easily
# Initialize WebSockets for real-time dashboard updates
socketio = SocketIO(app, cors_allowed_origins="*")
# Detect if we have a GPU available
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print("\n" + "="*60)
if DEVICE == "cuda":
gpu_name = torch.cuda.get_device_name(0)
vram_gb = torch.cuda.get_device_properties(0).total_memory / 1e9
print(f"✅ GPU DETECTED AND ACTIVE: {gpu_name}")
print(f"✅ TOTAL VRAM: {vram_gb:.2f} GB")
else:
print("❌ NO GPU DETECTED! PyTorch is falling back to the slow CPU.")
print("⚠️ Check your CUDA installation and PyTorch version.")
print("="*60 + "\n")
print(f"📂 WORKING DIR: {BASE_DIR}")
print(f"🖥️ MAIN AI DEVICE: {DEVICE}")
# Initialize SQLite Database for storing results
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{os.path.join(BASE_DIR, "species_data.db")}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
video_processor = None # Will hold our AI processing class later
# ==========================================
# 2. HELPER FUNCTIONS & DATABASE MODELS
# ==========================================
def send_telegram_alert(message):
"""Sends a push notification to your phone via Telegram."""
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID: return
try:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown"}
requests.post(url, data=payload, timeout=10)
print(f"✅ Telegram sent: {message}")
except Exception as e:
print(f"❌ Telegram Error: {e}")
class VideoRecord(db.Model):
"""Database table to store uploaded video details."""
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(255), nullable=False)
filepath = db.Column(db.String(255), nullable=False)
upload_time = db.Column(db.DateTime, default=datetime.utcnow)
processed = db.Column(db.Boolean, default=False)
detections = db.relationship('DetectionResult', backref='video', lazy=True)
class DetectionResult(db.Model):
"""Database table to store specific animals/weapons found in videos."""
id = db.Column(db.Integer, primary_key=True)
video_id = db.Column(db.Integer, db.ForeignKey('video_record.id'), nullable=False)
species = db.Column(db.String(100), nullable=False)
confidence = db.Column(db.Float, nullable=False)
timestamp_in_video = db.Column(db.Float, nullable=False)
image_url = db.Column(db.String(255), nullable=True)
class SensorEvent(db.Model):
"""Database table to store ESP32 hardware sensor alerts."""
id = db.Column(db.Integer, primary_key=True)
event_type = db.Column(db.String(50), nullable=False) # e.g., 'motion', 'tilt', 'gunshot'
value = db.Column(db.Float, nullable=True) # e.g., the specific tilt angle
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
class NodeConfig(db.Model):
"""Database table to permanently store node settings like Location."""
id = db.Column(db.Integer, primary_key=True)
node_id = db.Column(db.String(50), unique=True, nullable=False)
location = db.Column(db.String(100), default="Unassigned")
# Create the database file if it doesn't exist
with app.app_context(): db.create_all()
# ==========================================
# 3. THE ASYMMETRIC AI MANAGER
# ==========================================
class ModelManager:
"""Loads and manages both the GPU and CPU models safely."""
_instance = None
_lock = Lock()
def __new__(cls):
# Singleton pattern: Ensures we only load the heavy AI models ONCE into memory.
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.model = None # SpeciesNet (GPU)
cls._instance.weapon_model = None # Roboflow (CPU)
cls._instance.initialized = False
return cls._instance
def initialize(self):
"""Loads models into hardware during server startup."""
if self.initialized: return True
if not os.path.exists(MODEL_FOLDER):
print(f"❌ ERROR: SPECIESNET MODEL NOT FOUND AT: {MODEL_FOLDER}")
return False
print("="*60)
print("🧠 STARTING ASYMMETRIC AI ARCHITECTURE...")
print(f"📍 SpeciesNet loading to: {DEVICE} (GPU)")
print(f"📍 Weapon Model loading to: CPU (Intel i5)")
print("="*60)
try:
# 1. Load SpeciesNet to GPU
from speciesnet import SpeciesNet
self.model = SpeciesNet(model_name=MODEL_FOLDER, components='all', geofence=True, multiprocessing=False)
print("✅ SpeciesNet Loaded Successfully (GPU)")
# 2. Load Weapon Model to CPU
print("⏳ Loading Custom Weapon Model...")
weapon_model_path = os.path.join(BASE_DIR, "weapon_model.onnx")
self.weapon_model = YOLO(weapon_model_path)
print("✅ Weapon Model Loaded Successfully (CPU)")
self._warmup()
self.initialized = True
return True
except Exception as e:
print(f"❌ Model load error: {e}")
return False
def _warmup(self):
"""Runs a fake image to wake up the GPU so the first real video isn't slow."""
print("🔥 Warming up GPU...")
try:
import numpy as np
from PIL import Image
dummy_path = os.path.join(BASE_DIR, "warmup.jpg")
Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)).save(dummy_path)
_ = self.model.predict(filepaths=[dummy_path], country="IND", run_mode='single_thread', progress_bars=False)
if os.path.exists(dummy_path): os.remove(dummy_path)
print("🔥 Warmup complete")
except Exception as e:
print(f"⚠️ Warmup failed: {e}")
def predict(self, filepath):
"""Used for single image uploads via the web interface."""
if not self.model: return None
try:
return self.model.predict(filepaths=[filepath], country="IND", run_mode='single_thread', batch_size=1, progress_bars=False)
except Exception as e:
print(f"Prediction Error: {e}")
return None
model_manager = ModelManager()
# ==========================================
# 4. THE TWO-STAGE VIDEO PROCESSOR
# ==========================================
class BatchVideoProcessor:
"""Handles splitting videos into frames and passing them to the models."""
def __init__(self, model_manager):
self.model_manager = model_manager
def process_video_batched(self, video_path, batch_size=8, sample_fps=1, min_confidence=0.3, country='IND', rotate_video=False):
# Note: batch_size=2 protects your 4GB VRAM from crashing
print(f"\n🏆 PROCESSING VIDEO: {video_path}")
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if fps == 0: return []
frame_interval = int(max(1, fps / sample_fps)) # How many frames to skip
paths_buffer, timestamps_buffer, all_detections = [], [], []
video_alert_history = {}
# ⏱️ THE COOLDOWN TRACKER
# Tracks when the CPU last fired, and if we already sent a Telegram alert for this video
video_state = {"last_gun_time": -999, "alert_sent": False}
frame_count = 0
try:
while cap.isOpened():
# Only process 1 frame every second
if frame_count % frame_interval == 0:
ret, frame = cap.read()
if not ret: break
current_time_sec = frame_count / fps
# Optional: Rotate video if AMB82 is mounted sideways
# Optional: Rotate video if AMB82 is mounted sideways
if rotate_video:
frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
# Save frame temporarily for AI to read
frame_path = os.path.join(TEMP_DIR, f"frame_{uuid.uuid4().hex}.jpg")
cv2.imwrite(frame_path, frame)
paths_buffer.append(frame_path)
timestamps_buffer.append(current_time_sec)
# When buffer is full (2 frames), send to AI
if len(paths_buffer) >= batch_size:
batch_detections = self._process_batch(
paths_buffer, timestamps_buffer, country, min_confidence, video_alert_history, video_state
)
all_detections.extend(batch_detections)
# Clean up temp frames to save hard drive space
for p in paths_buffer:
if os.path.exists(p): os.remove(p)
paths_buffer, timestamps_buffer = [], []
print(f"⏳ Progress: {frame_count/max(1, total_frames):.1%}")
else:
ret = cap.grab()
if not ret: break
frame_count += 1
# Process any remaining frames at the end of the video
if paths_buffer:
batch_detections = self._process_batch(
paths_buffer, timestamps_buffer, country, min_confidence, video_alert_history, video_state
)
all_detections.extend(batch_detections)
for p in paths_buffer:
if os.path.exists(p): os.remove(p)
finally:
for p in paths_buffer:
if os.path.exists(p): os.remove(p)
cap.release()
print(f"✅ Video complete. Found {len(all_detections)} detections.")
return all_detections
def _process_batch(self, filepaths, timestamps, country, min_confidence, alert_history, video_state):
if not self.model_manager.model: return []
try:
path_to_time = {fp: ts for fp, ts in zip(filepaths, timestamps)}
# --- STAGE 1: SPECIESNET (GPU) ---
result = self.model_manager.model.predict(filepaths=filepaths, country=country, batch_size=len(filepaths))
valid_detections = []
predictions = result.get('predictions', {})
# Formatting magic to handle SpeciesNet output
if isinstance(predictions, list):
iterator = zip(filepaths, predictions)
is_dict = False
elif isinstance(predictions, dict):
iterator = predictions.items()
is_dict = True
else: return []
for item in iterator:
path_key, pred_data = item if not is_dict else item
if not pred_data: continue
class_data = pred_data.get("classifications", {})
if not class_data: continue
top_score = class_data.get("scores", [0])[0]
if top_score >= min_confidence:
top_class = class_data.get("classes", ["Unknown"])[0]
# Clean up scientific name (e.g. "Panthera tigris; Tiger" -> "Tiger")
if ";" in top_class:
parts = [p.strip() for p in top_class.split(";") if p.strip()]
common_name = parts[-1].title()
else:
common_name = top_class.title()
time_sec = path_to_time.get(path_key, 0)
unique_name = f"det_{uuid.uuid4().hex[:8]}.jpg"
save_path = os.path.join(DETECTIONS_DIR, unique_name)
image_url = None
is_weapon_threat = False
weapon_conf = 0.0
# Read original image to draw boxes and resize
if common_name.lower() not in ["blank", "unknown", "none"]:
if os.path.exists(path_key):
img = cv2.imread(path_key)
if img is not None:
# 🚀 PERFORMANCE FIX: Resize the image BEFORE making the CPU think
h, w = img.shape[:2]
if w > 640:
scale = 640 / w
img = cv2.resize(img, (640, int(h * scale)))
# --- STAGE 2: WEAPON DETECTION (CPU) ---
if common_name.lower() == "human" and (time_sec - video_state["last_gun_time"]) > 3.0:
print(f"👤 Human spotted at {time_sec:.1f}s. Running Weapon Scan on CPU...")
# Run YOLO inference explicitly on CPU
weapon_res = self.model_manager.weapon_model.predict(
source=img,
conf=APP_CONFIG["weapon_confidence_threshold"],
device="cpu",
verbose=False
)
boxes = weapon_res[0].boxes
# If weapon found...
if len(boxes) > 0:
print("🚨 LETHAL WEAPON DETECTED!")
video_state["last_gun_time"] = time_sec
is_weapon_threat = True
weapon_conf = float(boxes.conf[0]) # Confidence of top detection
# Draw Red Bounding Boxes on the image
for box in boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0])
conf = float(box.conf[0])
cls_id = int(box.cls[0])
class_name = weapon_res[0].names[cls_id]
label = f"{class_name} {conf:.2f}"
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2) # Red Box
cv2.putText(img, label, (x1, max(y1 - 10, 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# Send Telegram Alert (ONLY ONCE per video to prevent spam)
if not video_state["alert_sent"]:
# Pulling the main location from APP_CONFIG 👇
cam_location = APP_CONFIG.get("location_main", "Unknown")
msg = f"🚨 *LETHAL WEAPON DETECTED* 🚨\n\n🎯 *Threat:* Armed Human\n⏱️ *Video Time:* {int(time_sec)}s\n📍 *Unit:* Main Camera\n🌍 *Location:* {cam_location}"
Thread(target=send_telegram_alert, args=(msg,)).start()
video_state["alert_sent"] = True
# Save final image to static folder
cv2.imwrite(save_path, img)
image_url = f"/static/detections/{unique_name}"
# Standard Wildlife Telegram Alert (Ignores humans and empty frames)
excluded_categories = ["human", "blank", "unknown", "none"]
if top_score > 0.75 and not is_weapon_threat and common_name.lower() not in excluded_categories:
last_alert = alert_history.get(common_name, -999)
if (time_sec - last_alert) > 30: # Don't spam if a monkey sits in front of camera
msg = f"🐾 *WILDLIFE SIGHTING*\n\n🦁 *Species:* {common_name}\n🎯 *Confidence:* {top_score:.1%}\n⏱️ *Video Time:* {int(time_sec)}s"
Thread(target=send_telegram_alert, args=(msg,)).start()
alert_history[common_name] = time_sec
# Log the original SpeciesNet detection to the database (excluding blanks)
# If it's a human WITH a weapon, completely override the normal human log
if is_weapon_threat:
valid_detections.append({
"species": "ARMED HUMAN", "confidence": weapon_conf,
"timestamp": time_sec, "image_url": image_url
})
else:
# Log normal wildlife and unarmed humans
if common_name.lower() not in ["blank", "unknown", "none"]:
valid_detections.append({
"species": common_name, "confidence": float(top_score),
"timestamp": time_sec, "image_url": image_url
})
return valid_detections
except Exception as e:
print(f"❌ Batch error: {e}")
return []
# ==========================================
# 5. SENSORS (MQTT) & FLASK WEB ROUTES
# ==========================================
# --- Sensor Globals ---
fleet_state = {} # Dynamically stores data for main, node1, node2, etc.
def on_mqtt_connect(client, userdata, flags, rc):
"""Fires when local MQTT broker connects."""
print(f"✅ Connected to MQTT Broker with result code {rc}")
# The '+' wildcard tells the server to listen to ALL cameras
client.subscribe([("security/+/events", 0), ("security/+/heartbeat", 0)])
def on_mqtt_message(client, userdata, msg):
"""Processes incoming sensor data from ANY ESP32 unit."""
global fleet_state
current_time = time.time()
# Extract the node ID from the topic (e.g., "security/main/events" -> "main")
topic_parts = msg.topic.split('/')
if len(topic_parts) < 3: return
node_id = topic_parts[1]
msg_type = topic_parts[2]
# If this is a new camera connecting, create a memory profile for it
if node_id not in fleet_state:
# Fetch the saved location from the Database
with app.app_context():
node_db = NodeConfig.query.filter_by(node_id=node_id).first()
if not node_db:
node_db = NodeConfig(node_id=node_id, location="Unassigned")
db.session.add(node_db)
db.session.commit()
saved_location = node_db.location
fleet_state[node_id] = {
"location": saved_location, # <-- Store location in active memory
"status": {"motion": 0, "tilt": 0.0, "gunshot": 0, "temp": None, "dht_temp": None, "humidity": None, "free_heap": None, "min_heap": None, "rssi": None, "uptime": None, "batt_v": None, "batt_pct": None},
"last_seen": 0,
"gunshot_timestamp": 0,
"alert_history": {"motion": 0, "tilt": 0, "gunshot": 0},
"esp_online": True
}
# Grab this specific camera's memory
node = fleet_state[node_id]
node["last_seen"] = current_time
# Helper function to save to DB (Prepends the node_id to the event type)
def log_event_to_db(event_type, value=None):
with app.app_context():
db_event_type = f"{node_id}_{event_type}"
new_event = SensorEvent(event_type=db_event_type, value=value)
db.session.add(new_event)
db.session.commit()
print(f"💾 Logged {db_event_type.upper()} event to database.")
try:
payload = msg.payload.decode('utf-8')
data = json.loads(payload)
if msg_type == "events":
print(f"📨 {node_id.upper()} Event: {data}")
elif msg_type == "heartbeat":
print(f"💓 {node_id.upper()} Heartbeat: {data}")
# Update specific node status
for k in node["status"]:
if k in data:
node["status"][k] = data[k]
if k == "gunshot" and data[k] == 1:
node["gunshot_timestamp"] = current_time
# Broadcast to WebSockets (Includes the node_id so UI knows which card to update)
with app.app_context():
socketio.emit('sensor_update', {
"node_id": node_id,
"location": node["location"],
**node["status"],
"esp_online": True,
"gunshot": 1 if (current_time - node["gunshot_timestamp"]) < APP_CONFIG["gunshot_alert_duration"] else 0,
"model_loaded": model_manager.model is not None
})
# Process Sensor Alerts
if msg_type == "events":
# 1. MOTION
if data.get('motion') == 1:
if (current_time - node["alert_history"]['motion']) > APP_CONFIG["sensor_cooldown"]:
# Added Location here 👇
msg_text = f"🏃 *MOTION DETECTED* 🏃\n\n⏱️ *Time:* {datetime.now().strftime('%H:%M:%S')}\n📍 *Unit:* {node_id.upper()}\n🌍 *Location:* {node['location']}"
Thread(target=send_telegram_alert, args=(msg_text,)).start()
log_event_to_db("motion")
node["alert_history"]['motion'] = current_time
# ==========================================
# 🚀 NEW: CROSS-NODE TRIGGER LOGIC
# ==========================================
if node_id == "node1" and APP_CONFIG["node1_triggers_main"] == True:
print("🔗 Link Trigger: Node 1 detected motion, sending command to MAIN unit.")
# Change the payload below to whatever string/JSON your main ESP32 expects
payload = "wake"
client.publish("security/main/command", payload)
# 2. TILT
tilt_val = data.get('tilt', 0.0)
if tilt_val > 30:
if (current_time - node["alert_history"]['tilt']) > APP_CONFIG["sensor_cooldown"]:
# Added Location here 👇
msg_text = f"⚠️ *DEVICE TILT WARNING* ⚠️\n\n📉 *Angle:* {tilt_val}°\n📍 *Unit:* {node_id.upper()}\n🌍 *Location:* {node['location']}"
Thread(target=send_telegram_alert, args=(msg_text,)).start()
log_event_to_db("tilt", tilt_val)
node["alert_history"]['tilt'] = current_time
# 3. GUNSHOT
if data.get('gunshot') == 1:
if (current_time - node["alert_history"]['gunshot']) > 1:
# Added Location here 👇
msg_text = f"🔥 *GUNSHOT DETECTED* 🔥\n\n⏱️ *Time:* {datetime.now().strftime('%H:%M:%S')}\n📍 *Unit:* {node_id.upper()}\n🌍 *Location:* {node['location']}\n*IMMEDIATE ACTION REQUIRED*"
Thread(target=send_telegram_alert, args=(msg_text,)).start()
log_event_to_db("gunshot")
node["alert_history"]['gunshot'] = current_time
# ==========================================
# 🚀 NEW: CROSS-NODE TRIGGER LOGIC (GUNSHOT)
# ==========================================
# If node 1 hears a gunshot, and the feature is enabled in settings, wake MAIN
if node_id == "node1" and APP_CONFIG.get("node1_triggers_main") == True:
print("🔗 Link Trigger: Node 1 detected a GUNSHOT! Waking up MAIN unit.")
payload = "wake"
client.publish("security/main/command", payload)
# 4. MANUAL WAKEcls
if data.get('manual_wake') == 1:
log_event_to_db("system", value=1.0)
print(f"✅ Received ACK: {node_id.upper()} manually awakened.")
except Exception as e:
print(f"❌ MQTT Error on {node_id}: {e}")
# --- FLASK ROUTES ---
def handle_amb82_video(video_file, sample_fps=1, min_conf=0.5, country='IND', rotate_video=False):
"""Helper function to save and process uploaded videos."""
filename = secure_filename(f"amb82_{int(time.time())}.mp4")
file_path = os.path.join(VIDEO_DIR, filename)
video_file.save(file_path)
new_video = VideoRecord(filename=filename, filepath=file_path)
db.session.add(new_video)
db.session.commit()
print(f"💾 Video saved to DB: {filename}")
global video_processor
if video_processor is None:
video_processor = BatchVideoProcessor(model_manager)
try:
# 1. Get the raw, unfiltered detections from the AI
raw_detections = video_processor.process_video_batched(
file_path, batch_size=2, sample_fps=sample_fps,
min_confidence=min_conf, country=country, rotate_video=rotate_video
)
# ==========================================
# 🚀 THE "SMART FILTER" PIPELINE
# ==========================================
CONFIDENCE_THRESHOLD = APP_CONFIG["species_confidence_threshold"]
TIME_GAP_THRESHOLD = APP_CONFIG["time_gap_threshold"]
clean_detections = []
last_seen_dict = {}
# Ensure they are in chronological order
raw_detections.sort(key=lambda x: x['timestamp'])
for d in raw_detections:
# Rule 1: Confidence Check
if d['confidence'] < CONFIDENCE_THRESHOLD and d['species'] != "ARMED HUMAN":
continue
# Rule 2: Spam Prevention (5-second gap per species)
last_time = last_seen_dict.get(d['species'], -999)
if (d['timestamp'] - last_time) > TIME_GAP_THRESHOLD:
clean_detections.append(d)
last_seen_dict[d['species']] = d['timestamp']
# Rule 3: Empty Video Purge (Only save if clean_detections has items)
if clean_detections:
for d in clean_detections:
res = DetectionResult(
video_id=new_video.id, species=d['species'], confidence=d['confidence'],
timestamp_in_video=d['timestamp'], image_url=d.get('image_url')
)
db.session.add(res)
new_video.processed = True
db.session.commit()
# Send ONLY the clean data to the UI
return {
"success": True,
"video_id": new_video.id,
"count": len(clean_detections),
"results": clean_detections
}
except Exception as e:
print(f"❌ Error: {e}")
return {"success": False, "error": str(e)}
@app.route('/')
def index(): return render_template('index.html')
@app.route('/sensor')
def sen(): return render_template('sensor.html')
@app.route('/field_unit')
def amb82_analysis(): return render_template('amb82_dashboard.html')
@app.route('/analytics')
def analytics(): return render_template('analytics.html')
@app.route('/test')
def simple_test(): return render_template('simple_test.html')
@app.route('/settings')
def settings(): return render_template('settings.html')
@app.route('/api/detect', methods=['POST'])
def detect():
"""Handles single image uploads from the web interface."""
try:
data = request.get_json(silent=True) or {}
img_data = data.get('image')
if not img_data: return jsonify(success=False, error="No image data"), 400
if "," in img_data: _, encoded = img_data.split(",", 1)
else: encoded = img_data
try: binary = base64.b64decode(encoded)
except Exception: return jsonify(success=False, error="Invalid image encoding"), 400
filename = f"upload_{uuid.uuid4().hex}.jpg"
filepath = os.path.join(UPLOAD_DIR, filename)
with open(filepath, "wb") as f: f.write(binary)
# Initialize models if they somehow fell asleep
if not model_manager.initialized:
print("⚠️ Model wasn't loaded! Attempting to load now...")
model_manager.initialize()
if model_manager.model:
result = model_manager.predict(filepath)
# 1. Read the image into OpenCV BEFORE deleting the temp file
img = cv2.imread(filepath)
if os.path.exists(filepath): os.remove(filepath)
if result:
predictions = result.get('predictions', {})
if not predictions:
return jsonify(success=True, species="None", scientific_name="N/A", confidence=0.0)
if isinstance(predictions, list): pred_data = predictions[0]
elif isinstance(predictions, dict): pred_data = next(iter(predictions.values()))
else: return jsonify(success=False, error="Unknown prediction format"), 500
class_data = pred_data.get("classifications", {})
if not class_data:
return jsonify(success=True, species="None", scientific_name="N/A", confidence=0.0)
top_class = class_data.get("classes", ["Unknown"])[0]
top_score = class_data.get("scores", [0])[0]
if ";" in top_class:
parts = [p.strip() for p in top_class.split(";") if p.strip()]
species = parts[-1].title()
scientific = parts[-2] if len(parts) >= 2 else species
else:
species = top_class.title()
scientific = top_class
# ==========================================
# 🚀 NEW: WEAPON DETECTION FOR SINGLE IMAGES
# ==========================================
# Debug Print 1: See what SpeciesNet actually returned
print(f"\n📸 UI UPLOAD SCANNED: GPU thinks it is a '{species}' (Conf: {top_score:.2f})")
processed_b64 = None
# Make the check more forgiving
is_human = "human" in species.lower() or "person" in species.lower()
if is_human and img is not None:
print("👤 Human detected! Routing image to Intel i5 CPU for Weapon Scan...")
# Resize for CPU speed
h, w = img.shape[:2]
if w > 640:
scale = 640 / w
img = cv2.resize(img, (640, int(h * scale)))
try:
# 1. Run YOLO Weapon Model explicitly on CPU
weapon_res = model_manager.weapon_model.predict(
source=img,
conf=APP_CONFIG["weapon_confidence_threshold"],
device="cpu",
verbose=False
)
# YOLO stores detections inside the 'boxes' attribute
boxes = weapon_res[0].boxes
# Debug Print 2: See how many weapons the CPU found
print(f"🎯 Weapon scan complete. Found {len(boxes)} threats.")
if len(boxes) > 0:
print("🚨 LETHAL WEAPON DETECTED in UI upload! Drawing boxes...")
species = "ARMED HUMAN"
scientific = "Lethal Threat Detected"
top_score = float(boxes.conf[0]) # Confidence of the highest scoring box
# Draw Red Bounding Boxes
for box in boxes:
# YOLO gives us the exact corner coordinates right out of the box
x1, y1, x2, y2 = map(int, box.xyxy[0])
conf = float(box.conf[0])
cls_id = int(box.cls[0])
class_name = weapon_res[0].names[cls_id]
label = f"{class_name} {conf:.2f}"
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.putText(img, label, (x1, max(y1 - 10, 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# Convert the drawn image back to base64
_, buffer = cv2.imencode('.jpg', img)
processed_b64 = "data:image/jpeg;base64," + base64.b64encode(buffer).decode('utf-8')
except Exception as e:
print(f"❌ CPU Weapon Model Error: {e}")
elif is_human and img is None:
print("❌ ERROR: SpeciesNet saw a human, but OpenCV failed to read the image file.")
return jsonify({
"success": True,
"species": species,
"scientific_name": scientific,
"confidence": float(top_score),
"processed_image": processed_b64
})
else:
return jsonify(success=False, error="Inference failed."), 500
else:
return jsonify(success=False, error="Model not loaded"), 500
except Exception as e:
import traceback
traceback.print_exc()
return jsonify(success=False, error=str(e)), 500
# ==========================================
# 6. WEBSOCKET EVENTS (Real-Time Dashboard)
# ==========================================
@socketio.on('connect')
def handle_connect(auth=None): # Added auth=None to fix the TypeError
"""
Fires the moment a user opens the web dashboard.
Sends the current hardware state immediately so the UI doesn't load empty.
"""
global fleet_state
t = time.time()
print("🟢 Web client connected to real-time dashboard.")
# Loop through all known cameras and send their latest state to the UI
for node_id, node in fleet_state.items():
socketio.emit('sensor_update', {
"node_id": node_id,
**node["status"],
"esp_online": node["esp_online"],
"gunshot": 1 if (t - node["gunshot_timestamp"]) < APP_CONFIG["gunshot_alert_duration"] else 0,
"model_loaded": model_manager.model is not None
})
@socketio.on('disconnect')
def handle_disconnect():
print("🔴 Web client disconnected.")
@app.route('/api/video/upload', methods=['POST'])
def upload_video():
"""Endpoint where the IoT Camera or UI posts videos."""
if 'video' not in request.files: return jsonify(success=False), 400
video_file = request.files['video']
if video_file.filename == '': return jsonify(success=False), 400
country = request.form.get('country', 'IND')
response_mode = request.args.get('mode', 'simple')
# Check if the request came from the UI to disable rotation
source = request.form.get('source', 'amb82')
should_rotate = True if source == 'amb82' else False
full_data = handle_amb82_video(video_file, country=country, rotate_video=should_rotate)
if response_mode == 'simple': return jsonify({"success": True, "status": "Ack", "id": full_data.get('video_id')}), 200
else: return jsonify(full_data), 200
@app.route('/api/history')
def get_history():
"""Endpoint to fetch past detections for the dashboard."""
videos = VideoRecord.query.options(joinedload(VideoRecord.detections)).order_by(VideoRecord.upload_time.desc()).limit(50).all()
output = []
for v in videos:
# Since we did the "Empty Video Purge" during upload,
# any video with 0 detections in the DB can just be skipped
if not v.detections:
continue
# Sort the already-clean detections chronologically
sorted_detections = sorted(v.detections, key=lambda x: x.timestamp_in_video)
# Format the data for the UI
clean_detections = [{
"species": d.species,
"confidence": d.confidence,
"time": d.timestamp_in_video,
"image_url": d.image_url
} for d in sorted_detections]
output.append({
"id": v.id,
"filename": v.filename,
"time": v.upload_time,
"detections": clean_detections
})
return jsonify(output)
@app.route('/api/sensor_history')
def get_sensor_history():
"""Endpoint to fetch past sensor events for the dashboard log."""
try:
# Get the 50 most recent events from the database
events = SensorEvent.query.order_by(SensorEvent.timestamp.desc()).limit(50).all()
output = []
for e in events:
output.append({
"id": e.id,
"type": e.event_type,
"value": e.value,
"timestamp": e.timestamp.isoformat() + "Z" # Format as standard UTC string for JS
})
return jsonify({"success": True, "events": output})
except Exception as e:
return jsonify({"success": False, "error": str(e)})
# Static file servers for videos and images
@app.route('/uploads/videos/<path:filename>')
def serve_video(filename): return send_from_directory(VIDEO_DIR, filename)
@app.route('/static/detections/<path:filename>')
def serve_detections(filename): return send_from_directory(DETECTIONS_DIR, filename)
# command sending for esp
@app.route('/api/command', methods=['POST'])
def send_command():
"""Endpoint for the UI to send commands to the ESP32 via MQTT."""
try:
data = request.get_json(silent=True) or {}
command = data.get('command')
if command:
# Publish to the exact topic the ESP32 is subscribed to
mqtt_client.publish("security/main/command", command)
return jsonify({"success": True, "message": f"Sent {command} to ESP32"})
return jsonify({"success": False, "error": "No command provided"}), 400
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
#setting cahnge from ui
@app.route('/api/settings', methods=['GET'])
def get_settings():
"""Returns the current dynamic settings to the frontend."""
return jsonify({"success": True, "settings": APP_CONFIG})
@app.route('/api/settings', methods=['POST'])
def update_settings():
"""Allows the frontend to update the dynamic settings and node locations."""
try:
data = request.get_json(silent=True) or {}
if not data:
return jsonify({"success": False, "error": "No data provided"}), 400
# 🚀 PERFORMANCE OPTIMIZATION: Collect all location updates for bulk processing
location_updates = {}
# Loop through incoming data and update the config if the key exists
for key, value in data.items():
if key in APP_CONFIG:
# Ensure we maintain the correct data type (float, int, bool, or str)
if isinstance(APP_CONFIG[key], bool):
APP_CONFIG[key] = bool(value)
elif isinstance(APP_CONFIG[key], float):
APP_CONFIG[key] = float(value)
elif isinstance(APP_CONFIG[key], int):
APP_CONFIG[key] = int(value)
elif isinstance(APP_CONFIG[key], str):
APP_CONFIG[key] = str(value).strip()
# Collect location updates
if key.startswith("location_"):
node_id = key.replace("location_", "")
location_updates[node_id] = str(value).strip()
# Perform bulk database operations for locations
if location_updates:
# 1. Bulk query all existing configs in one go
existing_configs = NodeConfig.query.filter(NodeConfig.node_id.in_(location_updates.keys())).all()
config_map = {c.node_id: c for c in existing_configs}
for node_id, new_location in location_updates.items():
if node_id in config_map:
config_map[node_id].location = new_location
else:
new_config = NodeConfig(node_id=node_id, location=new_location)
db.session.add(new_config)
# 2. Update Active Memory for instant WebSocket broadcast
if node_id in fleet_state:
fleet_state[node_id]["location"] = new_location
# 3. Commit everything at once (Significant performance boost for SQLite)
db.session.commit()
print(f"📍 Bulk Database Update: {len(location_updates)} locations saved.")
print(f"⚙️ Settings updated via API: {APP_CONFIG}")
return jsonify({"success": True, "settings": APP_CONFIG})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
# --- ESP32 WATCHDOG MONITOR ---
def watchdog_monitor():
"""Continuously checks if any ESP32 timed out and forces the UI offline if it did."""
global fleet_state
while True:
time.sleep(5) # Wake up and check every 5 seconds
current_time = time.time()
# Check every camera in our memory
for node_id, node in list(fleet_state.items()):
is_online = (current_time - node["last_seen"]) < APP_CONFIG["esp_timeout"] and node["last_seen"] != 0
# If the state changed (it just went offline, or just came back online)
if is_online != node["esp_online"]:
node["esp_online"] = is_online
print(f"📡 Watchdog: {node_id.upper()} is now {'ONLINE' if is_online else 'OFFLINE'}")
try:
with app.app_context():
socketio.emit('sensor_update', {
"node_id": node_id,
"location": node["location"],
**node["status"],
"esp_online": is_online,