Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
392 lines (336 loc) · 14.6 KB
/
Copy pathserver.py
File metadata and controls
392 lines (336 loc) · 14.6 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
# Import necessary modules
from flask import Flask, render_template, Response, request, jsonify, session, redirect, url_for, stream_with_context , flash
from ultralytics import YOLO
from ultralytics.utils.plotting import Annotator, colors
import pandas as pd
import cv2
import json
import asyncio
import logging
import time
import threading
from threading import Thread
import requests
import os
import uuid
from aiortc import RTCPeerConnection, RTCSessionDescription
from shapely.geometry import Point, Polygon, LineString
from utils.login_utils import *
customer_color = (0, 140, 255) # in BGR
worker_color = (171, 71, 0) # in BGR
unknown_color = (0, 224, 252) # in BGR
# Create a Flask app instance
app = Flask(__name__, static_url_path='/static')
# app.secret_key = 'BAD_SECRET_KEY'
app.secret_key = os.urandom(24)
pcs = set()
# Initialize global variables
ipCam = "D2.mp4" # Set default to local video file path
token = ""
region_points = []
# CSV_FILE_PATH = 'form_data.csv'
def is_box_partially_in_region(box_points, region_points):
region_polygon = Polygon(region_points)
box_polygon = Polygon(box_points)
for point in box_points:
if region_polygon.contains(Point(point)):
return True
for point in region_points:
if box_polygon.contains(Point(point)):
return True
for i in range(len(box_points)):
box_edge = LineString(
[box_points[i], box_points[(i + 1) % len(box_points)]])
for j in range(len(region_points)):
region_edge = LineString(
[region_points[j], region_points[(j + 1) % len(region_points)]])
if box_edge.intersects(region_edge):
return True
return False
# Route to render the HTML template
@app.route('/')
def index():
if 'username' in session:
connection = connect_V89DB()
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM camera_config")
camera_configs = cursor.fetchall()
disconnect(connection)
return render_template('index.html', camera_configs=camera_configs)
else:
return redirect(url_for('login_page'))
@app.route('/login_page', methods=['GET', 'POST'])
def login_page():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
connection = connect_V89DB()
if validate_login(connection, username, password):
session['username'] = username # Store username in session
flash('Login successful!', 'success')
disconnect(connection)
return redirect(url_for('index'))
else:
flash('Invalid username or password', 'danger')
disconnect(connection)
return redirect(url_for('login_page'))
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
connection = connect_V89DB()
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM camera_config")
camera_configs = cursor.fetchall()
disconnect(connection)
return render_template('dashboard.html', camera_configs=camera_configs)
@app.route('/logout' , methods=['POST'])
def logout():
session.pop('username', None) # Remove user from session
flash('You have been logged out.', 'success')
return redirect(url_for('login_page'))
@app.route('/link_camera', methods=['POST'])
def link_camera():
if request.method == 'POST':
session['ipCam'] = request.form.get('ipCam')
connection = connect_V89DB()
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM camera_config")
camera_configs = cursor.fetchall()
disconnect(connection)
return render_template('index.html', camera_configs=camera_configs)
# return render_template('index.html')
@app.route('/get_input', methods=['POST'])
def get_input():
if request.method == 'POST':
form_data = request.form.to_dict()
ipCam_form = {'ipCam': session.get('ipCam')}
combined_data = {**ipCam_form, **form_data}
connection = connect_V89DB()
cursor = connection.cursor()
cursor.execute("SELECT * FROM camera_config")
camera_configs = cursor.fetchall()
id = 1
if len(camera_configs) != 0:
id = len(camera_configs) + 1
disconnect(connection)
insert_query = """
INSERT INTO camera_config
(id, ipCam, cameraName, lineToken, startTime, endTime, x1, y1, x2, y2, x3, y3, x4, y4)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
connection = connect_V89DB()
cursor = connection.cursor()
cursor.execute(insert_query, (
id,
combined_data['ipCam'],
combined_data['cameraName'],
combined_data['lineToken'],
combined_data['startTime'],
combined_data['endTime'],
float(combined_data['x1']),
float(combined_data['y1']),
float(combined_data['x2']),
float(combined_data['y2']),
float(combined_data['x3']),
float(combined_data['y3']),
float(combined_data['x4']),
float(combined_data['y4'])
))
connection.commit()
disconnect(connection)
# Update session variables
for key, value in combined_data.items():
session[key] = value
return redirect(url_for('index'))
@app.route('/manage_db', methods=['POST'])
def manage_db():
if request.method == 'POST':
connection = connect_V89DB()
cursor = connection.cursor()
ind_dop = request.form.get('index_drop')
if ind_dop.isnumeric():
if (request.form.get('edit_db') != None) and (request.form.get('del_db') == None):
update_query = """
UPDATE camera_config SET
ipCam = %s, cameraName = %s, lineToken = %s, startTime = %s, endTime = %s,
x1 = %s, y1 = %s, x2 = %s, y2 = %s, x3 = %s, y3 = %s, x4 = %s, y4 = %s
WHERE id = %s
"""
cursor.execute(update_query, (
request.form.get('manage_ipCam'),
request.form.get('manage_cameraName'),
request.form.get('manage_lineToken'),
request.form.get('manage_startTime'),
request.form.get('manage_endTime'),
float(request.form.get('manage_x1')),
float(request.form.get('manage_y1')),
float(request.form.get('manage_x2')),
float(request.form.get('manage_y2')),
float(request.form.get('manage_x3')),
float(request.form.get('manage_y3')),
float(request.form.get('manage_x4')),
float(request.form.get('manage_y4')),
int(ind_dop)
))
elif (request.form.get('edit_db') == None) and (request.form.get('del_db') != None):
delete_query = "DELETE FROM camera_config WHERE id = %s"
cursor.execute(delete_query, (int(ind_dop),))
connection.commit()
disconnect(connection)
return redirect(url_for('index'))
API_URI = "https://notify-api.line.me/api/notify"
# Function to send line notify
def send_line_notify(cust_id_lineNoti, frame, headers):
cv2.imwrite("toLineNoti.png", frame)
for c in range(len(cust_id_lineNoti)):
msg = '\ncustomer id = {}'.format(cust_id_lineNoti[c])
if c == len(cust_id_lineNoti) - 1:
requests.post(API_URI, headers=headers, data={'message': msg}, files={
"imageFile": open('toLineNoti.png', "rb")})
else:
requests.post(API_URI, headers=headers, data={'message': msg})
# Function to generate video frames from the camera
def generate_frames(ipCam, lineToken, region_points, startTime, endTime, stop_event):
model = YOLO("segment_V89_small_openvino_model/", task="segment")
track_history = {}
history_label = set({})
max_track_id = -1
worker_unique = 1
customer_unique = 1
unknown_unique = 1
headers = {'Authorization': 'Bearer ' + lineToken}
camera = cv2.VideoCapture(ipCam if ipCam else r"D2.mp4")
while not stop_event.is_set():
start_time = time.time()
success, frame = camera.read()
cust_id_lineNoti = []
if not success:
break
else:
annotator = Annotator(frame, line_width=2)
results = model.track(
frame, conf=0.15, iou=0.3, persist=True, verbose=False, tracker='botsort.yaml')
if results[0].boxes.id is not None and results[0].masks is not None:
masks = results[0].masks.xy
track_ids = results[0].boxes.id.int().cpu().tolist()
boxes = results[0].boxes.xyxy
for mask, track_id, box in zip(masks, track_ids, boxes):
box_points = [(box[0], box[1]), (box[0], box[3]),
(box[2], box[1]), (box[2], box[3])]
box_result = is_box_partially_in_region(
box_points, region_points)
if track_id not in history_label:
if box_result:
history = {
"label": "worker", "id": worker_unique, "first_time": time.time()}
worker_unique += 1
else:
history = {
"label": "unknown", "id": unknown_unique, "first_time": time.time()}
unknown_unique += 1
history_label.add(track_id)
track_history[track_id] = history
if track_id in history_label and track_history[track_id]["label"] == "unknown":
if time.time() - track_history[track_id]["first_time"] >= 10:
if box_result:
history = {
"label": "worker", "id": worker_unique, "first_time": time.time()}
worker_unique += 1
else:
history = {
"label": "customer", "id": customer_unique, "first_time": time.time()}
cust_id_lineNoti.append(customer_unique)
customer_unique += 1
track_history[track_id] = history
if track_history[track_id]['label'] == 'worker':
color = worker_color
elif track_history[track_id]['label'] == 'unknown':
color = unknown_color
else:
color = customer_color
annotator.box_label(box=(
box[0], box[1], box[2], box[3]), label=f"{track_history[track_id]['label']} {track_history[track_id]['id']}", color=color)
if len(region_points) >= 4:
annotator.draw_region(region_points)
if len(cust_id_lineNoti) != 0:
Thread(target=send_line_notify, args=(
cust_id_lineNoti, frame, headers,)).start()
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
async def offer_async():
params = await request.json
offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
pc_id = "PeerConnection(%s)" % uuid.uuid4()
pc_id = pc_id[:8]
await pc.createOffer(offer)
await pc.setLocalDescription(offer)
response_data = {"sdp": pc.localDescription.sdp,
"type": pc.localDescription.type}
return jsonify(response_data)
def offer():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.run_coroutine_threadsafe(offer_async(), loop)
return future.result()
@app.route('/offer', methods=['POST'])
def offer_route():
return offer()
@app.route('/video_feed/')
def video_feed():
# if index != -1:
# Retrieve session variables or use defaults
ipCam = session.get('ipCam', '')
lineToken = session.get('lineToken', '')
x1 = session.get('x1', 1)
y1 = session.get('y1', 1)
x2 = session.get('x2', 1)
y2 = session.get('y2', 1)
x3 = session.get('x3', 1)
y3 = session.get('y3', 1)
x4 = session.get('x4', 1)
y4 = session.get('y4', 1)
startTime = session.get('startTime', '')
endTime = session.get('endTime', '')
zone_points = [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
# Create a stop event for the thread
stop_event = threading.Event()
# Create a new thread for generating frames
thread = threading.Thread(target=generate_frames,
args=(ipCam, lineToken, zone_points, startTime, endTime, stop_event))
thread.start()
# Start generating frames from the camera
return Response(stream_with_context(generate_frames(ipCam, lineToken, zone_points, startTime, endTime , stop_event)),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_list/<int:index>')
def video_list(index):
connection = connect_V89DB()
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM camera_config WHERE id = %s", (index,))
config = cursor.fetchone()
disconnect(connection)
if len(config) != 0:
ipCam = config['ipCam']
lineToken = config['lineToken']
x1, y1 = config['x1'], config['y1']
x2, y2 = config['x2'], config['y2']
x3, y3 = config['x3'], config['y3']
x4, y4 = config['x4'], config['y4']
startTime = config['startTime']
endTime = config['endTime']
zone_points = [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
# Create a stop event for the thread
stop_event = threading.Event()
# Create a new thread for generating frames
thread = threading.Thread(target=generate_frames,
args=(ipCam, lineToken, zone_points, startTime, endTime, stop_event))
thread.start()
# Start generating frames from the camera
return Response(stream_with_context(generate_frames(ipCam, lineToken, zone_points, startTime, endTime, stop_event)),
mimetype='multipart/x-mixed-replace; boundary=frame')
else:
return "Configuration not found", 404
if __name__ == '__main__':
app.run(debug=True , threaded = True)