-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
1449 lines (1238 loc) · 69.4 KB
/
main.py
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
# Author: Van-Thong Huynh
# Dept. of AIC, Chonnam National University
# Last modified: Nov 2021
import datetime
import time
from collections import deque
import os, sys, threading, typing
import pandas as pd
import validators
from dash.exceptions import PreventUpdate
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Dash components
import cv2
import insightface.model_zoo
import numpy as np
from dash import Dash, dcc, html, callback_context, dash_table
from dash.dependencies import Input, Output, State
from flask import Response, stream_with_context
import dash_bootstrap_components as dbc
import diskcache
from dash.long_callback import DiskcacheLongCallbackManager
from PyQt6 import QtCore, QtWidgets, QtWebEngineWidgets
from PyQt6.QtGui import QIcon
from PyQt6.QtWebEngineCore import QWebEngineDownloadRequest
# Python Requests with REST APIs, download files
import base64
import requests
from pandas import DataFrame
import insightface
import tensorflow as tf
from tensorflow.keras.models import load_model
import glob2
from tqdm import tqdm
from sklearn.preprocessing import normalize
from skimage.io import imread
from skimage import transform
from multiprocessing import Process, Pipe
import onnxruntime as ort
print('ONNX devices: ', ort.get_device())
# Zoom API Information
zoom_client_ID = os.getenv('ZOOM_CLIENT_ID')
zoom_client_secret = os.getenv('ZOOM_CLIENT_SECRET')
zoom_oauth_redirect_uri = os.getenv('ZOOM_REDIRECT_URI')
zoom_userID = 'me'
print(zoom_client_ID, zoom_client_secret, zoom_oauth_redirect_uri)
MAX_SIZE_QUEUE = None
class VideoCamera(QtCore.QObject):
# Based on https://community.plotly.com/t/does-dash-support-opencv-video-from-webcam/11012/2
def __init__(self, parent=None):
super(VideoCamera, self).__init__(parent)
self.video = None
self.running = False
self.capture_save = ''
def __del__(self):
self.running = False
self.video.release()
@QtCore.pyqtSlot(str)
def capture_current_img(self, img_id):
# print('Receive signal capture ', img_id)
self.capture_save = img_id
@QtCore.pyqtSlot(bool)
def trigger_camera(self, run_camera):
if run_camera:
print('Turn on camera')
self.running = True
else:
print('Turn off camera')
self.running = False
def get_frame(self):
if not self.running:
if self.video is not None:
self.video.release()
self.video = None
image = np.zeros((480,640,3), dtype=np.uint8)
else:
if self.video is None:
self.video = cv2.VideoCapture(0)
success, image = self.video.read()
if self.capture_save != '':
# Save image
save_path = './assets/students/{}/{}.jpg'.format(self.capture_save,
datetime.datetime.now().strftime("%m-%d-%Y_%H-%M-%S"))
# print(self.capture_save, save_path)
cv2.imwrite(save_path, image)
self.capture_save = ''
# try:
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
# except:
# save_path = './assets/students/{}/{}.jpg'.format(self.capture_save,
# datetime.datetime.now().strftime("%m-%d-%Y_%H-%M-%S"))
# print(self.capture_save, save_path, success)
# cv2.imwrite(save_path, image)
# return None
def gen_camera(camera):
while True:
frame = camera.get_frame()
if frame is None:
continue
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
class VideoCaptureThread:
def __init__(self, src='0', threaded=True):
self.threaded = threaded
def init_camera(self, src='0'):
if src == '0':
src = int(src)
self.cap = cv2.VideoCapture(src)
self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
self.stopped = False
self.frame_queue = deque(maxlen=MAX_SIZE_QUEUE)
def start(self):
threading.Thread(target=self.get_frame, args=()).start()
def get_frame(self):
while True:
try:
if not self.stopped:
cont, frame = self.cap.read()
if cont:
self.frame_queue.append(frame)
else:
print('Stop capture')
self.stop()
break
else:
print('Stop capture')
break
except:
break
self.cap.release()
self.cap = None
def stop(self):
self.stopped = True
class VideoWriterThread:
def __init__(self, src, codec, fps=30, size=(640, 480)):
self.capW = cv2.VideoWriter(src, codec, fps, size)
self.stopped = False
self.frame_queue = deque(maxlen=MAX_SIZE_QUEUE)
self.student_queue = []
self.thread = threading.Thread(target=self.write_frame, args=())
self.count_num = 0
@staticmethod
def draw_polyboxes(frame, rec_dist, rec_class, bbs, ccs, dist_thresh):
cur_students = []
for dist, label, bb, cc in zip(rec_dist, rec_class, bbs, ccs):
# Red color for unknown, green for Recognized
color = (0, 0, 255) if dist < dist_thresh else (0, 255, 0)
label = "Unknown" if dist < dist_thresh else label
left, up, right, down = bb
cv2.line(frame, (left, up), (right, up), color, 3, cv2.LINE_AA)
cv2.line(frame, (right, up), (right, down), color, 3, cv2.LINE_AA)
cv2.line(frame, (right, down), (left, down), color, 3, cv2.LINE_AA)
cv2.line(frame, (left, down), (left, up), color, 3, cv2.LINE_AA)
xx, yy = np.max([bb[0] - 10, 10]), np.max([bb[1] - 10, 10])
# cv2.putText(frame, "Name: {}, dist: {:.4f}".format(label, dist), (xx, yy), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
# color, 2)
cv2.putText(frame, "{}".format(label), (xx, yy), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2)
cur_students.append(label)
return frame, np.unique(cur_students)
def write_frame(self):
while True:
while True:
try:
st_wr = time.time()
frame, rec_dist, rec_class, bbs, ccs, dist_thresh = self.frame_queue.popleft()
_, cur_students = self.draw_polyboxes(frame, rec_dist, rec_class, bbs, ccs, dist_thresh)
self.capW.write(frame)
# print('Time in write: ', time.time() - st_wr)
self.student_queue.append(cur_students)
self.count_num += 1
# if self.count_num % 300 == 0:
# print('Current write index ', self.count_num, time.time() - st_wr)
except:
if len(self.frame_queue) == 0 and self.stopped:
self.stop()
break
if len(self.frame_queue) == 0 and self.stopped:
self.stop()
break
def start(self):
self.thread.start()
def stop(self):
self.stopped = True
self.capW.release()
class FaceAnalysis(QtCore.QObject):
# Face recognition model code are adapted from
# https://github.com/leondgarse/Keras_insightface/blob/master/video_test.py
finished = QtCore.pyqtSignal(str)
trigger_video_process_signal = QtCore.pyqtSignal(str, int, float)
def __init__(self, parent=None):
super(FaceAnalysis, self).__init__(parent)
self.init_gpu = False
self.det = None
self.face_reg = None
self.embeddings = None
self.image_classes = None
self.video_src = None
self.second_per_detect = None
self.dist_thresh = None
self.do_video_analysis = False
self.shared_data_parent, self.shared_data_child = Pipe()
self.is_running_parent, self.is_running_child = Pipe()
self.stop_running_parent, self.stop_running_child = Pipe()
self.trigger_init_embedding_parent, self.trigger_init_embedding_child = Pipe()
self.shared_data_result_parent, self.shared_data_result_child = Pipe()
self.trigger_stop_running_parent, self.trigger_stop_running_child = Pipe()
self.is_running = False
def gen_frame_webcam(self):
prev_frame = np.zeros((480,640,3), dtype=np.uint8)
while True:
if not self.shared_data_result_parent.poll(0.0002):
frame_ret = prev_frame
else:
frame_ret = self.shared_data_result_parent.recv()
prev_frame = frame_ret
ret, jpeg = cv2.imencode('.jpg', frame_ret)
jpeg_send = jpeg.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + jpeg_send + b'\r\n\r\n')
def init_face_engine(self):
if not self.init_gpu:
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
# Currently, memory growth needs to be the same across GPUs
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
logical_gpus = tf.config.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Memory growth must be set before GPUs have been initialized
print('Using CPU')
print(e)
else:
print('Using CPU')
self.init_gpu = True
if self.det is None:
print('Re-initialize')
self.det = insightface.model_zoo.SCRFD('./assets/face_analysis/face_reg/scrfd_10g_bnkps.onnx',
providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
self.det.prepare(0)
if self.face_reg is None:
self.face_reg = load_model('./assets/face_analysis/face_reg/mobilenet_emb256.h5', compile=False)
@QtCore.pyqtSlot()
def re_init_face_embedding(self):
self.trigger_init_embedding_parent.send('True')
@QtCore.pyqtSlot()
def stop_running(self):
self.trigger_stop_running_parent.send('True')
def start_video_analysis(self, vd_src, second_per_detect=5, dist_thresh=0.6, in_minutes=0, cls_name_students=()):
print('Receive signals: ', vd_src, second_per_detect, dist_thresh)
if self.is_running:
raise ValueError('Current analysis is in progress')
else:
self.shared_data_parent.send([vd_src, second_per_detect, dist_thresh, in_minutes, cls_name_students])
print('Send signals to child process')
self.is_running = True
while not self.stop_running_parent.poll(0.1):
continue
attendance_df = self.stop_running_parent.recv()
self.is_running = False
# print('**** Recieved finish signal. Finished running. ', attendance_df)
self.stop_running_parent.send('OK')
return attendance_df
def init_embedding_images(self, re_run=False):
emb_path = './assets/students/students_emb.npz'
batch_size = 32
if os.path.isfile(emb_path) and not re_run:
npz = np.load(emb_path)
self.image_classes, self.embeddings = npz['image_classes'], npz['embeddings']
else:
image_names = sorted(glob2.glob(os.path.join("./assets/students/*/*.jpg")) + glob2.glob(
os.path.join("./assets/students/*/*.png")) + glob2.glob(os.path.join("./assets/students/*/*.jpeg")))
""" Detect faces in images, keep only those have exactly one face. """
nimgs, image_classes = [], []
for image_name in tqdm(image_names, "Detect"):
img = imread(image_name)
nimg = self.do_detect_in_image(img, image_format="RGB")[-1]
if nimg.shape[0] > 0:
nimgs.append(nimg[0])
image_classes.append(os.path.basename(os.path.dirname(image_name)))
""" Extract embedding info from aligned face images """
steps = int(np.ceil(len(image_classes) / batch_size))
nimgs = (np.array(nimgs) - 127.5) * 0.0078125
embeddings = [self.face_reg(nimgs[ii * batch_size: (ii + 1) * batch_size]) for ii in
tqdm(range(steps), "Embedding")]
self.embeddings = normalize(np.concatenate(embeddings, axis=0))
self.image_classes = np.array(image_classes)
np.savez_compressed(emb_path, embeddings=self.embeddings, image_classes=self.image_classes)
print(">>>> image_classes info:")
print(pd.value_counts(self.image_classes))
def do_detect_in_image(self, image, image_format="BGR"):
imm_BGR = image if image_format == "BGR" else image[:, :, ::-1]
imm_RGB = image[:, :, ::-1] if image_format == "BGR" else image
bboxes, pps = self.det.detect(imm_BGR, (640, 640))
nimgs = self.face_align_landmarks_sk(imm_RGB, pps)
bbs, ccs = bboxes[:, :4].astype("int"), bboxes[:, -1]
return bbs, ccs, nimgs
def face_align_landmarks_sk(self, img, landmarks, image_size=(112, 112), method="similar"):
tform = transform.AffineTransform() if method == "affine" else transform.SimilarityTransform()
src = np.array(
[[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.729904, 92.2041]],
dtype=np.float32)
ret = []
for landmark in landmarks:
# landmark = np.array(landmark).reshape(2, 5)[::-1].T
tform.estimate(landmark, src)
ret.append(transform.warp(img, tform.inverse, output_shape=image_size))
return (np.array(ret) * 255).astype(np.uint8)
def image_recognize(self, frame, image_format='BGR'):
bbs, ccs, nimgs = self.do_detect_in_image(frame, image_format=image_format)
if len(bbs) == 0:
return [], [], [], []
emb_unk = self.face_reg((nimgs - 127.5) * 0.0078125).numpy()
emb_unk = normalize(emb_unk)
dists = np.dot(self.embeddings, emb_unk.T).T
rec_idx = dists.argmax(-1)
rec_dist = [dists[id, ii] for id, ii in enumerate(rec_idx)]
rec_class = [self.image_classes[ii] for ii in rec_idx]
return rec_dist, rec_class, bbs, ccs
def video_recognize(self, video_src='0', second_per_detect=5, dist_thresh=0.6):
st_vr = time.time()
if isinstance(video_src, tuple):
write_video_src = video_src[1]
video_src = int(video_src[0])
pfx_replace = '.mp4'
else:
write_video_src = video_src.replace('.mp4', '_result.mp4')
pfx_replace = '_result.mp4'
cap_thread = VideoCaptureThread(video_src)
cap_thread.init_camera(video_src)
width = cap_thread.width
height = cap_thread.height
cap_result_thread = VideoWriterThread(write_video_src, cv2.VideoWriter_fourcc(*'mp4v'), 25, (width, height))
cur_frame_idx = 0
cap_thread.start()
# cap_result_thread.start()
print('Video src: ', video_src, cap_thread.cap.isOpened())
frames_per_detect = int(second_per_detect * cap_thread.fps) # cap_thread.fps
print('Frame per detect: ', frames_per_detect, cap_thread.fps)
while True:
if isinstance(video_src, int) and self.trigger_stop_running_child.poll(0.0001):
cap_thread.stop()
self.trigger_stop_running_child.recv()
break
try:
frame = cap_thread.frame_queue.popleft()
if cur_frame_idx % frames_per_detect == 0:
# st_deep = time.time()
rec_dist, rec_class, bbs, ccs = self.image_recognize(frame)
# print('Time in deep: ', time.time() - st_deep)
_, cur_students = cap_result_thread.draw_polyboxes(frame, rec_dist, rec_class, bbs, ccs, dist_thresh)
cap_result_thread.student_queue.append(cur_students)
if isinstance(video_src, int):
self.shared_data_result_child.send(frame)
# print('Sent frame')
cap_result_thread.capW.write(frame)
cur_frame_idx += 1
except:
if len(cap_thread.frame_queue) == 0 and cap_thread.stopped:
break
cap_result_thread.stop()
cap_result_thread.capW.release()
ffmpeg_cmd = "ffmpeg -y -i {} -vcodec libx264 {}".format(write_video_src,
write_video_src.replace(pfx_replace, '_analyzed.mp4'))
os.system(ffmpeg_cmd)
os.system("rm {}".format(write_video_src))
cv2.destroyAllWindows()
print('Time in while: ', time.time() - st_vr)
use_index = np.arange(0, cur_frame_idx, frames_per_detect)
student_attendance = np.array(cap_result_thread.student_queue, dtype=object)[use_index]
return list(student_attendance), use_index // cap_thread.fps
def start(self):
p = Process(target=self.run, args=(), daemon=True)
p.start()
def run(self):
print('Running face analysis engine')
while True:
self.init_face_engine()
if self.embeddings is None and self.image_classes is None:
self.init_embedding_images(re_run=False)
if self.trigger_init_embedding_child.poll(0.0002):
# Re-init embedding
tmp = self.trigger_init_embedding_child.recv()
self.init_embedding_images(re_run=True)
if not self.shared_data_child.poll(0.0002):
continue
video_src, second_per_detect, dist_thresh, in_minutes, students_list = self.shared_data_child.recv()
print('Receive data: ', video_src, second_per_detect, dist_thresh, in_minutes)
self.do_video_analysis = False
st = time.time()
results, use_index = self.video_recognize(video_src, second_per_detect, dist_thresh)
print('Total time: ', time.time() - st)
if in_minutes:
post = '(sec)'
else:
post = '(min)'
attendance_df = {'Timestamp {}'.format(post): use_index // (in_minutes * 59 + 1)}
attendance_df.update({x: np.zeros(len(results), dtype=int) for x in students_list})
for timestamp in range(len(results)):
cur_students = results[timestamp]
for stu in cur_students:
if stu in students_list:
attendance_df[stu][timestamp] = 1
attendance_df = DataFrame.from_dict(attendance_df)
self.stop_running_child.send(attendance_df)
# print('Send results signal to parent')
class QDash(QtCore.QObject):
zoom_auth_signal = QtCore.pyqtSignal()
zoom_off_signal = QtCore.pyqtSignal()
zoom_uuid_analyze_signal = QtCore.pyqtSignal(list)
zoom_process_video_signal = QtCore.pyqtSignal(str, int, float)
capture_webcam_signal = QtCore.pyqtSignal(str)
trigger_webcam_signal = QtCore.pyqtSignal(bool)
trigger_re_init_embedding_signal = QtCore.pyqtSignal()
zoom_stop_analyze_signal = QtCore.pyqtSignal()
def __init__(self, parent: typing.Optional['QObject'] = None) -> None:
super(QDash, self).__init__(parent=parent)
cache = diskcache.Cache("./cache")
long_callback_manager = DiskcacheLongCallbackManager(cache)
self.__app = Dash(suppress_callback_exceptions=True, assets_folder='assets',
external_stylesheets=[dbc.themes.BOOTSTRAP],
title='PRLAB - Facial Analysis',
long_callback_manager=long_callback_manager)
self.oauth_code = ''
self.access_token = ''
self.face_engine = FaceAnalysis()
self.zoom_process_video_signal.connect(self.face_engine.start_video_analysis)
self.trigger_re_init_embedding_signal.connect(self.face_engine.re_init_face_embedding)
self.zoom_stop_analyze_signal.connect(self.face_engine.stop_running)
self.webcam_object = VideoCamera()
self.capture_webcam_signal.connect(self.webcam_object.capture_current_img)
self.trigger_webcam_signal.connect(self.webcam_object.trigger_camera)
self.face_engine.start()
self.update_database = False
self.zoom_webcam = False
select_record_dropdown = dbc.DropdownMenu([
dbc.DropdownMenuItem("Zoom Cloud", id='zoom-cloud', n_clicks=0, external_link=True,
href="https://zoom.us/oauth/authorize?response_type=code&client_id={}&redirect_uri={}".format(
zoom_client_ID, zoom_oauth_redirect_uri)),
dbc.DropdownMenuItem(dcc.Upload('Local Recorded', id='zoom-local', multiple=True), n_clicks=0),
dbc.DropdownMenuItem('Webcam', id='zoom-webcam', n_clicks=0),
],
label="Select Records")
zoom_webcam_analyzed_modal = dbc.Modal([
dbc.ModalHeader(dbc.ModalTitle('Zoom webcam analyze'), close_button=False),
dbc.ModalBody([dbc.Container(
dbc.Row([dbc.Col(html.Img(src="/video_feed_analyzed", id='webcam-analyzed'), align='center'), ],
style={'textAlign': 'center'}), )]),
dbc.ModalFooter(
dbc.Button("Finish", id='do-zoom-webcam-finish', class_name='ms-auto', n_clicks=0),
class_name='align-self-center'
)
], backdrop="static", keyboard=False, id='zoom-webcam-analyzed-modal', is_open=False, size='xl', centered=True)
analyze_button = dbc.Button('Analyze', id="analyze-btn", className="me-1", n_clicks=0),
analyze_options = dbc.Modal([
dbc.ModalHeader(dbc.ModalTitle('Analyze options')),
# Body
dbc.ModalBody([
dbc.Container([
dbc.Row([
dbc.Col(html.Span("Interval"), width=2, align='center'),
dbc.Col(dbc.Input(type="number", min=0.1, step=0.05, value=1, id='analyze-interval'), width=3),
dbc.Col(dbc.Select(id='interval-type',
options=[{'label': 'seconds', 'value': 0}, {'label': 'minutes', 'value': 1}],
value=0), width='auto')
]),
dbc.Row([
dbc.Col(html.Span("Recognition Sensitive"), width='auto', align='center'),
dbc.Col(dbc.Input(type="number", min=0.1, max=0.99, value=0.5, step=0.05,
id='recognition-sensitive'),
width=3),
]),
dbc.Row([
dbc.Col(html.Span("Face analysis options"), width='auto', align='center'),
]),
dbc.Row([
dbc.Col(dbc.Checklist(options=[{'label': 'Attendance', 'value': 1},
{'label': 'Emotion', 'value': 2, 'disabled': False},
{'label': 'Engagement', 'value': 3, 'disabled': False}],
id='face-analyze-options', value=[1], switch=True),
width={'offset': 1})
]),
dbc.Row([
dbc.Col(html.Span("Select class"), width='auto', align='center'),
dbc.Col(dbc.Select(id='classes-list', options=[], ), width='auto')
])
],
class_name='container-fluid overflow-hidden d-grid gap-3',
)
]),
# Footer
dbc.ModalFooter(
dbc.Button("OK", id='do-analyze-btn', class_name='ms-auto', n_clicks=0)
)
],
id='analyze-options',
scrollable=True,
is_open=False
)
meeting_list = dash_table.DataTable(id='meeting-lists',
columns=[
{"name": i, "id": i} for i in
['ID', 'Topics', 'Start time', 'DL Link', 'Play Link']
],
data=[],
row_selectable='single',
fill_width=True,
style_cell={
'textAlign': 'left', 'height': 'auto',
},
style_cell_conditional=[
{'if': {'column_id': 'ID'}, 'display': 'none'},
{'if': {'column_id': 'DL Link'}, 'display': 'none'},
{'if': {'column_id': 'Play Link'}, 'display': 'none'},
],
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(220, 220, 220)',
}
],
style_table={'overflowX': 'auto'}
)
meeting_player = html.Video(id='meeting-player', controls=True, autoPlay=True, src='', width='100%',
height='auto')
attendance_check_results = dash_table.DataTable(id='attendance-results',
columns=[
{"name": i, "id": i} for i in
['Timestamp (sec)', 'STUD 1', 'STUD 2', 'STUD 3', 'STUD 4']
],
page_size=15,
data=[
{'Timestamp (sec)': 'NaN', 'STUD 1': 'NaN', 'STUD 2': 'NaN',
'STUD 3': 'NaN', 'STUD 4': 'NaN'}],
row_selectable='multi',
style_cell={
'textAlign': 'center', 'height': 'auto',
'minWidth': '80px', 'width': '110px', 'maxWidth': '150px',
'whiteSpace': 'normal'
},
style_cell_conditional=[
{'if': {'column_id': 'Emotions'}, 'display': 'none'},
{'if': {'column_id': 'Attention'}, 'display': 'none'}],
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(220, 220, 220)',
}
],
style_header={
'fontWeight': 'bold', 'height': '50px',
},
fixed_rows={'headers': True},
fixed_columns={'headers': True, 'data': 1},
style_table={'overflowX': 'auto', 'overflowY': 'auto',
'height': 400, 'minWidth': '100%'},
)
attendance_check_graphs = dcc.Graph(figure={
'data': [],
'layout': {
'title': 'Data Visualization'
}
},
id='attendance_graphs'
)
webcam_modal = dbc.Container([dbc.Row(
[dbc.Col(html.Img(src="/video_feed", id='webcam-jpeg'), align='center'), ], style={'textAlign': 'center'}),
dbc.Row([dbc.Col(dbc.Button('Take picture', id='take-picture', n_clicks=0),
width='auto'),
dbc.Col(dbc.Button('Close', id='close-webcam-take-picture-btn',
class_name='ms-auto', n_clicks=0), width='auto')],
justify='center')],
fluid=True, class_name='justify-content-center d-grid gap-4')
# webcam_modal = dbc.Col(html.Img(src="/video_feed"), align='center', style={'textAlign': 'center'})
student_database_modal_body = dbc.Container([dbc.Row([
dbc.Col(html.Span('Student ID'), width='auto', align='center'),
dbc.Col(dcc.Dropdown(id='student-list-db',
placeholder='Select an ID'),
width='3')]),
dbc.Row([dbc.DropdownMenu([
dbc.DropdownMenuItem("From Webcam", id='add-photo-webcam', n_clicks=0),
dbc.DropdownMenuItem(dcc.Upload('Upload', id='add-photo-upload', multiple=True), n_clicks=0),
],
label="Add Photo", id='add-photo-btn')]),
dbc.Row(webcam_modal, justify='center', align='center', class_name='g-2', id='webcam-modal',
style={'display': 'none'}),
dbc.Row(id='student-photos', ),
], class_name='d-grid gap-4')
student_database_modal = dbc.Modal([dbc.ModalHeader(dbc.ModalTitle("Student Database", class_name='ms-auto')),
dbc.ModalBody(student_database_modal_body),
dbc.ModalFooter(
dbc.Button('Close', id='close-std-db-modal-btn', class_name='ms-auto',
n_clicks=0))
], id='student-database-modal', is_open=False, fullscreen=True)
self.app.layout = dbc.Container([
dbc.Row(style={'height': 2}),
dbc.Row([
dbc.Col(dbc.Row([dbc.Col(select_record_dropdown, width='auto'),
dbc.Col(dbc.Button('Student Database', id='std-db-btn', n_clicks=0), align='center',
width='auto'), dbc.Col(student_database_modal, width='auto')]), width=6),
dbc.Col(dbc.Row([dbc.Col(dbc.DropdownMenu([
dbc.DropdownMenuItem("Log out", id='zoom-cloud-logout')
],
label='Not Sign in', id='user_btn',
), width='auto')], justify='end'), width=6, align='center'), ],
class_name='g-1',
style={'border-bottom': '1px solid #ccc', 'margin': '2'}
),
dbc.Row([
dbc.Col(dbc.Row([
dbc.Col(dcc.DatePickerRange(id='date-picker-range', min_date_allowed=datetime.date(2019, 8, 1),
max_date_allowed=datetime.date.today(), end_date=datetime.date.today(),
start_date=datetime.date.today()),
width='auto'),
dbc.Col(dbc.Button('Get records', className="me-1", n_clicks=0, id='get-records-btn'),
align='center',
width='auto'),
dbc.Col(analyze_button, width='auto', align='center'),
dbc.Col(analyze_options, width='auto', align='center'),
dbc.Col(zoom_webcam_analyzed_modal, width='auto', align='center')]
)),
dbc.Col([dbc.Row(dbc.Col(dbc.Select(id='video-viewer-options',
options=[{'label': 'Zoom Recorded', 'value': '1'},
{'label': 'Analyzed Video', 'value': '2'}],
value=1,
), width={'size': 'auto'}, align='center'
), justify='end')]),
],
class_name='g-1', align='center'
),
dbc.Row([
dbc.Col(html.Div(meeting_list), width=6),
dbc.Col(html.Div(meeting_player), width=6)
],
class_name='g-1 h-50',
justify='between',
),
dbc.Row([
dbc.Col(
[dbc.Row([dbc.Col(dcc.Download(id='dl-atr-dcc')),
dbc.Col(dbc.Button('Export Excel', id='dl-attendance-results'), width='auto',
align='end')]),
dbc.Row(attendance_check_results)], width=6),
# dbc.Col(attendance_check_graphs, width=6)
dbc.Col([
dbc.Row([dbc.Col(html.Span("Visualization"), width={'offset': 1, 'size': 'auto'}, align='center', ),
dbc.Col(dbc.Select(id='viz_select',
options=[{'label': 'Attendance (%)', 'value': '1'}],
value=1
), width='auto'
),
dbc.Col(dcc.Download(id='dl-viz-dcc'), style={'display': 'none'}),
dbc.Col(dbc.Button('Export Excel', id='dl-viz-results'), width='auto',
)
], align='start'),
dbc.Row(attendance_check_graphs),
], width=6)
],
className='g-1',
# justify='start'
),
# @self.app.callback(Output('check-url', 'children'), Input('current-url', 'pathname'))
dbc.Row([dbc.Col(dbc.Label(id='access-token', children=''), width=4)], class_name='g-1', justify='between',
style={'display': 'none'}),
dbc.Row([html.P(id='check-meeting-player', style={'display': 'none'})]),
dbc.Row([html.P(id='check-url', style={'display': 'none'}), dcc.Location(id='current-url', refresh=True),
dcc.Store('zoom_webcam_store'), dcc.Store('video-src-webcam')]),
# dbc.Row([dbc.Col(html.Img(src="/video_feed"), width=3)])
],
class_name='overflow-hidden d-grid gap-4',
fluid=True,
style={'width': '95%'}
)
# Server route
@self.app.server.route('/video_feed')
def video_feed():
return Response(gen_camera(self.webcam_object), mimetype='multipart/x-mixed-replace; boundary=frame')
@self.app.server.route('/video_feed_analyzed')
def video_feed_analyzed():
return Response(self.face_engine.gen_frame_webcam(),
mimetype='multipart/x-mixed-replace; boundary=frame')
# Callbacks
@self.app.callback([Output('webcam-modal', 'style'), Output('add-photo-btn', 'disabled')],
[Input('add-photo-webcam', 'n_clicks'), Input('close-webcam-take-picture-btn', 'n_clicks')],
prevent_initial_call=True)
def toggle_webcam_modal(n_click, close_n_click):
change_id = [p['prop_id'] for p in callback_context.triggered][0]
if 'add-photo-webcam' in change_id:
# Take photos from webcam
self.trigger_webcam_signal.emit(True)
print('Add photo webcam clicked')
return {}, True
elif 'close-webcam-take-picture-btn' in change_id:
# Close webcam
print('Close webcam clicked')
self.trigger_webcam_signal.emit(False)
return {'display': 'none'}, False
else:
raise PreventUpdate
@self.app.callback([Output('student-database-modal', 'is_open'), Output('webcam-jpeg', 'src')],
[Input('std-db-btn', 'n_clicks'), Input('close-std-db-modal-btn', 'n_clicks')],
State('student-database-modal', 'is_open'), prevent_initial_call=True)
def toggle_student_database_modal(n_click, close_n_click, is_open):
if n_click or close_n_click:
if not is_open:
src = '/video_feed'
else:
src = '/video_feed' # ''
print('Check db modal', not is_open, src)
return not is_open, src
@self.app.callback(Output('student-list-db', 'options'), Input("student-list-db", "search_value"),
running=[(Output('add-photo-btn', 'disabled'), True, False)])
def update_options(search_value):
cur_std_db = [{'label': std_id, 'value': std_id} for std_id in os.listdir('./assets/students/') if
os.path.isdir('./assets/students/{}'.format(std_id))]
if not search_value:
raise PreventUpdate
# return cur_std_db
search_results = [o for o in cur_std_db if search_value in o['label']]
if len(search_results) > 0:
return search_results
else:
return [{'label': 'Add {} to database'.format(search_value), 'value': search_value}]
@self.app.callback(Output('student-photos', 'children'),
[Input('student-list-db', 'value'), Input('take-picture', 'n_clicks'),
Input('add-photo-upload', 'contents')],
State('webcam-jpeg', 'src'), State('current-url', 'href'),
State('add-photo-upload', 'filename'),
prevent_initial_call=True)
def selected_student_db(value, n_clicks, photo_contents, webcam_jpg, current_url, photo_filenames):
if not value:
print('No ID selected')
raise PreventUpdate
change_id = [p['prop_id'] for p in callback_context.triggered][0]
if not os.path.isdir('./assets/students/{}'.format(value)):
os.makedirs('./assets/students/{}'.format(value))
if 'take-picture' in change_id:
# Take picture
# print('Emit capture webcam signal')
self.capture_webcam_signal.emit(value)
self.update_database = True
time.sleep(0.2)
elif 'add-photo-upload' in change_id:
print('Add photo upload ', photo_filenames)
# Process uploaded file
if not isinstance(photo_filenames, list):
photo_contents = [photo_contents]
photo_filenames = [photo_filenames]
print('Number of photo: ', len(photo_filenames))
for file_idx in range(len(photo_contents)):
content_type, content_string = photo_contents[file_idx].split(',')
photo_name = photo_filenames[file_idx]
if 'jpeg' not in content_type and 'png' not in content_type:
continue
decoded = base64.b64decode(content_string)
print('Write path: ', './assets/students/{}/up_{}'.format(value, photo_name))
with open('./assets/students/{}/{}'.format(value, photo_name), 'wb') as upl_writer:
upl_writer.write(decoded)
self.update_database = True
list_photos = sorted(glob2.glob('./assets/students/{}/*.jpg'.format(value)) + glob2.glob(
'./assets/students/{}/*.png'.format(value)) + glob2.glob('./assets/students/{}/*.jpeg'.format(value)))
if len(list_photos) > 0:
card = [dbc.Card(children=[dbc.CardImg(src=x[1:], id=x, class_name='img-fluid pb-3 m-0', alt=x)],
class_name='col-3', style={'justifyContent': 'center', 'border': 'none'}) for x in
list_photos]
else:
card = html.Span('There is no photo of this student (ID: {}) in the database'.format(value))
return card
@self.app.callback(
[Output("analyze-options", "is_open"), Output('classes-list', 'options'), Output('classes-list', 'value'),
Output('zoom_webcam_store', 'data')],
[Input('analyze-btn', 'n_clicks'), Input('do-analyze-btn', 'n_clicks'), Input('zoom-webcam', 'n_clicks')],
[State('analyze-options', 'is_open'), State('classes-list', 'options'), State('zoom_webcam_store', 'data'),
State('classes-list', 'value')], prevent_initial_call=True)
def toggle_analyze_options(analyze_click, do_analyze_click, zoom_webcam_clicks, is_open, student_list_options,
student_list_value, zoom_webcam_store):
change_id = [p['prop_id'] for p in callback_context.triggered][0]
if 'zoom-webcam' in change_id:
self.zoom_webcam = True
elif 'analyze-btn' in change_id:
self.zoom_webcam = False
else:
self.zoom_webcam = zoom_webcam_store
if analyze_click or do_analyze_click or zoom_webcam_clicks:
cur_sel_idx = student_list_value
class_name = student_list_options
if not is_open:
# Will open, update student lists
# student-list
class_list_files = sorted(glob2.glob('./assets/classes_list/*.txt'))
# options = [{'label': 'seconds', 'value': 0}, {'label': 'minutes', 'value': 1}]
class_name = [
{'label': class_list_files[cl_idx].split('/')[-1].replace('.txt', ''), 'value': cl_idx} for
cl_idx in range(len(class_list_files))]
print('Current list value: ', type(student_list_value))
if student_list_value is not None:
cur_sel = student_list_options[int(student_list_value)]['label']
for idx in range(len(class_name)):
print(class_name[idx]['label'], cur_sel)
if class_name[idx]['label'] == cur_sel:
cur_sel_idx = idx
print(cur_sel_idx)
break
else:
cur_sel_idx = class_name[0]['value']
return not is_open, class_name, cur_sel_idx, self.zoom_webcam
return is_open, student_list_options, student_list_value, self.zoom_webcam
@self.app.callback([Output('meeting-lists', 'data')],
[Input('get-records-btn', 'n_clicks'), Input('zoom-local', 'contents')],
State('date-picker-range', 'start_date'), State('date-picker-range', 'end_date'),
State('zoom-local', 'filename'), State('zoom-local', 'last_modified'),
running=[(Output('get-records-btn', 'disabled'), True, False)],
prevent_initial_call=True)
def get_meeting_lists(grbtn_clicks, zoom_local_contents, start_date, end_date, zoom_local_names,
zoom_local_last_modified):
change_id = [p['prop_id'] for p in callback_context.triggered][0]
meeting_lists_data = DataFrame(columns=['ID', 'Topics', 'Start time'])
if 'get-records-btn' in change_id and self.access_token != '':
# Get list of meeting
requests_address = 'https://api.zoom.us/v2/users/{}/recordings'.format(zoom_userID)
requests_headers = {
"Authorization": "Bearer " + self.access_token,
}
resp_get = requests.get(url=requests_address, headers=requests_headers,
params={'from': start_date, 'to': end_date}
)
print(resp_get.status_code, resp_get.json())
resp = resp_get.json()
if resp_get.status_code == 200:
if resp['total_records'] > 0:
total_records = resp['total_records']
list_meetings = resp['meetings']
disp_meetings = []
for idx in range(total_records):
cur_uuid = list_meetings[idx]['uuid']
curr_topic = list_meetings[idx]['topic']
curr_start_time = list_meetings[idx]['start_time']
curr_recording_files = list_meetings[idx]['recording_files']
cur_gal_view = False
cur_dl_link = ''
cur_play_link = ''
for rec_files in curr_recording_files:
if rec_files['recording_type'] == 'gallery_view':
cur_gal_view = True
cur_dl_link = rec_files['download_url']
cur_play_link = rec_files['play_url']
disp_meetings.append([cur_uuid, curr_topic, curr_start_time, cur_dl_link, cur_play_link])