Repository navigation
Expand file tree
/
Copy pathface_recognize.py
More file actions
1311 lines (1175 loc) Β· 56 KB
/
Copy pathface_recognize.py
File metadata and controls
1311 lines (1175 loc) Β· 56 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
#!/usr/bin/env python3
"""Real-time face recognition using InsightFace (ArcFace embeddings).
Features:
- Enrollment: build embedding templates from images in a folder (per-person subfolders supported).
- Real-time recognition from webcam using precomputed templates.
- Basic augmentations at enrollment (flip, small rotations) to improve one-shot robustness.
Usage examples:
# Build templates from images under data/original (or faces/)
python face_recognize.py --mode enroll --enroll-dir data/original --out models/templates.npz
# Run real-time recognition using stored templates
python face_recognize.py --mode recognize --templates models/templates.npz --threshold 0.45
Requirements: see requirements.txt (insightface, onnxruntime, opencv-python, numpy)
"""
import os
import sys
import argparse
import time
import json
from pathlib import Path
# Ensure script runs only inside a Python virtual environment (venv).
def _in_venv():
# sys.real_prefix is set for old virtualenv, or base_prefix != prefix for venv
try:
in_venv_flag = hasattr(sys, 'real_prefix') or (getattr(sys, 'base_prefix', None) != getattr(sys, 'prefix', None)) or ('VIRTUAL_ENV' in os.environ)
except Exception:
in_venv_flag = False
return in_venv_flag
if not _in_venv():
msg = (
"Error: This script must be run inside a Python virtual environment (venv).\n"
"Create and activate one in the project root, then install requirements:\n\n"
" python3 -m venv venv\n"
" source venv/bin/activate\n"
" pip install -r requirements.txt\n\n"
"After activating the venv, re-run this script.\n"
)
print(msg, file=sys.stderr)
sys.exit(1)
import cv2
import numpy as np
import threading
import queue
import base64
import sqlite3
import random
import re
try:
from insightface.app import FaceAnalysis
except Exception as e:
print("Error importing insightface. Please install requirements from requirements.txt")
raise
def load_face_analyzer(ctx_id=-1, det_size=(640, 640), provider='cpu'):
"""Initialize InsightFace FaceAnalysis (detection + recognition)."""
# allowed_modules ensures we have detection + recognition
fa = FaceAnalysis(allowed_modules=['detection', 'recognition'])
# ctx_id = -1 -> CPU, 0 -> GPU
fa.prepare(ctx_id=ctx_id, det_size=det_size)
return fa
def image_files_in_dir(dirpath):
exts = ('.jpg', '.jpeg', '.png', '.bmp')
p = Path(dirpath)
if not p.exists():
return []
files = [str(x) for x in p.rglob('*') if x.suffix.lower() in exts]
return files
def compute_embedding(fa, img_bgr):
# insightface expects BGR images (OpenCV), works with FaceAnalysis.get
faces = fa.get(img_bgr)
if len(faces) == 0:
return None
# Take the largest face (most common scenario)
faces = sorted(faces, key=lambda f: f.bbox[2] * f.bbox[3], reverse=True)
emb = faces[0].embedding
# normalize
emb = emb / np.linalg.norm(emb)
return emb
def augment_image(img):
"""Yield simple augmentations for a single image to improve template robustness."""
yield img
# Horizontal flip
yield cv2.flip(img, 1)
# small rotations
for angle in (-10, -5, 5, 10):
h, w = img.shape[:2]
M = cv2.getRotationMatrix2D((w // 2, h // 2), angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
yield rotated
def enroll_from_folder(fa, enroll_dir, out_path=None, augment=True, skip_names=None):
"""Build templates (average normalized embedding per identity) from an enrollment folder.
Folder formats supported:
- enroll_dir/person_name/*.jpg (recommended)
- enroll_dir/*.jpg with filenames like 'personname_1.jpg'
"""
enroll_dir = Path(enroll_dir)
if not enroll_dir.exists():
raise FileNotFoundError(f"Enroll directory not found: {enroll_dir}")
templates = {}
# If there are subdirectories, treat each subdir as a person
subdirs = [d for d in enroll_dir.iterdir() if d.is_dir()]
if len(subdirs) > 0:
for person_dir in subdirs:
name = person_dir.name
if skip_names and name in skip_names:
# skip processing existing identity
continue
files = image_files_in_dir(person_dir)
embeddings = []
for f in files:
img = cv2.imread(f)
if img is None:
continue
if augment:
imgs = list(augment_image(img))
else:
imgs = [img]
for ai in imgs:
emb = compute_embedding(fa, ai)
if emb is not None:
embeddings.append(emb)
if len(embeddings) > 0:
templates[name] = np.mean(np.stack(embeddings), axis=0)
templates[name] = templates[name] / np.linalg.norm(templates[name])
print(f"Enrolled {name}: {len(embeddings)} embeddings -> template saved")
else:
print(f"Warning: No valid face embeddings for {name}")
else:
# No subdirs: use files directly and derive person name from filename prefix
files = image_files_in_dir(enroll_dir)
by_person = {}
for f in files:
stem = Path(f).stem
# take prefix up to first non-alphanumeric (e.g., person_1.jpg -> person)
prefix = ''.join([c for c in stem if c.isalnum() or c==' '])
name = prefix.split('_')[0]
by_person.setdefault(name, []).append(f)
for name, flist in by_person.items():
if skip_names and name in skip_names:
continue
embeddings = []
for f in flist:
img = cv2.imread(f)
if img is None:
continue
imgs = list(augment_image(img)) if augment else [img]
for ai in imgs:
emb = compute_embedding(fa, ai)
if emb is not None:
embeddings.append(emb)
if len(embeddings) > 0:
templates[name] = np.mean(np.stack(embeddings), axis=0)
templates[name] = templates[name] / np.linalg.norm(templates[name])
print(f"Enrolled {name}: {len(embeddings)} embeddings -> template saved")
else:
print(f"Warning: No valid face embeddings for {name}")
# Return templates dict (caller may save or merge)
return {k: v.astype(np.float32) for k, v in templates.items()}
def save_templates(templates: dict, out_path: str):
np_templates = {k: v.astype(np.float32) for k, v in templates.items()}
np.savez_compressed(out_path, **np_templates)
print(f"Templates saved to {out_path}. Keys: {list(templates.keys())}")
def merge_and_save_templates(existing_path: str, new_templates: dict, out_path: str):
"""Load existing templates (if any), merge/overwrite with new_templates, and save to out_path."""
merged = {}
if os.path.exists(existing_path):
data = np.load(existing_path)
merged = {k: data[k].astype(np.float32) for k in data.files}
# Overwrite or add
merged.update(new_templates)
save_templates(merged, out_path)
return out_path
def load_templates(path):
if not os.path.exists(path):
raise FileNotFoundError(path)
data = np.load(path)
templates = {k: data[k].astype(np.float32) for k in data.files}
return templates
def match_embedding(emb, templates):
# emb and templates are normalized; use cosine similarity
best_name = None
best_score = -1.0
for name, temp in templates.items():
score = float(np.dot(emb, temp))
if score > best_score:
best_score = score
best_name = name
return best_name, best_score
class CameraRecognizer:
"""Headless camera recognizer for R/reticulate integration.
R can call:
recognizer = CameraRecognizer(templates_path='models/templates.npz', det_size=320)
recognizer.start()
frame_b64 = recognizer.get_frame() # returns base64 JPEG string
recognizer.stop()
"""
def __init__(self, templates_path='models/templates.npz', det_size=320, threshold=0.45, camera_id=0, detect_every=1, guide_w=0.4, guide_h=0.5, wait_time=0.0, guide_shape='rect'):
self.templates_path = templates_path
self.det_size = det_size
self.threshold = threshold
self.camera_id = camera_id
self.detect_every = int(detect_every)
# guide box relative size (fractions of frame width/height)
self.guide_w = float(guide_w)
self.guide_h = float(guide_h)
# guide shape: 'rect' or 'triangle'
self.guide_shape = 'rect'
self.fa = None
self.templates = None
self.cap = None
self.running = False
self.latest_frame = None
self.lock = threading.Lock()
self.thread = None
# legacy simple timers (kept for compatibility but not used by tracker)
self.confirm_timers = {}
self.confirmed = set()
# map of confirmed track id -> display label (keeps human-friendly names)
self.confirmed_map = {}
# Lightweight tracker state: track_id -> dict(centroid=(x,y), last_seen=t, start_time=t_started, raw_name, label, bbox)
self.tracks = {}
self.next_track_id = 1
# grace time (seconds) before clearing a track when face disappears briefly
self.grace_time = 0.6
# maximum distance (px) to match detection to existing track
self.track_match_dist = 80
# expose guide shape
self.guide_shape = guide_shape
# latest annotations for external polling (list of tuples)
self.latest_annotations = []
# DB integration
self.db_path = os.path.join('db', 'attendance.db')
self.session_id = None
# Person state tracker with movement direction for door-mounted camera
# raw_name -> {'state', 'last_record_time', 'last_state_change'}
self._person_states = {}
# Entry zone: top 40% of frame (where door/entrance would be)
self.entry_zone_threshold = 0.4
# Cooldown period: minimum time between recording same person (prevents spam)
self.record_cooldown = 30.0 # 30 seconds minimum between entry/exit records
# background writer queue + thread to avoid blocking camera loop
self._write_queue = queue.Queue()
self._writer_thread = threading.Thread(target=self._writer_loop, daemon=True)
self._writer_running = True
self._writer_thread.start()
# Track exit times for absence alerts (raw_name -> timestamp)
self.exit_alerts = {}
def start(self):
"""Initialize and start the recognition loop in a background thread."""
if self.running:
return
# Start an init thread so the call to start() is non-blocking for the caller/UI.
def _init_and_start():
try:
# Load analyzer and templates (may be slow)
self.fa = load_face_analyzer(ctx_id=-1, det_size=(self.det_size, self.det_size))
if os.path.exists(self.templates_path):
self.templates = load_templates(self.templates_path)
else:
raise FileNotFoundError(f"Templates not found: {self.templates_path}")
# Open camera with multiple fallbacks to handle common Linux V4L2 issues
def try_open_device(dev, prefer_v4l2=True):
# Try to open with V4L2 backend first when available (better on Linux)
caps = []
try:
if prefer_v4l2 and hasattr(cv2, 'CAP_V4L2'):
caps.append(cv2.CAP_V4L2)
except Exception:
pass
caps.append(None) # fallback to default
for backend in caps:
cap_try = None
try:
if backend is None:
cap_try = cv2.VideoCapture(dev)
else:
cap_try = cv2.VideoCapture(dev, backend)
if cap_try is None:
continue
if cap_try.isOpened():
# quick read to ensure frames are produced
r, _ = cap_try.read()
if r:
return cap_try
try:
cap_try.release()
except Exception:
pass
except Exception:
try:
if cap_try is not None:
cap_try.release()
except Exception:
pass
return None
self.cap = None
# If camera_id is an integer, try that index first then probe /dev/video* and 0..9
if isinstance(self.camera_id, int):
# Try requested index first
self.cap = try_open_device(self.camera_id)
# If failed, scan /dev/video* for available devices
if self.cap is None:
try:
dev_ids = [int(p.name.replace('video', '')) for p in sorted(Path('/dev').glob('video*')) if p.name.startswith('video')]
except Exception:
dev_ids = []
tried = set()
for i in dev_ids + list(range(0, 10)):
if i in tried:
continue
tried.add(i)
self.cap = try_open_device(i)
if self.cap is not None:
self.camera_id = i
print(f"Using camera device /dev/video{ i }")
break
else:
# camera_id may be a path/URL string (e.g., '/dev/video0' or rtsp://...)
try:
self.cap = try_open_device(self.camera_id, prefer_v4l2=False)
except Exception:
self.cap = None
if self.cap is None or not self.cap.isOpened():
# Do not raise from background init thread; print helpful diagnostics instead
print(f"Error: Unable to open camera (requested: {self.camera_id}).")
print("Tried V4L2 and default OpenCV backends. Ensure the device exists, is not in use, and permissions allow access.")
print("On Linux: check /dev/video* devices, run 'v4l2-ctl --list-devices', and ensure no other process holds the camera.")
self.running = False
return
# Set standard laptop camera resolution for proper aspect ratio and performance
# 640x480 provides good balance: natural aspect ratio, fast processing, no zoom
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
# Set FPS to 30 for smoother capture
self.cap.set(cv2.CAP_PROP_FPS, 30)
# Try to reduce capture buffering / latency when supported
try:
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
except Exception:
pass
# mark running and start loop thread
self.running = True
self.thread = threading.Thread(target=self._run_loop, daemon=True)
self.thread.start()
except Exception:
# ensure running is false on failure
self.running = False
raise
self._init_thread = threading.Thread(target=_init_and_start, daemon=True)
self._init_thread.start()
def _run_loop(self):
"""Background loop: read frames, detect, annotate, and store latest JPEG."""
def split_name_id(s):
i = len(s)
while i > 0 and s[i-1].isdigit():
i -= 1
name = s[:i] if i>0 else s
idpart = s[i:] if i<len(s) else ''
return name, idpart
frame_idx = 0
last_annotations = []
while self.running:
ret, frame = self.cap.read()
if not ret:
time.sleep(0.01)
continue
frame_idx += 1
do_detect = (self.detect_every <= 0) or (frame_idx % self.detect_every == 0)
h, w = frame.shape[:2]
if do_detect:
faces = self.fa.get(frame)
annotations = []
for face in faces:
x1, y1, x2, y2 = [int(v) for v in face.bbox]
cx = (x1 + x2) // 2
cy = (y1 + y2) // 2
# Match all faces (no guide restriction)
emb = face.embedding / np.linalg.norm(face.embedding)
raw_name, score = match_embedding(emb, self.templates)
label = 'Unknown'
color = (0, 0, 255)
if score >= self.threshold and raw_name is not None:
person_name, person_id = split_name_id(raw_name)
display_text = f"{person_name} {person_id}".strip()
label = display_text if display_text else person_name
color = (0, 255, 0)
# store raw_name and score for confirmation logic
annotations.append((x1, y1, x2, y2, label, color, raw_name, float(score)))
last_annotations = annotations
else:
annotations = last_annotations
now = time.time()
# Build detections list (include all faces)
detections = []
for ann in annotations:
x1, y1, x2, y2, label, color, raw_name, score = ann
cx = (x1 + x2) // 2
cy = (y1 + y2) // 2
detections.append((cx, cy, x1, y1, x2, y2, label, raw_name, score, color))
# Simple centroid tracker: match detections to existing tracks
updated_tids = set()
for det in detections:
cx, cy, x1, y1, x2, y2, label, raw_name, score, color = det
best_tid = None
best_dist = None
for tid, t in self.tracks.items():
tx, ty = t['centroid']
dist = (tx - cx) ** 2 + (ty - cy) ** 2
if best_dist is None or dist < best_dist:
best_dist = dist; best_tid = tid
if best_tid is not None and best_dist is not None and best_dist <= (self.track_match_dist ** 2):
# update track
t = self.tracks[best_tid]
t['centroid'] = (cx, cy)
t['last_seen'] = now
t['bbox'] = (x1, y1, x2, y2)
t['label'] = label
t['raw_name'] = raw_name
t['score'] = score
if t.get('start_time', None) is None:
t['start_time'] = now
updated_tids.add(best_tid)
else:
# create new track
tid = self.next_track_id
self.next_track_id += 1
self.tracks[tid] = {
'centroid': (cx, cy),
'last_seen': now,
'start_time': now,
'bbox': (x1, y1, x2, y2),
'label': label,
'raw_name': raw_name,
'score': score
}
updated_tids.add(tid)
# Track currently detected people with cooldown-based recording
currently_detected = set()
# Valid detection logic with 1.5s static verification and 30s cooldown
# Update tracks with static analysis
for tid, t in self.tracks.items():
# centroid history for static analysis
if 'history' not in t:
t['history'] = []
t['history'].append(t['centroid'])
# keep last 2 seconds approx (30 fps * 2 = 60 frames)
if len(t['history']) > 60:
t['history'].pop(0)
currently_detected = set()
for tid, t in self.tracks.items():
raw = t.get('raw_name')
if raw and raw != 'Unknown':
currently_detected.add(raw)
# Check if static for 0.33 seconds
# We need at least 0.33s * 30fps = 10 frames of history
is_static = False
if len(t.get('history', [])) >= 10:
# Calculate movement range in last ~0.33s
recent = t['history'][-10:]
xs = [p[0] for p in recent]
ys = [p[1] for p in recent]
# max dispersion (box diagonal approx 150px, so 30px is reasonable for "standing still")
dispersion = max(max(xs) - min(xs), max(ys) - min(ys))
if dispersion < 40: # 40px threshold for static
is_static = True
# Initialize state if new
if raw not in self._person_states:
self._person_states[raw] = {
'state': 'outside', # Assume outside initially
'last_state_change': 0,
'track_id': tid
}
state_info = self._person_states[raw]
last_change = state_info.get('last_state_change', 0)
current_state = state_info.get('state', 'outside')
# Logic: Only trigger change if COOLDOWN passed AND person is STATIC
# Cooldown: uses self.record_cooldown (30 seconds)
if (now - last_change) > self.record_cooldown:
if is_static:
if current_state == 'outside':
# Trigger ENTRY
self._person_states[raw]['state'] = 'inside'
self._person_states[raw]['last_state_change'] = now
self._enqueue_record(dict(t), None, detection_type='entry')
print(f"π₯ ENTRY: {raw} (Static Verified)")
# Show feedback on frame (optional)
t['label'] = f"ENTRY: {t.get('label', raw)}"
# Clear exit alert when student re-enters
self.exit_alerts.pop(raw, None)
elif current_state == 'inside':
# Trigger EXIT
self._person_states[raw]['state'] = 'outside'
self._person_states[raw]['last_state_change'] = now
self._enqueue_record(dict(t), None, detection_type='exit')
print(f"π€ EXIT: {raw} (Static Verified)")
t['label'] = f"EXIT: {t.get('label', raw)}"
# Track exit time for absence alerts
self.exit_alerts[raw] = now
else:
# Not static yet - maybe show progress?
pass
# Always update map for display
self.confirmed_map[tid] = t.get('label', raw)
# Garbage collect states for people deemed "outside" for a long time (e.g. > 1 hour) to keep memory clean
# But we must keep them if they are "inside" to track exit
for raw, state_info in list(self._person_states.items()):
if state_info['state'] == 'outside' and (now - state_info['last_state_change'] > 3600):
del self._person_states[raw]
# Remove stale tracks (don't record exit here, already handled above)
stale = [tid for tid, t in self.tracks.items() if (now - t['last_seen']) > self.grace_time]
for tid in stale:
self.tracks.pop(tid, None)
# Draw face annotations; show label when confirmed and intermediate progress bars
for ann in annotations:
x1, y1, x2, y2, label, color, raw_name, score = ann
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
# find nearest track for this annotation (if any)
cx = (x1 + x2) // 2
cy = (y1 + y2) // 2
best_tid = None
best_dist = None
for tid, t in self.tracks.items():
tx, ty = t['centroid']
dist = (tx - cx) ** 2 + (ty - cy) ** 2
if best_dist is None or dist < best_dist:
best_dist = dist; best_tid = tid
frac = 0.0
confirmed_label = None
if best_tid is not None and best_dist is not None and best_dist <= (self.track_match_dist ** 2):
t = self.tracks[best_tid]
st = t.get('start_time', None)
if st is not None:
# Show as confirmed immediately
frac = 1.0
if best_tid in self.confirmed_map:
confirmed_label = self.confirmed_map.get(best_tid)
# Draw label next to bounding box (no progress bar)
if confirmed_label is not None:
tx = x2 + 8
ty = y1 + 20
text = confirmed_label
(tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)
if tx + tw + 4 > w:
tx = max(4, x1 - tw - 8)
cv2.putText(frame, text, (tx, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
# Encode to JPEG with lower quality for speed (75% quality)
ret, jpg = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 75])
if ret:
with self.lock:
self.latest_frame = jpg.tobytes()
# store a shallow copy of annotations for polling (x1,y1,x2,y2,label,color,raw_name,score)
try:
self.latest_annotations = list(annotations)
except Exception:
self.latest_annotations = []
# small sleep to avoid busy loop (reduced for higher FPS)
time.sleep(0.005)
def get_frame(self):
"""Return latest annotated frame as base64 string (for embedding in HTML img src)."""
with self.lock:
data = self.latest_frame
if data is None:
return None
return base64.b64encode(data).decode('utf-8')
def get_confirmed(self, pop=True):
"""Return list of confirmed names. If pop=True, clear the confirmed set after returning.
Returns a Python list of strings (suitable for reticulate conversion to R).
"""
with self.lock:
names = list(self.confirmed_map.values())
if pop:
# clear confirmed map (do not remove tracks immediately)
self.confirmed_map.clear()
# Note: we keep person_states intact to maintain state across polling
return names
def set_db_path(self, path):
"""Set SQLite DB path used for recording detections/attendance."""
self.db_path = path
def set_session(self, session_id):
"""Set active session_id (string). When set, confirmed detections will be written into `attendance` table."""
self.session_id = session_id
def _map_rawname_to_student(self, raw_name):
"""Try to map a template raw_name to a student_id in the DB.
Returns student_id (str) or None if not found.
Strategy: try exact student_id match, then name match, then photo_path LIKE, then trailing digits as id.
"""
if raw_name is None:
return None
# sanitize
key = str(raw_name)
# quick heuristic: if key looks like an id (all digits) try direct match
try:
conn = sqlite3.connect(self.db_path, timeout=5)
cur = conn.cursor()
except Exception:
return None
try:
# 1) exact student_id
cur.execute("SELECT student_id FROM students WHERE student_id = ?", (key,))
r = cur.fetchone()
if r:
return r[0]
# 2) exact name
cur.execute("SELECT student_id FROM students WHERE name = ? COLLATE NOCASE", (key,))
r = cur.fetchone()
if r:
return r[0]
# 3) name LIKE
cur.execute("SELECT student_id FROM students WHERE name LIKE ? LIMIT 1", (f"%{key}%",))
r = cur.fetchone()
if r:
return r[0]
# 5) trailing digits heuristic
m = re.search(r"(\d{3,})$", key)
if m:
candidate = m.group(1)
cur.execute("SELECT student_id FROM students WHERE student_id = ?", (candidate,))
r = cur.fetchone()
if r:
return r[0]
except Exception:
pass
finally:
try:
conn.close()
except Exception:
pass
return None
def _split_name_id(self, s: str):
"""Split a string into (name, idpart) where idpart is trailing digits if present."""
if s is None:
return (None, None)
s = str(s).strip()
i = len(s)
while i > 0 and s[i-1].isdigit():
i -= 1
name = s[:i].strip() if i > 0 else s
idpart = s[i:].strip() if i < len(s) else ''
if idpart == '':
idpart = None
return (name if name != '' else None, idpart)
def _record_detection_and_attendance(self, track, frame=None, detection_type='entry'):
"""Record a Detection row with entry or exit type.
Expects `track` dict containing keys: raw_name, label, score
"""
raw = track.get('raw_name')
if not raw or raw == 'Unknown':
return
try:
conn = sqlite3.connect(self.db_path, timeout=5)
cur = conn.cursor()
except Exception:
return
# find student mapping
student_id = self._map_rawname_to_student(raw)
if not student_id:
conn.close()
return
# Record entry or exit
score = float(track.get('score', 0.0) or 0.0)
ts = time.strftime('%Y%m%d%H%M%S')
det_id = f"DET_{ts}_{random.randint(1000,9999)}"
try:
cur.execute(
"INSERT INTO Detection (detection_id, student_id, session_id, photo_path, confidence_score, detection_type, face_detected, num_faces, match_status, processing_time_ms, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(det_id, student_id, self.session_id, None, score, detection_type, None, None, 'matched', None, f'Auto-detected {detection_type}')
)
conn.commit()
except Exception:
pass
conn.close()
def peek_confirmed(self):
"""Return list of confirmed names without clearing."""
with self.lock:
return list(self.confirmed_map.values())
def get_progress(self):
"""Return current in-guide annotations with progress fraction.
Returns list of dict-like tuples: {"label", "raw_name", "frac", "bbox":(x1,y1,x2,y2), "score"}
Suitable for `reticulate` conversion to R as a list of lists.
"""
now = time.time()
out = []
with self.lock:
# snapshot tracks
tracks = dict(self.tracks)
for tid, t in tracks.items():
start = t.get('start_time', None)
# Show as confirmed immediately (no wait time)
frac = 1.0 if start is not None else 0.0
out.append({
'label': t.get('label', t.get('raw_name', 'Unknown')),
'raw_name': t.get('raw_name', 'Unknown'),
'frac': float(frac),
'bbox': t.get('bbox', (0,0,0,0)),
'score': float(t.get('score', 0.0))
})
return out
def get_absence_alerts(self):
"""Return list of students who exited and haven't returned within 40 seconds.
Returns list of dicts: [{"name": str, "seconds_absent": int}, ...]
"""
now = time.time()
alerts = []
with self.lock:
for raw_name, exit_time in list(self.exit_alerts.items()):
seconds_gone = now - exit_time
if seconds_gone >= 40.0:
alerts.append({
'name': raw_name,
'seconds_absent': int(seconds_gone)
})
return alerts
def stop(self):
"""Stop the recognition loop and release camera."""
# signal run loop to stop
self.running = False
# join run loop thread if started
try:
if getattr(self, 'thread', None):
self.thread.join(timeout=2.0)
except Exception:
pass
# join init thread if still initializing
try:
if getattr(self, '_init_thread', None):
self._init_thread.join(timeout=2.0)
except Exception:
pass
if self.cap:
self.cap.release()
self.cap = None
# stop writer thread
try:
self._writer_running = False
# put a sentinel to unblock queue.get()
self._write_queue.put(None)
self._writer_thread.join(timeout=2.0)
except Exception:
pass
def flush_writes(self, timeout=None):
"""Block until the writer queue appears drained or until `timeout` seconds elapse.
Returns True if the queue was drained, False if timed out.
"""
start = time.time()
while True:
try:
# If queue empty and writer likely processed last item, return
if self._write_queue.empty():
# small pause to let writer pick last job
time.sleep(0.05)
if self._write_queue.empty():
return True
if timeout is not None and (time.time() - start) > float(timeout):
return False
time.sleep(0.05)
except Exception:
return False
def _enqueue_record(self, track, frame=None, detection_type='entry'):
"""Quickly enqueue a detection record for background writing.
We crop and encode the face to JPEG bytes here (fast) then push to queue.
"""
try:
# prepare shallow metadata
bbox = track.get('bbox', (0, 0, 0, 0))
x1, y1, x2, y2 = bbox
jpeg_bytes = None
if frame is not None and isinstance(frame, (np.ndarray,)):
try:
h, w = frame.shape[:2]
# clamp bbox
x1c = max(0, min(w - 1, int(x1)))
y1c = max(0, min(h - 1, int(y1)))
x2c = max(0, min(w, int(x2)))
y2c = max(0, min(h, int(y2)))
if x2c > x1c and y2c > y1c:
crop = frame[y1c:y2c, x1c:x2c]
else:
crop = frame
ret, enc = cv2.imencode('.jpg', crop)
if ret:
jpeg_bytes = enc.tobytes()
except Exception:
jpeg_bytes = None
job = {
'track': dict(track),
'jpeg': jpeg_bytes,
'ts': time.time(),
'detection_type': detection_type
}
self._write_queue.put(job)
print(f"π Enqueued job: raw_name={track.get('raw_name')} detection_type={detection_type}")
except Exception:
pass
def _writer_loop(self):
"""Background writer thread: process queued jobs and write DB + files."""
import traceback
while self._writer_running:
try:
job = self._write_queue.get()
if job is None:
break
track = job.get('track', {})
jpeg = job.get('jpeg', None)
detection_type = job.get('detection_type', 'entry')
print(f"π Writer processing job: raw_name={track.get('raw_name')} detection_type={detection_type}")
# perform DB write with its own sqlite connection
try:
conn = sqlite3.connect(self.db_path, timeout=5)
cur = conn.cursor()
except Exception:
conn = None; cur = None
student_id = None
try:
raw = track.get('raw_name')
# mapping only β DO NOT auto-create students here
student_id = self._map_rawname_to_student(raw)
print(f"π Mapped raw_name='{raw}' to student_id='{student_id}'")
except Exception:
student_id = None
# Use detection_type from job (entry or exit)
det_id = None
try:
if cur is not None and student_id:
ts = time.strftime('%Y%m%d%H%M%S')
det_id = f"DET_{ts}_{random.randint(1000,9999)}"
score_val = float(track.get('score', 0.0) or 0.0)
try:
time_arrived = time.strftime('%Y-%m-%d %H:%M:%S')
cur.execute(
"INSERT INTO Detection (detection_id, student_id, session_id, confidence_score, detection_type, match_status, time_arrived, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(det_id, student_id, self.session_id, score_val, detection_type, 'matched', time_arrived, f'Auto-detected {detection_type}')
)
conn.commit()
print(f"β
Writer: inserted Detection {det_id} student={student_id} session={self.session_id} score={score_val}")
except Exception as e:
print("β Writer: failed to insert Detection", e)
traceback.print_exc()
else:
print(f"β οΈ Writer: skipping insert because cur={cur is not None} student_id={student_id} session_id={self.session_id}")
except Exception:
try:
if conn is not None:
conn.rollback()
except Exception:
pass
try:
if conn is not None:
conn.close()
except Exception:
pass
# Job completed - state is tracked in _person_states
self._write_queue.task_done()
except Exception:
time.sleep(0.01)
def recognize_realtime(fa, templates, threshold=0.45, camera_id=0, print_only=False, no_save_frames=True, skip_frames=0, guide_w=0.4, guide_h=0.5, wait_time=0.0, guide_shape='rect'):
# skip_frames: number of frames to skip between full detections (0 means detect every frame)
# If the user requested a camera (int), prefer scanning for a working
# camera device (try /dev/video* first, then ids 0..9) and pick the first
# device that returns a frame. This avoids sticking on /dev/video0 when it
# opens but doesn't produce frames.
cap = None
if isinstance(camera_id, int):
dev_ids = []
try:
for p in sorted(Path('/dev').glob('video*')):
name = p.name
if name.startswith('video'):
try:
dev_ids.append(int(name.replace('video', '')))
except Exception:
pass
except Exception:
dev_ids = []
scan_ids = []
seen = set()
for i in dev_ids:
if i not in seen:
scan_ids.append(i); seen.add(i)
for i in range(0, 10):
if i not in seen:
scan_ids.append(i); seen.add(i)
found = False
for i in scan_ids:
try:
alt = cv2.VideoCapture(i)
if alt.isOpened():
# try a quick read to ensure frames are available
r, _ = alt.read()
if r:
cap = alt
camera_id = i
print(f"Using camera device /dev/video{i}")