AI-Powered Face Recognition Attendance System with Multi-Distance Detection & Automatic Absent Marking
An advanced automated attendance management system using ArcFace and RetinaFace for face recognition, supporting multiple distance categories and automatic absent marking.
- Features
- System Architecture
- Technology Stack
- Prerequisites
- Installation
- Database Setup
- Configuration
- Running the Application
- Usage Guide
- Project Structure
- API Documentation
- Troubleshooting
- Contributing
- License
- Acknowledgments
- Multi-Distance Face Recognition - Detects faces from very close to far distances (20px-150px+)
- Dual Model System - Uses ArcFace for speed and RetinaFace for accuracy
- 4-Level Recognition Strategy - Individual embeddings β Adjacent categories β Category averages β Global fallback
- Automatic Absent Marking - Auto-marks absent students after class ends (5-minute grace period)
- Subject-Specific Attendance - Separate tables for each subject with proper tracking
- Real-Time Face Recognition - Live webcam feed with instant detection
- Duplicate Prevention - Prevents marking same student twice in same time slot
- Personal attendance dashboard
- Subject-wise attendance view
- Overall attendance statistics
- Attendance percentage calculation
- View captured face images
- Download attendance reports (PDF/Excel/Word)
- Subject-specific dashboard (teachers only see their assigned subject)
- Start/Stop face recognition
- Manual attendance marking with validation
- Image upload for face testing
- Real-time recognition feed
- View captured face images
- Automatic absent marking control
- Backfill past absences
- Download class reports (PDF/Excel/Word)
- Student-wise detailed reports
- Session-based authentication
- Role-based access control (Student/Teacher)
- Subject-level authorization for teachers
- Duplicate attendance prevention
- Time-based validation
- SQL injection protection
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FastAPI Server β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Auth β β Attendance β β Reports β β
β β Management β β Marking β β Generation β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Face Recognition Engine β
β ββββββββββββ ββββββββββββ ββββββββββββββββββ β
β β ArcFace β βRetinaFaceβ βMulti-Distance β β
β β Buffalo-Lβ β β β Recognition β β
β ββββββββββββ ββββββββββββ ββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MySQL Database β
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ β
β β Students β β Teachers β β Student β β
β β β β β β Detail β β
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ β
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ β
β βStudent β β DummyTime β βSubject-wise β β
β βEmbeddings β β Table β β Attendance β β
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- FastAPI - Modern Python web framework
- Python 3.8+ - Core programming language
- MySQL 8.0+ - Relational database
- InsightFace (ArcFace) - Primary face recognition model
- RetinaFace - High-accuracy face detection
- OpenCV - Computer vision operations
- NumPy - Numerical computations
- ReportLab - PDF generation
- OpenPyXL - Excel generation
- python-docx - Word document generation
- Schedule - Background task scheduling for absent marking
- HTML5/CSS3 - Modern responsive UI
- JavaScript (Vanilla) - Client-side interactions
- Jinja2 - Server-side templating
Before installation, ensure you have:
- Python 3.8 or higher (Download)
- MySQL 8.0 or higher (Download)
- Webcam (for face recognition)
- Git (Download)
- 4GB+ RAM (recommended for face recognition models)
- Good lighting (for better face detection accuracy)
git clone https://github.com/Git-Suraj-hub/Vision_Mark.git
cd pythonProject4# Windows
python -m venv venv
venv\Scripts\activate
# Linux/Mac
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtrequirements.txt:
fastapi==0.104.1
uvicorn[standard]==0.24.0
mysql-connector-python==8.2.0
insightface==0.7.3
retinaface==0.0.13
opencv-python==4.8.1.78
numpy==1.24.3
scipy==1.11.4
python-multipart==0.0.6
schedule==1.2.0
reportlab==4.0.7
openpyxl==3.1.2
python-docx==1.1.0
torch==2.1.0
onnxruntime==1.16.3Linux (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install -y libgl1-mesa-glx libglib2.0-0macOS:
brew install opencvmysql -u root -pCREATE DATABASE face_detection;
USE face_detection;Execute the following SQL files in order:
# 1. Create base tables
mysql -u root -p face_detection < database/01_base_tables.sql
# 2. Create subject attendance tables
mysql -u root -p face_detection < database/02_subject_tables.sql
# 3. Create embeddings table
mysql -u root -p face_detection < database/03_embeddings_table.sql
# 4. Add category-specific columns
mysql -u root -p face_detection < database/04_category_columns.sql
# 5. Create timetable
mysql -u root -p face_detection < database/05_timetable.sql-- Sample student
INSERT INTO students (username, password, name, enrollment_no, class)
VALUES ('student1', 'pass123', 'John Doe', 'MUR2300001', 'CSE-A');
-- Sample teacher
INSERT INTO teachers (username, password, name, class, subject)
VALUES ('teacher1', 'pass123', 'Dr. Smith', 'CSE-A', 'Theory of Computation');
-- Sample timetable entry (24/7 for testing)
INSERT INTO DummyTimeTable (Day, Start_Time, End_Time, Subject, Teacher, Room)
VALUES ('Monday', '00:00:00', '23:59:59', 'Theory of Computation', 'Dr. Smith', 'A101');Edit the following files with your MySQL credentials:
backend/server.py:
def get_db_conn():
return mysql.connector.connect(
host="localhost",
user="root",
password="YOUR_PASSWORD_HERE", # Change this
database="face_detection"
)backend/Recognize2.py:
self.conn = mysql.connector.connect(
host="localhost",
user="root",
password="YOUR_PASSWORD_HERE", # Change this
database="face_detection"
)Place your images in:
backend/static/images/logo.png
backend/static/images/favicon.png
Image specifications:
- Logo: 512x512px, transparent PNG
- Favicon: 32x32px or 64x64px PNG
Temporary solution:
# Use placeholder images
cp demo.png backend/static/images/logo.png
cp demo.png backend/static/images/favicon.pngBefore using the system, you need to generate face embeddings for students.
# 1. Organize photos in Dataset folder:
Dataset/
βββ MUR2300001_JohnDoe/
β βββ 1.jpg
β βββ 2.jpg
β βββ 3.jpg
βββ MUR2300002_JaneSmith/
β βββ 1.jpg
β βββ 2.jpg
βββ ...
# 2. Run embedding generator
python student_Embedding.py
# 3. Calculate category averages
python student_detail_embedding.pypython generate_embeddings.py
# Choose option 3 (Webcam capture)
# Enter enrollment number and name
# Press SPACE to capture# Development mode (with auto-reload)
uvicorn backend.server:app --reload --host 0.0.0.0 --port 8000
# Production mode
uvicorn backend.server:app --host 0.0.0.0 --port 8000 --workers 4Open your browser and navigate to:
http://localhost:8000
Student:
- Username:
student1 - Password:
pass123
Teacher:
- Username:
teacher1 - Password:
pass123
-
Login
- Go to http://localhost:8000
- Click "Student Login"
- Enter credentials
-
View Attendance
- Dashboard shows overall statistics
- Click subject tabs to view subject-wise attendance
- See present/absent records with timestamps
-
Login
- Go to http://localhost:8000
- Click "Teacher Login"
- Enter credentials
-
Start Face Recognition
- Click "Start Recognition" button
- Webcam will open
- Students' faces will be detected automatically
- Attendance marked in real-time
-
Manual Marking
- Enter student enrollment number
- Select status (Present/Absent)
- Click "Mark Attendance"
-
Absent Marking
- Click "Mark Absences NOW" for immediate marking
- Click "Backfill Past Absences" to recover past data
smart-attendance-system/
βββ backend/
β βββ server.py # FastAPI server
β βββ Recognize2.py # Face recognition engine
β βββ static/
β β βββ css/
β β β βββ style.css # Styles
β β βββ images/
β β β βββ logo.png
β β β βββ favicon.png
β β βββ captures/ # Face captures (auto-created)
β β βββ uploads/ # Test uploads (auto-created)
β βββ templates/
β βββ index.html # Landing page
β βββ login_student.html
β βββ login_teacher.html
β βββ student.html # Student dashboard
β βββ teacher.html # Teacher dashboard
βββ database/
β βββ 01_base_tables.sql
β βββ 02_subject_tables.sql
β βββ 03_embeddings_table.sql
β βββ 04_category_columns.sql
β βββ 05_timetable.sql
βββ Dataset/ # Student photos
β βββ ENROLLMENT_NAME/
β βββ *.jpg
βββ student_Embedding.py # Generate embeddings
βββ student_detail_embedding.py # Calculate averages
βββ generate_embeddings.py # Interactive embedding tool
βββ absent_marker.py # Standalone absent marker
βββ requirements.txt
βββ README.md
βββ LICENSE
Login
POST /api/login
Content-Type: multipart/form-data
role=student&username=student1&password=pass123Logout
POST /api/logoutGet Student Attendance
GET /api/student/attendance/{enrollment_no}Get Teacher's Subject Attendance
GET /api/teacher/attendance
Cookie: session={token}Mark Attendance Manually
POST /api/mark_attendance
Content-Type: multipart/form-data
enrollment_no=MUR001&status=PresentStart Webcam
POST /api/start_webcam
Cookie: session={token}Stop Webcam
GET /api/stop_webcam
Cookie: session={token}Test Image
POST /api/test_image
Content-Type: multipart/form-data
file={image_file}Mark Absences Now
POST /api/mark_absences_now
Cookie: session={token}Backfill Absences
POST /api/backfill_absences
Content-Type: multipart/form-data
days_back=7Get Current Subject
GET /api/current_subjectGet Current User
GET /api/current_user
Cookie: session={token}Problem: Face recognition models fail to load
Solution:
# Models download automatically on first run
# Ensure good internet connection
# Models are cached in ~/.insightface/
# If issues persist:
rm -rf ~/.insightface/
python -c "from insightface.app import FaceAnalysis; app = FaceAnalysis(name='buffalo_l'); app.prepare(ctx_id=0)"Problem: Webcam fails to start
Solution:
# Try different camera index in Recognize2.py
cv2.VideoCapture(0) # Change 0 to 1, 2, etc.
# Check camera permissions
# Windows: Settings > Privacy > Camera
# Mac: System Preferences > Security > Camera
# Linux: Check /dev/video* permissionsProblem: Faces not being recognized
Solution:
- Ensure good lighting
- Face should be frontal and clearly visible
- Minimum face size: 40x40 pixels
- Check if embeddings exist for student
- Verify camera is working:
python -c "import cv2; cap=cv2.VideoCapture(0); print(cap.isOpened())"
Problem: Cannot connect to MySQL
Solution:
# Check MySQL is running
sudo service mysql status
# Test connection
mysql -u root -p
# Verify database exists
mysql -u root -p -e "SHOW DATABASES LIKE 'face_detection';"Problem: Automatic attendance marking fails
Solution:
- Verify DummyTimeTable has entry for current day/time
- Check teacher's subject matches current class
- Ensure face embeddings exist for student
- Check server logs for errors
- Verify absent marking scheduler is running
Problem: System uses too much resources
Solution:
# In Recognize2.py, increase frame skip
skip_frames = 5 # Process every 5th frame instead of 2
# Reduce detection size
self.arcface_app.prepare(ctx_id=0, det_size=(320, 320)) # Instead of (640, 640)- Good Lighting - Well-lit environment improves detection
- Multiple Photos - 5+ photos per student at different distances
- Quality Photos - Clear, frontal face images
- Regular Updates - Re-generate embeddings periodically
- Frame Skipping - Adjust
skip_framesin Recognize2.py - Detection Size - Reduce
det_sizefor faster processing - Database Indexing - Add indexes on frequently queried columns
- Hardware - Use GPU if available (change to
CUDAExecutionProvider)
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow PEP 8 for Python code
- Add comments for complex logic
- Update documentation for new features
- Test thoroughly before submitting
This project is licensed under the MIT License - see the LICENSE file for details.
- InsightFace - Face recognition models
- RetinaFace - Face detection
- FastAPI - Web framework
- OpenCV - Computer vision library
- ReportLab - PDF generation
For issues and questions:
- Check Troubleshooting section
- Search existing GitHub Issues
- Create a new issue with:
- Detailed description
- Steps to reproduce
- Error messages/logs
- System information
- Mobile app (Android/iOS)
- Real-time dashboard updates
- Email notifications
- SMS alerts for low attendance
- Biometric authentication
- Multi-language support
- Dark mode
- Advanced analytics
- Export to Google Sheets
- Integration with LMS
- CPU: Dual-core 2.0 GHz
- RAM: 4 GB
- Storage: 2 GB free space
- OS: Windows 10, Ubuntu 18.04, macOS 10.14+
- CPU: Quad-core 2.5 GHz+
- RAM: 8 GB+
- Storage: 5 GB free space
- GPU: NVIDIA GPU with CUDA support (optional)
- Recognition Accuracy: 85-95% (depending on distance)
- Processing Speed: 2-5 FPS (CPU) / 15-30 FPS (GPU)
- Face Detection Range: 20px to 150px+ face width
- Supported Students: Unlimited (tested with 500+)
- Concurrent Users: 50+ (with proper hardware)
This system was developed as part of an academic project. If you use this system in your research or project, please cite:
@software{smart_attendance_system,
author = {Your Name},
title = {Smart Attendance System: AI-Powered Face Recognition},
year = {2025},
url = {https://github.com/yourusername/smart-attendance-system}
}
This system is designed for LOCAL USE ONLY and should be deployed in a controlled environment. For production deployment:
- Implement HTTPS
- Use password hashing (bcrypt)
- Add CSRF protection
- Implement rate limiting
- Regular security audits
- Comply with data privacy regulations (GDPR, etc.)
If you find this project useful, please consider giving it a star β
Made with β€οΈ for educational institutions
