-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2513 lines (2195 loc) · 124 KB
/
app.py
File metadata and controls
2513 lines (2195 loc) · 124 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
from flask import Flask, render_template, request, jsonify, send_from_directory, Response, session, redirect, url_for
from flask_mail import Mail, Message
import cv2
import numpy as np
from ultralytics import YOLO
import os
import mimetypes
# Load environment variables from .env file
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
# python-dotenv not installed, skip loading .env file
pass
import base64
import threading
import time
import re
import queue
from io import BytesIO
from datetime import datetime
from src.botsort_tracker import BotSORT
from src.email_templates import generate_violation_email_body
from werkzeug.security import check_password_hash
from src.debug_utils import debug_rfid, debug_violation, debug_email, debug_compliance, debug_database, debug_camera, debug_sync, debug_print
# Diagnostic: Print Python path for debugging
import sys
print(f"Python executable: {sys.executable}")
print(f"Python version: {sys.version}")
try:
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
REPORTLAB_AVAILABLE = True
print("✓ reportlab library loaded successfully - PDF generation enabled")
except ImportError as e:
REPORTLAB_AVAILABLE = False
print(f"✗ Warning: reportlab not available. PDF generation will be disabled.")
print(f" Error: {e}")
print(f" Python path: {sys.executable}")
print(f" Try running: {sys.executable} -m pip install reportlab")
except Exception as e:
REPORTLAB_AVAILABLE = False
print(f"✗ Warning: Error loading reportlab. PDF generation will be disabled.")
print(f" Error: {e}")
print(f" Python path: {sys.executable}")
# College abbreviation mapping
COLLEGE_ABBREVIATIONS = {
'College of Sciences': 'CS',
'College of Engineering': 'COE',
'College of Business and Accountancy': 'CBA',
'College of Nursing and Health Sciences': 'CNHS',
'College of Architecture and Design': 'CAD',
'College of Hospitality Management and Tourism': 'CHTM',
'College of Criminal Justice and Education': 'CCJE',
'College of Teacher Education': 'CTE',
'College of Arts And Humanities': 'CAH'
}
def get_college_abbreviation(college_name):
"""Get the abbreviation for a college name, or return the original if not found."""
return COLLEGE_ABBREVIATIONS.get(college_name, college_name)
try:
from src.config import (
get_connection,
find_student_by_rfid,
insert_rfid_log,
insert_violation,
has_student_violation_today,
enqueue_email_outbox,
get_due_email_outbox_entries,
get_email_outbox_entry,
mark_email_outbox_attempting,
mark_email_outbox_sent,
mark_email_outbox_failed,
)
except Exception as e:
get_connection = None
find_student_by_rfid = None
insert_rfid_log = None
insert_violation = None
has_student_violation_today = None
enqueue_email_outbox = None
get_due_email_outbox_entries = None
get_email_outbox_entry = None
mark_email_outbox_attempting = None
mark_email_outbox_sent = None
mark_email_outbox_failed = None
print(f"Warning: Database config not available: {e}")
RFID_AVAILABLE = False
try:
from src.rfid_scanner import (
get_rfid_uid,
start_rfid_monitoring,
stop_rfid_monitoring,
subscribe_to_rfid_events,
unsubscribe_from_rfid_events,
get_rfid_status,
_rfid_is_present,
set_rfid_enabled,
is_rfid_enabled,
)
except Exception as e:
print(f"Warning: RFID scanner not available: {e}")
def get_rfid_uid(*args, **kwargs):
return None, "RFID not available"
def start_rfid_monitoring():
pass
def stop_rfid_monitoring():
pass
def subscribe_to_rfid_events():
return None
def unsubscribe_from_rfid_events(*args):
pass
def get_rfid_status():
return {"available": False, "present": False, "enabled": False}
def _rfid_is_present():
return False
def set_rfid_enabled(enabled):
pass
def is_rfid_enabled():
return False
else:
RFID_AVAILABLE = True
app = Flask(__name__)
# Secret key for session management (can be overridden via environment variable)
app.secret_key = os.getenv('FLASK_SECRET_KEY', 'change-this-in-production')
# Flask-Mail configuration
# All email settings must be configured in .env file
app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER', 'smtp.gmail.com')
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', '587'))
app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'true').lower() in {'1','true','yes','on'}
app.config['MAIL_USE_SSL'] = os.getenv('MAIL_USE_SSL', 'false').lower() in {'1','true','yes','on'}
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER', os.getenv('MAIL_USERNAME'))
# Email timeout settings to prevent hanging
app.config['MAIL_TIMEOUT'] = int(os.getenv('MAIL_TIMEOUT', '10')) # 10 seconds timeout
app.config['MAIL_CONNECT_TIMEOUT'] = int(os.getenv('MAIL_CONNECT_TIMEOUT', '5')) # 5 seconds connection timeout
# Validate required email settings
if not app.config['MAIL_USERNAME'] or not app.config['MAIL_PASSWORD']:
print("⚠ WARNING: MAIL_USERNAME and/or MAIL_PASSWORD not set in .env file. Email notifications will not work.")
mail = Mail(app)
# Add charset=utf-8 to all JSON responses
@app.after_request
def add_charset_to_json(response):
"""Automatically add charset=utf-8 to JSON responses"""
if response.content_type == 'application/json':
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
# Register Blueprints
from routes import auth_bp, dashboards_bp, violations_bp, files_bp, camera_bp, rfid_bp, debug_bp, students_bp, settings_bp
app.register_blueprint(auth_bp)
app.register_blueprint(dashboards_bp)
app.register_blueprint(violations_bp)
app.register_blueprint(files_bp)
app.register_blueprint(camera_bp)
app.register_blueprint(rfid_bp)
app.register_blueprint(debug_bp)
app.register_blueprint(students_bp)
app.register_blueprint(settings_bp)
# Configure upload folder
UPLOAD_FOLDER = 'uploads'
RESULT_FOLDER = 'results'
VIOLATION_SUBDIR = 'violations'
VIOLATION_FOLDER = os.path.join(RESULT_FOLDER, VIOLATION_SUBDIR)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}
# Create necessary directories
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(RESULT_FOLDER, exist_ok=True)
os.makedirs(VIOLATION_FOLDER, exist_ok=True)
# Email outbox configuration
EMAIL_OUTBOX_POLL_SECONDS = int(os.getenv('EMAIL_OUTBOX_POLL_SECONDS', '15'))
EMAIL_OUTBOX_RETRY_DELAY_SECONDS = int(os.getenv('EMAIL_OUTBOX_RETRY_DELAY_SECONDS', '10')) # Reduced to 10 seconds for faster retries
EMAIL_OUTBOX_BATCH_SIZE = int(os.getenv('EMAIL_OUTBOX_BATCH_SIZE', '5'))
email_outbox_thread = None
email_outbox_thread_lock = threading.Lock()
def _normalize_outbox_attachment_path(path: str | None) -> str | None:
"""Store attachment paths as project-relative forward-slash paths."""
if not path:
return None
normalized = os.path.normpath(path)
if os.path.isabs(normalized):
try:
normalized = os.path.relpath(normalized, start=os.getcwd())
except Exception:
pass
return normalized.replace('\\', '/')
def _resolve_outbox_attachment_path(stored_path: str | None) -> str | None:
"""Convert stored attachment path back to absolute path."""
if not stored_path:
return None
normalized = os.path.normpath(stored_path)
if os.path.isabs(normalized):
return normalized
return os.path.join(os.getcwd(), normalized)
def _guess_mime_type(path: str) -> str:
mime, _ = mimetypes.guess_type(path)
return mime or 'application/octet-stream'
def _send_email_from_outbox_record(record: dict) -> tuple[bool, str | None]:
"""Send an email using data stored in an outbox record."""
if mail is None:
return False, "Mail extension is not initialized"
recipient = (record or {}).get('recipient')
subject = (record or {}).get('subject')
html_body = (record or {}).get('body_html')
plain_body = (record or {}).get('body_plain')
attachment_path = _resolve_outbox_attachment_path((record or {}).get('attachment_path'))
attachment_cid = (record or {}).get('attachment_cid')
if not recipient or not subject:
return False, "Recipient or subject missing"
sender = app.config.get('MAIL_DEFAULT_SENDER', app.config.get('MAIL_USERNAME'))
if not sender:
return False, "MAIL_DEFAULT_SENDER or MAIL_USERNAME is not configured"
try:
msg = Message(
subject=subject,
recipients=[recipient],
html=html_body if html_body else None,
body=plain_body if plain_body else None,
sender=sender
)
if attachment_path and os.path.exists(attachment_path):
disposition = 'inline' if attachment_cid else 'attachment'
headers = {'Content-ID': f'<{attachment_cid}>'} if attachment_cid else None
try:
with open(attachment_path, 'rb') as fp:
msg.attach(
filename=os.path.basename(attachment_path),
content_type=_guess_mime_type(attachment_path),
data=fp.read(),
disposition=disposition,
headers=headers
)
except Exception as attach_err:
debug_email(f"Attachment error for outbox email {record.get('email_id')}: {attach_err}")
with app.app_context():
mail.send(msg)
return True, None
except Exception as send_err:
return False, f"{type(send_err).__name__}: {send_err}"
def _process_outbox_record(record: dict, source: str = 'worker') -> bool:
"""Attempt to send a specific outbox record."""
if not record:
return False
email_id = record.get('email_id')
if not email_id or mark_email_outbox_attempting is None:
return False
if not mark_email_outbox_attempting(email_id):
return False
success, error_message = _send_email_from_outbox_record(record)
if success:
if mark_email_outbox_sent:
mark_email_outbox_sent(email_id)
debug_email(f"{source} sent email_outbox #{email_id} to {record.get('recipient')}")
return True
else:
if mark_email_outbox_failed:
mark_email_outbox_failed(email_id, error_message)
debug_email(f"{source} failed email_outbox #{email_id}: {error_message}")
return False
def email_outbox_worker():
"""Background worker that retries pending/failed emails when connectivity is available."""
if get_due_email_outbox_entries is None:
print("Email outbox worker disabled: database helpers unavailable")
return
print("Email outbox worker started")
while True:
try:
pending = get_due_email_outbox_entries(
limit=EMAIL_OUTBOX_BATCH_SIZE,
retry_delay_seconds=EMAIL_OUTBOX_RETRY_DELAY_SECONDS
) if get_due_email_outbox_entries else []
if not pending:
time.sleep(EMAIL_OUTBOX_POLL_SECONDS)
continue
debug_email(f"Email outbox worker found {len(pending)} email(s) to process")
for record in pending:
try:
email_id = record.get('email_id')
recipient = record.get('recipient')
status = record.get('status')
debug_email(f"Worker processing email_outbox #{email_id} to {recipient} (status: {status})")
_process_outbox_record(record, source='worker')
except Exception as record_err:
debug_email(f"Worker error for email_outbox #{record.get('email_id')}: {record_err}")
import traceback
debug_email(f"Traceback: {traceback.format_exc()}")
time.sleep(1)
except Exception as worker_err:
print(f"Email outbox worker exception: {worker_err}")
import traceback
traceback.print_exc()
time.sleep(EMAIL_OUTBOX_POLL_SECONDS)
def ensure_email_outbox_worker():
"""Start the email outbox worker thread if needed."""
global email_outbox_thread
if email_outbox_thread is not None and email_outbox_thread.is_alive():
return
if get_due_email_outbox_entries is None or mark_email_outbox_attempting is None:
return
with email_outbox_thread_lock:
if email_outbox_thread is not None and email_outbox_thread.is_alive():
return
email_outbox_thread = threading.Thread(
target=email_outbox_worker,
name="EmailOutboxWorker",
daemon=True
)
email_outbox_thread.start()
# Alerts cache for deans (per college)
dean_alerts_cache = {}
# Load YOLOv8n model for person detection
person_model = YOLO('models/yolov8n.pt')
# Load best.pt model for dress code detection
dress_model = YOLO('models/best.pt')
# Initialize BotSort tracker
tracker = BotSORT()
# Global variables for webcam
camera = None
detection_enabled = False
current_frame = None
frame_lock = threading.Lock()
selected_camera_id = 0
# Global variables for smooth detection (async processing)
detection_queue = None # Queue for frames to be processed
latest_detections = None # Latest detection results
latest_detection_frame = None # Frame that was used for latest detections
detection_results_lock = threading.Lock() # Lock for detection results
detection_thread = None # Background detection thread
# Global variables for RFID integration
rfid_event_queue = None
rfid_last_uid = None
rfid_present = False
rfid_lock = threading.Lock()
rfid_last_student = None # Holds last looked-up student dict or None
# Global variable for auto-sync control
auto_sync_enabled = True
auto_sync_lock = threading.Lock()
rfid_last_violation_ts = 0 # last violation timestamp to throttle duplicates
rfid_last_violation_uid = None # last UID that had a violation (for throttle check - only throttle same card)
rfid_current_uid_checks = 0 # number of detection checks for current RFID UID
rfid_current_uid_violated = False # whether a violation has been issued for current UID session
rfid_current_uid_compliant = False # whether compliant status was detected for current UID session (stops detection)
rfid_current_uid_snapshot_saved = False # whether a clean snapshot was saved for current UID
rfid_consecutive_non_compliant = 0 # counter for consecutive non-compliant detections
rfid_consecutive_compliant = 0 # counter for consecutive compliant detections
rfid_last_compliance_status = None # track last compliance status to detect changes
rfid_enabled = False # flag to completely disable RFID processing
rfid_violation_timeout = 30 # seconds after which violation flag resets (allows re-recording)
compliant_monitor_frame_counter = 0 # counter to periodically check for violations even when compliant
# Global variable for test mode
test_mode = False
test_mode_lock = threading.Lock()
# Schedule checking function
def is_system_scheduled_active():
"""Check if the system should be active based on the schedule settings"""
try:
if get_connection is None:
# If DB not configured, allow system to run
return True
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"SELECT setting_value FROM settings WHERE setting_key = 'system_schedule'"
)
result = cur.fetchone()
if not result or not result.get('setting_value'):
# No schedule set, system is always active
return True
import json
schedule = json.loads(result['setting_value'])
if not schedule or len(schedule) == 0:
# Empty schedule, system is always active
return True
# Get current day and time
now = datetime.now()
current_day = now.strftime('%A') # e.g., 'Monday'
current_time = now.strftime('%H:%M') # e.g., '14:30'
# Check if current time falls within any schedule entry for today
for entry in schedule:
if entry['day'] == current_day:
if entry['start_time'] <= current_time < entry['end_time']:
return True
# Not within any schedule
return False
finally:
conn.close()
except Exception as e:
error_msg = str(e)
if "Access denied" in error_msg or "1045" in error_msg:
print(f"⚠️ Database authentication error: {error_msg}")
print("⚠️ Please check:")
print(" 1. DB_PASSWORD environment variable is set correctly")
print(" 2. Your IP address is whitelisted in Aiven")
print(" 3. SSL certificate is properly configured")
else:
print(f"Error checking schedule: {e}")
# On error, allow system to run (fail open)
return True
# Auto-initialize camera
def initialize_camera():
global camera, selected_camera_id, detection_queue, detection_thread, latest_detections, latest_detection_frame
try:
camera = cv2.VideoCapture(selected_camera_id) # Use selected camera
if camera.isOpened():
print(f"Camera {selected_camera_id} initialized successfully")
# Initialize detection queue and start detection thread if not already running
if detection_queue is None:
detection_queue = queue.Queue(maxsize=2) # Small queue to prevent lag
latest_detections = None
latest_detection_frame = None
# Start detection worker thread
if detection_thread is None or not detection_thread.is_alive():
detection_thread = threading.Thread(target=detection_worker, daemon=True)
detection_thread.start()
print("Detection worker thread started")
return True
else:
print(f"Failed to initialize camera {selected_camera_id}")
camera = None
return False
except Exception as e:
print(f"Error initializing camera: {e}")
camera = None
return False
def initialize_rfid():
"""Initialize RFID monitoring"""
global rfid_event_queue
try:
# Start RFID monitoring
start_rfid_monitoring()
# Subscribe to RFID events
rfid_event_queue = subscribe_to_rfid_events()
print("RFID monitoring initialized successfully")
return True
except Exception as e:
print(f"Error initializing RFID: {e}")
return False
def update_rfid_enabled_based_on_schedule():
"""Update rfid_enabled flag based on schedule and test mode"""
global rfid_enabled, test_mode, test_mode_lock, camera
# Check test mode first
with test_mode_lock:
test_mode_active = test_mode
# If test mode is active, RFID should be disabled
if test_mode_active:
if rfid_enabled:
rfid_enabled = False
set_rfid_enabled(False)
print("RFID disabled: Test mode is active")
return
# Check schedule
is_active = is_system_scheduled_active()
if is_active:
# Within scheduled hours - enable RFID if camera is running
if camera is not None and camera.isOpened():
if not rfid_enabled:
rfid_enabled = True
set_rfid_enabled(True)
print("RFID enabled: Within scheduled hours")
else:
# Camera not running, disable RFID
if rfid_enabled:
rfid_enabled = False
set_rfid_enabled(False)
print("RFID disabled: Camera is not running")
else:
# Outside scheduled hours - disable RFID
if rfid_enabled:
rfid_enabled = False
set_rfid_enabled(False)
print("RFID disabled: Outside scheduled hours")
def rfid_event_handler():
"""Handle RFID events in background thread"""
global rfid_last_uid, rfid_present, detection_enabled, rfid_lock, rfid_last_student, rfid_consecutive_non_compliant, rfid_consecutive_compliant, rfid_last_compliance_status, rfid_last_violation_ts, camera, rfid_enabled, tracker, test_mode, test_mode_lock, rfid_current_uid_violated, rfid_current_uid_compliant, rfid_current_uid_snapshot_saved, rfid_last_violation_uid, compliant_monitor_frame_counter
while True:
try:
# Update RFID enabled status based on schedule and test mode
update_rfid_enabled_based_on_schedule()
# Skip RFID processing if test mode is active
with test_mode_lock:
test_mode_active = test_mode
if test_mode_active:
time.sleep(0.1) # Small delay to avoid busy waiting
continue
# Check if system is scheduled to be active - RFID only works during scheduled hours
if not is_system_scheduled_active():
time.sleep(0.1) # Small delay to avoid busy waiting
continue
if rfid_event_queue and rfid_enabled and camera is not None and camera.isOpened():
try:
event = rfid_event_queue.get(timeout=1.0)
except queue.Empty:
# Timeout - no event in queue, check current RFID status
current_present = _rfid_is_present()
with rfid_lock:
# Always check if card is not present and reset state accordingly
if not current_present:
# Card is not present - always reset state if we have any stale data
if rfid_present or rfid_last_uid is not None or rfid_last_student is not None:
# Card was present but now removed - reset all state
rfid_present = False
detection_enabled = False
rfid_last_student = None
rfid_last_uid = None # Reset UID so next scan is treated as new
rfid_current_uid_checks = 0
rfid_current_uid_violated = False
rfid_current_uid_compliant = False
rfid_just_violated = False
rfid_just_compliant = False
rfid_consecutive_non_compliant = 0
rfid_consecutive_compliant = 0
rfid_last_compliance_status = None
rfid_current_uid_snapshot_saved = False
rfid_last_violation_ts = 0
rfid_last_violation_uid = None
# Reset tracker when RFID card is removed
tracker = BotSORT()
print("RFID Card removed - Detection DISABLED - Tracker reset - All state cleared")
elif current_present and not rfid_present:
# Card just appeared
rfid_present = True
print("RFID Card present - Waiting for UID event")
continue # Skip to next iteration
if event['type'] == 'uid':
with rfid_lock:
incoming_uid = event['uid']
old_uid = rfid_last_uid
# Check if this is a new card (different UID or no previous UID)
# IMPORTANT: Check BEFORE updating rfid_last_uid to compare with old value
is_same_uid = (rfid_present and rfid_last_uid is not None and rfid_last_uid == incoming_uid)
# If this is a NEW card (different UID or no previous UID), reset all counters
# Also check if UID actually changed (safety check)
uid_changed = (old_uid is None or old_uid != incoming_uid)
if not is_same_uid or uid_changed:
if not is_same_uid:
debug_rfid(f"New RFID card detected - Old UID: {old_uid}, New UID: {incoming_uid}")
else:
debug_rfid(f"UID changed detected (safety check) - Old UID: {old_uid}, New UID: {incoming_uid}")
# Reset all counters and flags for new card - MUST reset compliant flag to enable detection
rfid_current_uid_checks = 0
rfid_current_uid_violated = False
rfid_current_uid_compliant = False # CRITICAL: Reset compliant flag for new card
rfid_consecutive_non_compliant = 0
rfid_consecutive_compliant = 0 # Reset compliant count for new card
rfid_last_compliance_status = None
rfid_current_uid_snapshot_saved = False
rfid_last_violation_ts = 0
rfid_last_violation_uid = None # Reset violation UID tracking for new card
compliant_monitor_frame_counter = 0 # Reset compliant monitoring counter
# Reset tracker for new RFID scan
tracker = BotSORT()
# Clear detection queue to prevent old frames from being processed for new card
if detection_queue is not None:
try:
# Drain the queue by getting all items
while True:
try:
detection_queue.get_nowait()
detection_queue.task_done()
except queue.Empty:
break
except Exception as e:
debug_rfid(f"Error clearing detection queue: {e}")
debug_rfid("Tracker reset for new RFID scan - All flags and counters reset (including compliant count)")
else:
debug_rfid(f"Same RFID card still present - UID: {incoming_uid}")
# Update UID and present flag after reset logic
rfid_last_uid = incoming_uid
rfid_present = True
# Perform DB lookup and log
try:
student = None
if get_connection is not None and rfid_last_uid:
student = find_student_by_rfid(rfid_last_uid) if find_student_by_rfid else None
if student and insert_rfid_log:
insert_rfid_log(rfid_last_uid, student.get('student_id'), 'valid')
elif insert_rfid_log:
insert_rfid_log(rfid_last_uid, None, 'unregistered')
rfid_last_student = student
except Exception as e:
print(f"RFID DB handling error: {e}")
# Capture a clean snapshot on each RFID scan (no overlays/bounding boxes) - only once per UID
# This should happen for both cases: when student is found and when not found
snapshot = None
with frame_lock:
if current_frame is not None:
snapshot = current_frame.copy()
save_snapshot = False
with rfid_lock:
if not rfid_current_uid_snapshot_saved:
save_snapshot = True
rfid_current_uid_snapshot_saved = True
# Only enable detection and capture images if RFID has a record in database
# Only disable detection if student already has a violation recorded today (not based on session flag)
if rfid_last_student is not None:
student_id = rfid_last_student.get('student_id')
# Check if student already has a violation today (check database, not session flag)
has_violation_today = False
if has_student_violation_today and student_id:
try:
has_violation_today = has_student_violation_today(student_id)
except Exception as e:
debug_violation(f"Error checking violation today: {e}")
with rfid_lock:
# Check if UID changed (for detection enabling logic)
uid_changed_for_detection = (old_uid is None or old_uid != incoming_uid)
# If student already has violation today, mark as violated and disable detection
if has_violation_today:
rfid_current_uid_violated = True
rfid_current_uid_compliant = False # Reset compliant flag
detection_enabled = False
print(f"RFID Card detected: {event['uid']} - Student found: {rfid_last_student.get('name', 'Unknown')} - Detection DISABLED (student already has violation today)")
# Enable detection for new UID (use uid_changed check for safety)
elif not is_same_uid or uid_changed_for_detection:
# New card - always enable detection (flags were reset above, including rfid_current_uid_compliant)
# CRITICAL: Explicitly reset ALL flags to ensure clean state for new card
rfid_current_uid_violated = False
rfid_current_uid_compliant = False # MUST be False to allow detection
detection_enabled = True
print(f"RFID Card detected: {event['uid']} - Student found: {rfid_last_student.get('name', 'Unknown')} - Detection ENABLED (new card)")
debug_rfid(f"NEW CARD - detection_enabled={detection_enabled}, rfid_current_uid_violated={rfid_current_uid_violated}, rfid_current_uid_compliant={rfid_current_uid_compliant}, is_same_uid={is_same_uid}")
# Same card - only disable if violation today OR if compliant detected
elif rfid_current_uid_compliant:
# Same card, but compliant already detected - keep detection paused via compliant flag
# Don't change detection_enabled here - let it stay as is
print(f"RFID Card detected: {event['uid']} - Student found: {rfid_last_student.get('name', 'Unknown')} - Detection remains paused (student is compliant)")
debug_rfid(f"SAME CARD COMPLIANT - detection_enabled={detection_enabled}, rfid_current_uid_violated={rfid_current_uid_violated}, rfid_current_uid_compliant={rfid_current_uid_compliant}")
else:
# Same card, no violation today, and not compliant - enable detection
# This allows re-detection if the same card is scanned again (unless violation today)
rfid_current_uid_compliant = False # Ensure it's False
detection_enabled = True
print(f"RFID Card detected: {event['uid']} - Student found: {rfid_last_student.get('name', 'Unknown')} - Detection ENABLED (same card, no violation today)")
debug_rfid(f"SAME CARD - detection_enabled={detection_enabled}, has_violation_today={has_violation_today}, rfid_current_uid_violated={rfid_current_uid_violated}, rfid_current_uid_compliant={rfid_current_uid_compliant}")
# Save snapshot if we have one and haven't saved it yet
try:
if snapshot is not None and save_snapshot:
ts = int(time.time())
sid = (rfid_last_student or {}).get('student_id', 'unknown')
snap_name = f"scan_{ts}_{sid}.jpg"
os.makedirs(RESULT_FOLDER, exist_ok=True)
snap_path = os.path.join(RESULT_FOLDER, snap_name)
cv2.imwrite(snap_path, snapshot)
debug_rfid(f"Saved clean RFID snapshot (non-violation): {snap_path}")
# Create a duplicate with dress code bounding boxes (no labels/text)
try:
boxed = snapshot.copy()
# Run dress model directly on the full snapshot
results = dress_model(snapshot)
for r in results:
boxes = r.boxes
if boxes is None:
continue
for box in boxes:
conf = float(box.conf[0]) if hasattr(box, 'conf') else 0.0
if conf < 0.50:
continue
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
# Use a constant blue box for dress items to distinguish from violations
cv2.rectangle(boxed, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 2)
# Label with class name and confidence
try:
class_id = int(box.cls[0]) if hasattr(box, 'cls') else None
class_name = dress_model.names[class_id] if class_id is not None else 'item'
except Exception:
class_name = 'item'
label_text = f"{class_name} {conf*100:.0f}%"
label_scale = 0.4
label_thickness = 1
(tw, th), _ = cv2.getTextSize(label_text, cv2.FONT_HERSHEY_SIMPLEX, label_scale, label_thickness)
pad = 3
bx1, by1 = int(x1), int(y1)
# Draw filled background above the box if room, otherwise inside
rect_top = by1 - th - pad*2 if by1 - th - pad*2 > 0 else by1 + pad
rect_bottom = rect_top + th + pad*2
cv2.rectangle(boxed, (bx1, rect_top), (bx1 + tw + pad*2, rect_bottom), (255, 0, 0), -1)
cv2.putText(boxed, label_text, (bx1 + pad, rect_bottom - pad), cv2.FONT_HERSHEY_SIMPLEX, label_scale, (255, 255, 255), label_thickness)
boxed_name = f"scan_{ts}_{sid}_dress.jpg"
boxed_path = os.path.join(RESULT_FOLDER, boxed_name)
cv2.imwrite(boxed_path, boxed)
debug_rfid(f"Saved dress-boxed RFID snapshot: {boxed_path}")
except Exception as e:
debug_rfid(f"Error creating dress-boxed RFID snapshot: {e}")
elif snapshot is None and save_snapshot:
debug_rfid("No current_frame to save RFID snapshot")
except Exception as e:
debug_rfid(f"Error saving RFID snapshot: {e}")
if rfid_last_student is None:
# No student found - disable detection
with rfid_lock:
detection_enabled = False
rfid_current_uid_compliant = False
print(f"RFID Card detected: {event['uid']} - No student found in database - Detection DISABLED")
else:
# Event received but not a 'uid' event (shouldn't happen, but handle it)
with rfid_lock:
rfid_present = False
detection_enabled = False
rfid_last_student = None
rfid_last_uid = None # Reset UID so next scan is treated as new
rfid_current_uid_checks = 0
rfid_current_uid_violated = False
rfid_current_uid_compliant = False
rfid_consecutive_non_compliant = 0
rfid_consecutive_compliant = 0
rfid_last_compliance_status = None
rfid_current_uid_snapshot_saved = False
rfid_last_violation_ts = 0
rfid_last_violation_uid = None # Reset violation UID tracking when card removed
# Reset tracker when RFID card is removed
tracker = BotSORT()
print("RFID Card removed - Detection DISABLED - Tracker reset - All state cleared")
elif rfid_event_queue:
# RFID disabled or camera off, just consume events without processing
try:
rfid_event_queue.get(timeout=1.0)
except queue.Empty:
pass
except Exception as e:
# Other exceptions - log and continue
print(f"Error in RFID event handler: {e}")
import traceback
traceback.print_exc()
# Check if RFID is disabled or camera is off - ensure RFID is inactive
if not rfid_enabled or camera is None or not camera.isOpened():
with rfid_lock:
if rfid_present:
rfid_present = False
detection_enabled = False
rfid_last_student = None
rfid_last_uid = None
rfid_current_uid_checks = 0
rfid_current_uid_violated = False
rfid_current_uid_compliant = False
rfid_consecutive_non_compliant = 0
rfid_consecutive_compliant = 0
rfid_last_compliance_status = None
rfid_current_uid_snapshot_saved = False
rfid_last_violation_ts = 0
rfid_last_violation_uid = None
# Reset tracker when RFID is disabled or camera is off
tracker = BotSORT()
print("RFID disabled or camera off - RFID forced inactive - Tracker reset")
time.sleep(0.1)
# Initialize RFID on startup (camera will be initialized when user starts it)
# initialize_camera() # Commented out to keep camera off by default
# initialize_rfid() # Commented out - RFID will start with camera
# Start RFID event handler thread (but RFID monitoring won't start until camera is on)
rfid_thread = threading.Thread(target=rfid_event_handler, daemon=True)
rfid_thread.start()
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def format_dress_class(class_name):
"""Format dress class names for better readability"""
class_mapping = {
'polo_shirt': 'Polo Shirt',
'pants': 'Pants',
'shoes': 'Shoes',
'blouse': 'Blouse',
'skirt': 'Skirt',
'doll_shoes': 'Doll Shoes'
}
return class_mapping.get(class_name, class_name.replace('_', ' ').title())
def validate_dress_code(detected_items, gender='male'):
"""Validate dress code compliance based on gender requirements"""
# Define gender-specific dress code requirements
if gender == 'male':
required_items = ['polo_shirt', 'pants', 'shoes']
item_names = {
'polo_shirt': 'Polo Shirt',
'pants': 'Pants',
'shoes': 'Shoes'
}
else: # female
required_items = ['blouse', 'skirt', 'doll_shoes']
item_names = {
'blouse': 'Blouse',
'skirt': 'Skirt',
'doll_shoes': 'Doll Shoes'
}
# Get detected item classes
detected_classes = [item['class'].lower().replace(' ', '_') for item in detected_items]
# Check compliance
compliance_status = {}
for required_item in required_items:
if required_item in detected_classes:
compliance_status[required_item] = {
'present': True,
'name': item_names[required_item],
'status': 'compliant:'
}
else:
compliance_status[required_item] = {
'present': False,
'name': item_names[required_item],
'status': 'non-compliant:'
}
# Calculate compliance percentage
present_count = sum(1 for status in compliance_status.values() if status['present'])
compliance_percentage = (present_count / len(required_items)) * 100
# Determine overall status
if compliance_percentage == 100:
overall_status = "COMPLIANT"
status_color = "success"
elif compliance_percentage >= 66:
overall_status = "PARTIALLY COMPLIANT"
status_color = "warning"
else:
overall_status = "NON-COMPLIANT"
status_color = "danger"
return {
'compliance_status': compliance_status,
'compliance_percentage': compliance_percentage,
'overall_status': overall_status,
'status_color': status_color,
'required_items': required_items,
'detected_items': detected_classes
}
def detect_dress_code(person_crop, gender: str = 'male'):
"""Detect dress code items for a person crop using best.pt model"""
try:
# Run dress code detection on person crop
results = dress_model(person_crop)
dress_items = []
dress_detections = []
for r in results:
boxes = r.boxes
if boxes is not None:
for box in boxes:
class_id = int(box.cls[0])
confidence = float(box.conf[0])
# Apply per-class confidence thresholds (shoes/doll shoes at 0.50, others at 0.70)
class_name = dress_model.names[class_id]
normalized_class = class_name.lower().replace(' ', '_')
threshold = 0.50 if normalized_class in ['shoes', 'doll_shoes'] else 0.70
if confidence >= threshold:
dress_detections.append({
'class': class_name,
'confidence': round(confidence, 2)
})
# Group by class and get best confidence for each dress item
class_confidences = {}
for detection in dress_detections:
class_name = detection['class']
confidence = detection['confidence']
if class_name not in class_confidences or confidence > class_confidences[class_name]:
class_confidences[class_name] = confidence
# Convert to list of dress items with formatted names
for class_name, confidence in class_confidences.items():
dress_items.append({
'class': format_dress_class(class_name),
'confidence': confidence
})
# Sort by confidence (highest first)
dress_items.sort(key=lambda x: x['confidence'], reverse=True)
# Validate dress code compliance per provided gender
validation_result = validate_dress_code(dress_items, gender=(gender or 'male').lower())
return validation_result
except Exception as e:
print(f"Error in dress code detection: {e}")
return {
'compliance_status': {},
'compliance_percentage': 0,
'overall_status': 'ERROR',
'status_color': 'danger',
'required_items': [],
'detected_items': []
}
return []
def detect_persons_with_dress(image_path):
"""Two-stage detection: first detect persons, then detect dress code"""
try:
# Read image for tracking
image = cv2.imread(image_path)
# Stage 1: Detect persons using YOLOv8n
results = person_model(image_path)
# Process person detections
detections = []
for r in results:
boxes = r.boxes