-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
276 lines (208 loc) · 9.61 KB
/
Copy pathapp.py
File metadata and controls
276 lines (208 loc) · 9.61 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
#!/usr/bin/env python3
"""
SecureX Web v2.0 — Main Server
Flask + SocketIO + YOLOv8 multi-camera security dashboard.
"""
import os, sys, time, threading, json
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from flask import Flask, render_template, request, redirect, url_for, session, Response, jsonify
from flask_socketio import SocketIO, emit
from utils.config_loader import load_config
from utils.user_db import UserDB
from utils.event_logger import EventLogger
from core.camera_manager import CameraManager
from core.detection_engine import DetectionEngine
from alerts.telegram_alerter import TelegramAlerter
# ── Init ──────────────────────────────────────────────
config = load_config()
app = Flask(__name__)
app.secret_key = config["server"]["secret_key"]
socketio = SocketIO(app, async_mode="eventlet", cors_allowed_origins="*")
db = UserDB()
logger = EventLogger()
cam_mgr = CameraManager()
alerter = TelegramAlerter(config)
print(" Loading YOLOv8...")
detector = DetectionEngine(config)
print(" [OK] All systems ready.\n")
# ── Detection Loop (background thread) ───────────────
detection_running = False
def detection_loop():
global detection_running
detection_running = True
while detection_running:
for stream in cam_mgr.get_all():
if not stream.alive:
continue
frame = stream.read()
if frame is None:
continue
ann, dets, alerts = detector.process(
frame, stream.name, stream.zone, stream.user_email
)
stream.set_annotated(ann)
stream.detection_count = len(dets)
for alert in alerts:
print(f" 🔴 {alert.reason} — {alert.camera_name}")
logger.log_alert(alert.camera_name, alert.zone, alert.reason,
alert.detections, alert.user_email)
# Send telegram to the camera owner
chat_id = db.get_chat_id_for_user(alert.user_email)
if chat_id:
alerter.send_alert(chat_id, alert.camera_name, alert.zone,
alert.reason, alert.frame, alert.detections)
# Push to web dashboard via socketio
socketio.emit("alert", alert.to_dict(), namespace="/live")
time.sleep(0.02)
# ── Auth Routes ───────────────────────────────────────
@app.route("/")
def index():
if "user_email" in session:
return redirect(url_for("dashboard"))
return render_template("index.html")
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
email = request.form.get("email", "").strip().lower()
telegram = request.form.get("telegram", "").strip()
if not email or "@" not in email:
return render_template("signup.html", error="Enter a valid email.")
if db.user_exists(email):
return render_template("signup.html", error="Email already registered. Log in instead.")
user = db.create_user(email, telegram)
# Try to resolve their telegram chat_id
if telegram:
chat_id = alerter.resolve_chat_id(telegram)
if chat_id:
db.set_telegram(email, telegram, chat_id)
session["user_email"] = email
return redirect(url_for("dashboard"))
return render_template("signup.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email", "").strip().lower()
if not email:
return render_template("login.html", error="Enter your email.")
user = db.get_user(email)
if not user:
return render_template("login.html", error="No account found. Sign up first.")
session["user_email"] = email
return redirect(url_for("dashboard"))
return render_template("login.html")
@app.route("/logout")
def logout():
session.pop("user_email", None)
return redirect(url_for("index"))
# ── Dashboard ─────────────────────────────────────────
@app.route("/dashboard")
def dashboard():
if "user_email" not in session:
return redirect(url_for("login"))
email = session["user_email"]
user = db.get_user(email)
cameras = cam_mgr.get_status(email)
alerts = logger.get_recent(20)
return render_template("dashboard.html", user=user, cameras=cameras, alerts=alerts)
# ── Camera API ────────────────────────────────────────
@app.route("/api/cameras", methods=["GET"])
def api_cameras():
if "user_email" not in session:
return jsonify({"error": "Not logged in"}), 401
return jsonify(cam_mgr.get_status(session["user_email"]))
@app.route("/api/cameras/add", methods=["POST"])
def api_add_camera():
if "user_email" not in session:
return jsonify({"error": "Not logged in"}), 401
email = session["user_email"]
data = request.json or request.form
name = data.get("name", "My Camera")
source = data.get("source", "0")
zone = data.get("zone", "default")
result = cam_mgr.add_camera(name, source, zone, email)
if result["alive"]:
db.add_camera(email, {"name": name, "source": str(source), "zone": zone, "cam_id": result["cam_id"]})
logger.log_system(f"Camera added: {name}", email)
return jsonify(result)
@app.route("/api/cameras/remove", methods=["POST"])
def api_remove_camera():
if "user_email" not in session:
return jsonify({"error": "Not logged in"}), 401
data = request.json or request.form
cam_id = data.get("cam_id")
if cam_mgr.remove_camera(cam_id):
db.remove_camera(session["user_email"], cam_id)
return jsonify({"ok": True})
return jsonify({"error": "Camera not found"}), 404
# ── Video Stream (MJPEG) ─────────────────────────────
@app.route("/video/<cam_id>")
def video_feed(cam_id):
"""MJPEG stream endpoint for a single camera."""
def generate():
while True:
stream = cam_mgr.get_stream(cam_id)
if stream is None:
break
jpeg = stream.get_jpeg(quality=65)
if jpeg:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + jpeg + b'\r\n')
time.sleep(0.05) # ~20fps
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
# ── Telegram Setup ────────────────────────────────────
@app.route("/api/telegram/setup", methods=["POST"])
def api_telegram_setup():
"""User provides telegram username, we try to resolve their chat_id."""
if "user_email" not in session:
return jsonify({"error": "Not logged in"}), 401
data = request.json or request.form
username = data.get("telegram_username", "").strip()
if not username:
return jsonify({"error": "Provide a telegram username"}), 400
email = session["user_email"]
db.set_telegram(email, username)
# Try resolving chat_id
chat_id = alerter.resolve_chat_id(username)
if chat_id:
db.set_telegram(email, username, chat_id)
return jsonify({"ok": True, "chat_id": chat_id,
"message": "Connected! You'll receive alerts on Telegram."})
else:
return jsonify({"ok": False,
"message": f"Couldn't find your chat. Send any message to the bot first, then try again."})
@app.route("/api/alerts", methods=["GET"])
def api_alerts():
if "user_email" not in session:
return jsonify({"error": "Not logged in"}), 401
return jsonify(logger.get_recent(30))
# ── SocketIO Events ───────────────────────────────────
@socketio.on("connect", namespace="/live")
def on_connect():
print(f" [WS] Client connected")
@socketio.on("request_frames", namespace="/live")
def on_request_frames():
"""Client requests current frames for their cameras."""
email = session.get("user_email", "")
streams = cam_mgr.get_user_streams(email)
frames = {}
for s in streams:
b64 = s.get_base64(quality=50)
if b64:
frames[s.cam_id] = {"image": b64, "name": s.name,
"fps": round(s.fps, 1), "dets": s.detection_count}
emit("frames", frames)
# ── Startup ───────────────────────────────────────────
def start_detection_thread():
t = threading.Thread(target=detection_loop, daemon=True, name="detector")
t.start()
print(" [OK] Detection loop started")
if __name__ == "__main__":
print("\n ╔═══════════════════════════════════╗")
print(" ║ SecureX Web v2.0 ║")
print(" ╚═══════════════════════════════════╝\n")
start_detection_thread()
logger.log_system("Server started")
host = config["server"]["host"]
port = config["server"]["port"]
print(f" 🌐 Dashboard: http://localhost:{port}\n")
socketio.run(app, host=host, port=port, debug=False, use_reloader=False)