DRESS (Dress-code Recognition Surveillance System) is a Flask-based web application that uses computer vision (YOLOv8) and RFID technology to automatically monitor and track dress code violations in an educational institution.
- Backend: Flask (Python web framework)
- Database: MySQL (Local primary, Aiven cloud backup)
- Computer Vision: YOLOv8 (Ultralytics) for person detection + custom model for dress code detection
- Tracking: Bot-SORT algorithm for person tracking
- Frontend: HTML/CSS/JavaScript (vanilla, no framework)
- Email: Flask-Mail for SMTP notifications
- PDF Generation: ReportLab (optional)
-
Main Application (
app.py)- Flask app initialization
- Global state management
- Background thread orchestration
- Detection pipeline coordination
-
Route Blueprints (
routes/)- Modular route organization
- Separation of concerns by feature
-
Core Modules (
src/)- Database configuration
- RFID scanner integration
- Bot-SORT tracker
- Email templates
-
ML Models (
models/)yolov8n.pt: Person detectionbest.pt: Custom dress code detection
- Purpose: All application operations
- Connection: Always used for reads/writes
- Performance: Fast, no network dependency
- Configuration:
LOCAL_DB_*environment variables
- Purpose: Periodic backup only
- Sync Direction: Local → Aiven (one-way)
- Sync Frequency: Every 5 minutes (when available)
- Availability: Optional, system works without it
- Configuration:
DB_*environment variables
-
admins- User accounts with role-based access
- Roles:
security,dean,osas,guidance - Password hashing for security
-
students- Student information
- RFID UID mapping
- College, program, year level
-
violations- Dress code violation records
- Links to students
- Status tracking (pending, resolved, etc.)
- Strike count (1st, 2nd, 3rd offense)
- Follow-up email flag
-
rfid_logs- RFID card scan history
- Tracks valid/unregistered cards
-
settings- Key-value configuration storage
- Schedule settings
- Auto-sync enabled/disabled flag
-
email_outbox- Email queue for offline operation
- Stores emails that need to be sent
- Status:
pending,sending,sent,failed - Tracks attempt count, last attempt time, and error messages
- Links to violations via
violation_idforeign key
- Model: YOLOv8n (person class only)
- Purpose: Detect and track people in frame
- Tracking: Bot-SORT algorithm assigns track IDs
- Output: Bounding boxes with track IDs
- Model: Custom
best.ptmodel - Input: Cropped person regions from Stage 1
- Processing: Only processes track_id == 1 (primary tracked person)
- Output: Dress code compliance status per item
The system checks for:
- Upper body clothing (shirt, polo, etc.)
- Lower body clothing (pants, skirt, etc.)
- Footwear (shoes)
- Gender-specific requirements
- COMPLIANT: All required items present
- PARTIALLY COMPLIANT: Some items missing
- NON-COMPLIANT: Critical items missing
- NO_DETECTION: Person not detected or out of frame
Requirements for Recording:
- Valid RFID card must be present
- Student must be registered in database
- Requires 3 consecutive violation detections
- Only records once per RFID scan session
- Resets counter when status changes to COMPLIANT
- Does NOT reset on temporary NO_DETECTION
Violation States:
rfid_consecutive_non_compliant: Counter for violationsrfid_consecutive_compliant: Counter for compliancerfid_current_uid_violated: Flag if violation recordedrfid_current_uid_compliant: Flag if compliant detected
Asynchronous Recording:
- Violation recording happens in a background thread (
threading.Thread) - Prevents blocking the detection worker
- Email queuing is non-blocking (only queues, never sends synchronously)
- System continues operating even if violation recording fails
- Hardware: USB RFID reader
- Protocol: Serial communication
- Event System: Queue-based event handling
-
Card Detection
- RFID reader detects card
- UID extracted and queued
- Event handler processes in background
-
Student Lookup
- UID matched against
studentstable - Student information loaded
- RFID log entry created
- UID matched against
-
Detection Control
- Detection enabled only when valid card present
- Disabled if student already has violation today
- Disabled if compliant status detected
- Reset when new card detected
-
Violation Linking
- Violations linked to student via RFID UID
- Strike count calculated automatically
- Email notifications sent to student
rfid_present: Card currently detectedrfid_last_uid: Last detected UIDrfid_last_student: Student info for current cardrfid_enabled: System-level enable/disable flag
Controls when RFID and detection systems are active.
- Days: Monday through Sunday (toggle on/off)
- Time Range: Start time and end time
- Storage:
settingstable with JSON format
- Within Schedule: RFID and detection active
- Outside Schedule: RFID and detection disabled
- Test Mode: Overrides schedule (for testing)
- Background thread checks schedule every 10 seconds
- Updates
rfid_enabledflag based on schedule - Visual indicators in UI show schedule status
- Frequency: Every 10 seconds
- Purpose: Enable/disable RFID based on schedule
- Location:
app.py
- Type: Event-driven (processes queue)
- Purpose: Handle RFID card detections
- Actions: Student lookup, detection control, logging
- Type: Queue-based processing
- Purpose: Process video frames for detection
- Input: Frame queue from camera feed
- Output: Detection results stored in shared state
- Frequency: Checks every 15 seconds
- Purpose: Process queued emails and retry failed sends
- Batch Size: Processes up to 5 emails per cycle
- Retry Delay: 10 seconds for failed emails
- Status Management: Updates email status in
email_outboxtable - Error Handling: Logs errors and marks emails as failed
- Location:
app.pyline ~306
- Frequency: Daily (24 hours)
- Purpose: Send follow-up emails for old violations
- Criteria: Violations 3+ days old, status='pending', followup_sent=0
- Duplicate Prevention: Sets
followup_sent=1before sending
- Frequency: Checks every 60 seconds, syncs every 5 minutes
- Purpose: Backup local database to Aiven
- Conditions: Only syncs when Aiven available and auto-sync enabled
- Debug Logging: Comprehensive logging for troubleshooting
- Type: Spawned per violation (background thread)
- Purpose: Record violation asynchronously without blocking detection
- Actions: Database insert, email queuing
- Location:
app.py_maybe_record_violation()function
- Dashboard:
index.html(main security dashboard) - Features:
- Real-time camera feed with detection overlay
- RFID status monitoring
- Schedule configuration
- Test mode toggle
- Auto-sync control
- System status indicators
- Dashboard:
dean_dashboard.html - Features:
- View violations for their college only
- Filter and search violations
- Update violation status
- Generate PDF reports
- Analytics and statistics
- Dashboard:
osas_dashboard.html - Features:
- University-wide violation oversight
- All colleges visible
- Advanced analytics
- Report generation
- System-wide statistics
- Dashboard:
guidance_dashboard.html - Features:
- Student counseling support
- Violation management
- Student information access
- Support tools
The system includes a robust email queuing mechanism that ensures emails are sent even when the system is offline:
- Stores all emails that need to be sent
- Tracks status:
pending,sending,sent,failed - Records attempt count and last error for debugging
- Links to violations via
violation_idforeign key
- Violation Detected: Email details are queued in
email_outboxtable - Asynchronous Queuing: Violation recording happens in background thread (non-blocking)
- Background Worker:
email_outbox_worker()processes queued emails every 15 seconds - Retry Logic: Failed emails are retried after 10 seconds
- Automatic Recovery: When connectivity returns, all queued emails are sent automatically
- Frequency: Checks every 15 seconds
- Batch Size: Processes up to 5 emails per cycle
- Retry Delay: 10 seconds for failed emails
- Status Management: Updates email status (
pending→sending→sent/failed) - Error Handling: Logs errors and marks emails as failed with error message
- Trigger: When violation is recorded
- Process: Queued in
email_outboxtable (not sent immediately) - Recipient: Student email from database
- Content: Violation details, strike count, proof image
- Template:
generate_violation_email_body() - Offline Behavior: Queued and sent when connectivity returns
- Trigger: Automatic (3+ days after violation, if still pending)
- Purpose: Remind student of unresolved violation
- Duplicate Prevention:
followup_sentflag in database - Scheduler: Background thread runs daily
- SMTP: Configured via
.envfile - Library: Flask-Mail
- Templates: HTML email templates in
src/email_templates.py - Offline Support: Emails queued when offline, sent automatically when online
enqueue_email_outbox(): Queue email for sendingget_due_email_outbox_entries(): Get emails ready to send (pending or failed after retry delay)mark_email_outbox_attempting(): Mark email as being sentmark_email_outbox_sent(): Mark email as successfully sentmark_email_outbox_failed(): Mark email as failed with error message
POST /login- User loginPOST /logout- User logout
GET /video_feed- Video stream with detectionsPOST /camera/start- Start cameraPOST /camera/stop- Stop cameraGET /camera/status- Camera status
GET /rfid/status- RFID status and student infoPOST /rfid/enable- Enable RFIDPOST /rfid/disable- Disable RFID
GET /dean/violations- Dean violations (college-filtered)GET /osas/violations- OSAS violations (all)GET /guidance/violations- Guidance violationsPOST /violations/<id>/update- Update violation statusGET /violations/<id>/report- Generate PDF reportPOST /violations/followup- Send follow-up emails
GET /students- List studentsPOST /students- Create studentPUT /students/<id>- Update studentDELETE /students/<id>- Delete student
GET /api/settings/schedule- Get schedulePOST /api/settings/schedule- Update scheduleGET /api/settings/schedule/check- Check if currently activeGET /api/settings/auto-sync- Get auto-sync statusPOST /api/settings/auto-sync- Toggle auto-sync
GET /uploads/<filename>- Serve uploaded filesGET /results/<filename>- Serve result imagesGET /violations/<filename>- Serve violation images
uploads/: User-uploaded imagesresults/: Processed detection imagesresults/violations/: Violation proof images
static/css/: Stylesheetsstatic/js/: JavaScript modulesstatic/images/: UI images
templates/: HTML templates for each dashboard- Jinja2 templating for dynamic content
# Local Database (Primary)
LOCAL_DB_HOST=localhost
LOCAL_DB_PORT=3306
LOCAL_DB_USER=root
LOCAL_DB_PASSWORD=your_password
LOCAL_DB_NAME=dress
# Email Configuration
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USE_TLS=True
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password# Aiven Database (Backup)
DB_HOST=your-aiven-host.aivencloud.com
DB_PORT=22870
DB_USER=avnadmin
DB_PASSWORD=your_password
DB_NAME=dress
DB_SSL_CA=certs/ca.pem
DB_SSL_REQUIRED=true
DB_SSL_DISABLED=false- Purpose: Track people across frames
- Implementation:
src/botsort_tracker.py - Output: Consistent track IDs for same person
- Usage: Only track_id == 1 is processed for dress detection
- Check if RFID student present
- Check if already violated today → skip
- Check detection results for worst status
- Increment violation counter if non-compliant
- Increment compliance counter if compliant
- Record violation after 3 consecutive violations
- Reset counters when status changes
- Check if auto-sync enabled (global flag)
- Check if Aiven available (cached 30 seconds)
- Check if 5 minutes passed since last sync
- Connect to both databases
- Sync all tables (truncate + insert)
- Update last sync time
- Log results
- Session-based authentication
- Password hashing (Werkzeug)
- Role-based access control (RBAC)
- Route-level role checks
- College-level filtering for deans
- Security role required for system settings
- SQL injection prevention (parameterized queries)
- File upload validation
- Secure password storage
- Detection runs in background thread
- Camera feed not blocked by detection
- Queue-based frame processing
- Latest results cached for display
- Violation recording happens in separate thread
- Detection worker never blocks on database operations
- Email queuing is non-blocking (only queues, never sends synchronously)
- System remains responsive even during violation recording
- Connection pooling via
get_connection() - Local database for all operations (fast)
- Backup sync doesn't block operations
- Aiven availability cached (30 seconds)
- Detection results cached
- Dean alerts cached per college
- Graceful degradation if Aiven unavailable
- Local database errors logged and handled
- Transaction rollback on sync failures
- Continues processing if frame fails
- Logs errors without crashing
- Fallback to previous detection results
- Handles unregistered cards gracefully
- Continues operation if RFID unavailable
- Logs all RFID events
- Offline Operation: System works fully offline
- Email Queuing: Emails queued when offline, sent when online
- Retry Logic: Failed emails retried automatically after 10 seconds
- Error Logging: Email errors stored in
email_outbox.last_error - Non-Blocking: Email failures don't block violation recording
- Network Detection: Detects online/offline status
- Timeout Handling: All fetch requests have 7-second timeout
- Request Deduplication: Prevents concurrent identical requests
- Error Recovery: Automatically retries failed requests
- Video Feed Recovery: Auto-restarts video feed on errors or network reconnection
- Localhost Endpoints: Local endpoints (
/rfid/status,/api/settings/schedule/check) work offline
- RFID status checks
- Detection processing
- Violation recording
- Auto-sync operations
- Schedule checks
rfid_scanner.log: RFID scanner events- Console output: Application logs
routes/debug.py: Debug utilities- System state inspection
- Manual trigger endpoints
- Overrides schedule restrictions
- Allows testing outside scheduled hours
- Toggle in Security dashboard
- Visual indicator when active
scripts/sync_database.py: Interactive sync tool- Choose sync direction
- Select tables to sync
- View sync status
- Python 3.8+
- MySQL database
- Webcam (for detection)
- RFID reader (optional)
- Internet connection (for Aiven backup, optional)
- Load environment variables
- Initialize database connections
- Load ML models
- Start background threads
- Initialize Flask app
- Register blueprints
- Start web server
- Schedule checker: Immediate
- RFID handler: Immediate
- Detection worker: Immediate
- Follow-up email: 10 second delay
- Auto-sync: 15 second delay
- Single Person Tracking: Only track_id == 1 is processed for dress detection
- Schedule Dependency: Detection disabled outside scheduled hours (unless test mode)
- RFID Required: Violations only recorded when valid RFID card present
- 3-Strike Rule: Requires 3 consecutive violations before recording
- Aiven Dependency: Backup sync requires Aiven availability (optional, system works without it)
- ✅ Violation detection and recording
- ✅ RFID scanning and student identification
- ✅ Camera feed display
- ✅ Dashboard updates (localhost endpoints)
- ✅ Database operations (local database)
- ✅ Email queuing (emails stored for later sending)
- ⏳ Email notifications (queued in
email_outboxtable) - ⏳ Cloud database sync (resumes when online)
- Email worker checks every 15 seconds for queued emails
- Retries failed emails after 10 seconds
- Sends all queued emails when connectivity returns
- Frontend automatically detects network reconnection and updates UI
- Multi-person tracking and detection
- Real-time notifications (WebSocket)
- Mobile app integration
- Advanced analytics dashboard
- Machine learning model retraining pipeline
- Multi-camera support
- Cloud deployment options
- Monitor auto-sync logs
- Check email delivery
- Review violation records
- Update student database
- Backup local database
- Check logs for errors
- Verify schedule configuration
- Test RFID reader connection
- Verify camera access
- Check email SMTP settings
- System: DRESS v2
- Python: 3.8+
- Flask: Latest
- YOLOv8: Ultralytics
- Database: MySQL 8.0+
Last Updated: Based on current codebase analysis Documentation covers all major system components and workflows