0% found this document useful (0 votes)
100 views118 pages

Project Book

The document outlines a project proposal for a Face Recognition Attendance System developed by Yash Jaiswar as part of his Bachelor of Science in Information Technology. The system aims to automate attendance tracking using facial recognition technology, enhancing accuracy and efficiency while reducing manual errors. The report includes sections on objectives, technology survey, system design, implementation, and results, demonstrating the system's applicability across various sectors such as education and corporate environments.

Uploaded by

garojic983
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views118 pages

Project Book

The document outlines a project proposal for a Face Recognition Attendance System developed by Yash Jaiswar as part of his Bachelor of Science in Information Technology. The system aims to automate attendance tracking using facial recognition technology, enhancing accuracy and efficiency while reducing manual errors. The report includes sections on objectives, technology survey, system design, implementation, and results, demonstrating the system's applicability across various sectors such as education and corporate environments.

Uploaded by

garojic983
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROFORMA FOR THE APPROVAL PROJECT PROPOSAL

PNR No.: Roll No:

1. Name of the Student

2. Title of the Project

3. Name of the Guide

4. Teaching experience of the Guide

5. Is this your first Submission? Yes No

Signature of the Student Signature of the Guide

Date: Date:

Signature of the Coordinator

Date:

1
FACE RECOGNITION ATTENDANCE
SYSTEM
A Project Report
Submitted in partial fulfillment of the
Requirements for the award of the
Degree of

BACHELOR OF SCIENCE (INFORMATION TECHNOLOGY)


By
YASH JAISWAR

(Seat Number: 3022712)

Under the esteemed guidance of


Mrs. Awantika Deshpande
Asst. Prof.

DEPARTMENT OF INFORMATION TECHNOLOGY


DNYAN GANGA EDUCATION TRUST’S
DEGREE COLLEGE OF ARTS, COMMERECE & SCIENCE
Affiliated to University of
Mumbai THANE, 400615
MAHARASHTRA

2024-2025
DNYAN GANGA EDUCATION TRUST’S
DEGREE COLLEGE OF ARTS, COMMERCE & SCIENCE
Affiliated to University of Mumbai
THANE-MAHARASHTRA-400615

DEPARTMENT OF INFORMATION TECHNOLOGY

CERTIFICATE

This is to certify that the project entitled “FACE RECOGNITION ATTENDANCE


SYSTEM” is bonafied work of Yash Jaiswar bearing Seat No: 3033712
Submitted in partial fulfillment of the requirements for the award of Degree of BACHELOR
OF SCIENCE in INFORMATION TECHNOLOGY from University of Mumbai

Internal Guide Coordinator

External Examiner

Date: College Seal


Abstract
Face recognition technology is a powerful tool that has gained recognition in numerous
fields which include protection, surveillance, and biometric identification

A Face Recognition Attendance System (FRAS) offers automated reliable, efficient, and
convenient way to record and track attendance in numerous places such as schools, workplaces,
and events. This system works by capturing facial images of individuals and comparing them
with a pre-registered database to identify and record attendance

The main objective of this system is to automate the attendance technique, eliminate methods
which include paper-based registers and decrease the probabilities of errors or fraud. By
utilizing the strength of machine learning algorithms and facial recognition technology, and
FRAS guarantees accurate, actual-time attendance monitoring and generating desired result by
utilizing analytics technique

This abstract provides an overview of the advantages and capability of a Face Recognition
Attendance System, demonstrating how it can streamline attendance manipulates methods and
provides protection and overall performance in various environments.
ACKNOWLEDGEMENT

The goal is best achieved by treading the path of excellence with discipline and deep
insight. We would never have succeeded in completing our task without the cooperation,
encouragement and help provided to us by various teachers and guides.
With a deep sense of gratitude, we express our sincere thanks to our esteemed and
worthy guide, Mrs. Awantika Deshpande, for her valuable guidance in carrying out this
project under her effective supervision, encouragement, enlightenment and cooperation.
We feel indebted to express our deep sense of gratitude towards Dr. Bhavika R.
Karkera (I/C Principal) who has been a constant source of inspiration for us throughout this
project.
We would also like to thank all faculty members and non-teaching staff for their kind
support without vacillation.
The acknowledgement would be incomplete if we did not mention the emotional
support and blessings provided by our parents and friends. We had a pleasant enjoyable and
fruitful company with them. Last but not the least we would like to thank all the people who
directly or indirectly helped us with this project.
DECLARATION

I hereby declare that the project entitled, “Face Recognition Attendance System”
done at Dnyan Ganga College, has not been in any case duplicated to submit to any other
university for the award of any degree. To the best of my knowledge other than me, no one
has submitted to any other university.
The project is done in partial fulfillment of the requirements for the award of degree of
BACHELOR OF SCIENCE (INFORMATION TECHNOLOGY) to be submitted
as final semester project as part of our curriculum

Signature of the Student

Yash Jaiswar
TABLE OF CONTENTS
SR. NO. PAGE NO.
CHAPTER 1: INTRODUCTION
1.1 Background……………………………………………………………………………2
1.2 Objectives…………………………………………………………………………….3
1.3 Purpose, Scope, and Applicability…………………………………………………….4
1.3.1 Purpose……………………………………………………………………...4
1.3.2 Scope…………………………………………………………………….…4
1.3.3 Applicability……………………………………………………….……….4
1.4 Achievements…………………………………………………………………………5
1.5 Organization of Report……………………………………………………………….6
CHAPTER 2: SURVEY OF TECHNOLOGIES
2.1 System Requirement……………………………………………………………….…8
2.1.1 Front-End Technologies…………………………………………….………8
2.1.2 Back-End Technologies…………………………………………………….9
2.1.3 Database Management…………………………………………………….11
2.1.4 Software Requirements………………………………………….…………15
2.1.5 Hardware Requirements……………………………………………………16
CHAPTER 3: REQUIREMENTS AND ANALYSIS
3.1 Problem Definition………………………………………………………………….19
3.2 Requirements Specification………………………………………………………….20
3.3 Planning and Scheduling…………………………………………………………….21
3.4 Software and Hardware Requirements………………………………………………23
3.5 Preliminary Product Description…………………………………………………….24
3.6 Conceptual Models………………………………………………………………….24
CHAPTER 4: SYSTEM DESIGN
4.1 Basic Modules……………………………………………………………………….25
4.2 Data Design………………………………………………………………………….37
4.2.1 Schema Design…………………………………………………………….40
4.2.2 Data Integrity and Constraints…………………………………………….41
4.3 Procedural Design……………………………………………………………………42
4.3.1 Logic Diagrams…………………………………………………………….42
4.3.2 Data Structures…………………………………………………………….43
1
4.3.3 Algorithms Design………………………………………………….………44
4.4 User interface design…………………………………………………………….……47
4.5 Security Issues………………………………………………………………….…. ….50
4.6 Test Cases Design…………………………………………………………….….…….52
CHAPTER 5: IMPLEMENTATION AND TESTING
5.1 Coding Details………………………………………………………………………....55
5.2 Testing Approach………………………………………………………………………92
5.2.1 Unit Testing………………………………………………………………….92
5.2.2 Integrated testing…………………………………………………………….95
5.3 Modifications and Improvements…………………………………………….……….95
5.4 Test Cases……………………………………………………………………….….…95
CHAPTER 6: RESULTS AND DISCUSSION
6.1 Test Reports……………………………………………………………………………98
6.2 User Documentation………………………………………………………………….98
CHAPTER 7: CONCLUSIONS
7.1 Conclusion……………………………………………………………………………104
7.1.1 Significance of the System………………………………………………….104
7.2 Limitations of the System…………………………………………………………….104
7.3 Future Scope of the Project…………………………………………………………...106
REFERENCES

2
LIST OF TABLES

SR.NO. PAGE.NO.
Table 1: Users Table……………………………………………………………………….37
Table 2: Attendance Table……………………………………………............................................38
Table 3: Settings Table…………………………………………………………………………….38
Table 4: Face Recognition Table...………………………………………………...........................39

3
4
CHAPTER 1
INTRODUCTION

1
1.1 Background
A face recognition attendance system is designed to automate the process of
recording attendance using facial recognition technology. This approach has gained popularity
due to its efficiency and accuracy, addressing many limitations found in traditional attendance
methods like roll calls or manual sign-ins.

Automated facial recognition was pioneered in the 1960s by Woody Bledsoe, Helen Chan
Wolf, and Charles Bisson, whose work focused on teaching computers to recognize human
faces. Their early facial recognition project in facial recognition was called "man- machine"
because a human was required first to locate in an image the coordinates of facial features before
their use in computerized recognition.

In 1993, DARPA and the Army Research Laboratory began a face recognition technology
program called FERET to develop "automatic face recognition capabilities" that could be used
in the real world for "helping security, intelligence and law enforcement personnel perform
their duties more effectively and efficiently." Face recognition systems that had been tested in
research labs were evaluated and the FERET tests found that while the performance of
existing automated facial recognition systems varied, a handful of existing methods could
viably be used to recognize faces in still images taken in a controlled environment.

The late 1990s and early 2000s saw a rise in biometric authentication systems for security
applications. As these technologies matured, they began to be adopted in various fields,
including security, banking, and later, in educational settings.

2
1.2 Objectives

The Face Recognition Attendance System is designed with a host of key goals in mind:
to enhance efficiency and accuracy on attendance recording, for security, education, and
banking fields. One of the main objectives of the system is the reduce amounts of efforts and
hours spent by humans in tracking attendance, which reduces errors to a minimum and saves
user time. Here are the primary objectives:

 Automated Attendance Recording: To eliminate manual attendance processes by


automatically recording attendance through facial recognition, reducing the time spent
on administrative tasks.
 Enhancement of Accuracy: To provide a highly accurate method for tracking
attendance, minimizing errors associated with manual entries and proxy attendance.
 Real-Time Monitoring: To offer real-time updates on attendance status, allowing
educators and administrators to quickly identify late arrivals or absentees.
 Reduction of Operational Costs: To decrease operational costs by removing the need
for manual labor in attendance tracking and reducing the resources needed for data
processing and management.
 Secure and Reliable Identification: To enhance security by ensuring that only
authorized individuals are marked present, thus preventing unauthorized entry and
potential fraud, such as buddy punching.
 Adaptability Across Environments: To ensure that the system can be effectively
implemented in various environments, whether in classrooms, corporate offices, or
public events, making it a versatile solution for diverse attendance management needs.
 Support for Analytics and Insights: To enable institutions and organizations to
analysis attendance patterns over time, helping them identify trends and make informed
decisions regarding resource allocation and student or employee engagement.

3
1.3 Purpose, Scope, and Applicability
1.3.1 Purpose
The purpose of a face recognition attendance system It includes a number of key objectives
that contribute to making the attendance tracking more effective and accurate. Here are the
key purposes of this project: Automation of Attendance Tracking, Increased Accuracy, Real-
Time Updates, Real-Time Updates, Improved Data Management, Efficiency in
Administrative Processes, providing User-Friendly Experience, Support for Analytics and
Insights and Adaptability and Versatility. Overall, face recognition attendance can be
developed to ensure efficiency, accuracy, and safety for attendance tracking, hence this tool
is much needed in any organization that wants to upgrade its procedural operations.

1.3.2 Scope
The scope of a face recognition attendance system encompasses a robust integration of
advanced biometric technology aimed at simplifying attendee tracking across businesses. This
system will provide user the help which enabling real-time attendance recording and reporting
presences of other in various fields. It is designed to be very user-friendly, with the user
interface accessible on both mobile and desktop for convenience to the administrator and
employee. Furthermore, the scope includes scalability to support a range of organizational
sizes, from small businesses to large enterprises, while also providing data analytics features
to discern attendance trends and patterns that aid in decision-making.

1.3.3 Applicability
A face recognition attendance system is highly applicable across various sectors,
enhancing operational efficiency and accuracy. In educational institutions, it automates
attendance tracking, saving time and reducing administrative tasks. The technology also
benefits event management by simplifying guest check-ins and enhancing security.
Additionally, it aids healthcare by tracking patient visits while ensuring compliance with
regulations. Overall, these systems improve accountability, security, and resource
management, making them essential tools for modern organizations while adhering to ethical
standards regarding biometric data use.

4
1.4 Achievements
The implementation of a face recognition attendance system and significantly
transforming traditional attendance tracking methods across various sectors. First and
foremost, these systems have drastically reduced the time and effort spent on manual
attendance processes, allowing for real-time recording and instant reporting. This automation
minimizes human error and enhances accuracy, leading to better data integrity for both payroll
and performance evaluation.

Another key achievement is the enhanced resource management provided by the application.
By allowing for real-time recording and instant reporting this system provide protection against
unauthorized access in organization.

Organizations implementing these systems have reported increased employee productivity


and satisfaction due to streamlined workflows and fewer interruptions Overall, the face
recognition attendance system has set a new standard in organizational efficiency, security,
and data management.

5
1.5 Organization of Report
The report is structured as follows:

 Chapter 1: Introduction: This chapter outlines the significance of automation in


attendance tracking and introduces the advantages of using facial recognition
technology. It highlights the motivation behind the project and the objectives it aims
to achieve through the development of the Face Recognition Attendance System.
 Chapter 2: Literature Review: This chapter presents an in-depth analysis of existing
attendance tracking systems and facial recognition technologies. It critically examines
their limitations and builds the rationale for designing a more efficient and accurate
solution using advanced techniques.
 Chapter 3: System Design: This chapter describes the structural design of the
proposed system, covering both hardware and software components. It includes
camera specifications, face detection and recognition algorithms, and the design of the
database used for attendance data storage and retrieval.
 Chapter 4: Implementation: This chapter focuses on the development and
deployment process of the system. It discusses the step-by-step implementation
including installation, system configuration, and integration with existing
infrastructure, offering technical insights into how the system was brought to life.
 Chapter 5: Results and Evaluation: This chapter evaluates the system’s
performance using key metrics such as recognition accuracy, processing speed, and
user experience. Results are supported with visual representations like charts and
tables to showcase system efficiency.
 Chapter 6: Discussion and Conclusion: This chapter reflects on the broader
implications of the system, discusses potential limitations, and suggests future
improvements. It also provides recommendations for further research and outlines
how the system can be adapted for broader institutional use.

6
CHAPTER 2
SURVEY OF TECHNOLOGIES

7
In building the "Face Recognition Attendance" system, the following technologies and
tools are employed to ensure smooth functionality, efficiency, and a good user experience.
These technologies are grouped into front-end, back-end, database, software, and hardware
requirements.
A survey of technologies for a face recognition attendance system involves exploring various
components and methodologies that enable the implementation of such systems. Here’s an
overview of key technologies and considerations:

2.1 System Requirement:


In the context of developing a Face Recognition Attendance System, the selection of
appropriate technologies is vital for ensuring system accuracy, real-time performance, seamless
integration, and ease of maintenance. Chapter 2 provides a detailed survey of the technologies
employed in building the system, covering both front-end and back-end development, image
processing libraries, and database management tools. This survey helps in understanding the
rationale behind selecting specific technologies, their advantages, and how they collaborate to
deliver an effective and efficient attendance tracking solution.

The development of the Face Recognition Attendance System involves several critical
technologies that contribute to its functionality, speed, and user experience. This chapter
outlines the key components utilized in the project, including front-end GUI tools, face
detection and recognition libraries, back-end programming languages, and database systems.
The integration of these technologies ensures the system can accurately recognize individuals,
log attendance data securely, and offer a user-friendly interface for administrators and users
alike.

2.1.1 Front-End Technologies


The frontend is what users see and interact with. It’s all about the visual interface and user
experience—everything from layout and navigation to color schemes and widgets. In Python,
Tkinter and CustomTkinter can serve as powerful frontend libraries for building desktop
applications. Tkinter is the standard Python GUI toolkit. It’s included with most Python
installations, so, you can start creating windows, labels, buttons, and input fields right away—
no extra dependencies required.

CustomTkinter builds on Tkinter to give your apps a more modern look. With pre-built hemes
(dark, light, system) and sleek widgets, CustomTkinter helps you break away from the dated
feel of default Tkinter interfaces.

8
2.1.2 Back-End Technologies
The back end is the backbone of the application, responsible for business logic, server-side
operations, and database management.

 PYTHON
Python is a popular high-level general purpose programming language kw readability and
versatility. It was created by Guido van Rossum and first released in 1991 here are some
key points about Python

1. Readability and Simplicity: Python's syntax is designed to be clear and intuitive,


often resembling plain English. This focus on readability allows developers to write
code more quickly and maintain it more easily over time. The use of indentation to
define code blocks encourages a clean, organized structure, making it accessible to
beginners and experienced programmers alike.

2. Interpreted and Interactive: As an interpreted language, Python executes code line-


by-line, which is beneficial for debugging and testing. The interactive mode, often
accessed through the Python shell or Jupyter notebooks, allows developers to
experiment with code snippets in real-time. This feature fosters a hands-on learning
environment, making it a popular choice for educational purposes.

3. Cross-Platform: Python's cross-platform nature means that code written on one


operating system can run on others without modification. This flexibility allows
developers to work in diverse environments and ensures that applications can reach a
wider audience. Python’s compatibility extends to various platforms, including
mobile devices, servers, and cloud services.

4. Extensive Standard Library: Python's standard library is one of its greatest


strengths, offering a wide range of modules and functions for tasks like file I/O,
system calls, and even web protocols. This comprehensive set of tools means that
developers can focus on solving specific problems rather than reinventing the wheel,
accelerating the development process and improving productivity.

9
5. Dynamically Typed: With dynamic typing, Python allows developers to assign
values to variables without explicitly declaring their types. This feature simplifies
coding, but it also requires careful management of variable types to avoid runtime
errors. The flexibility of dynamic typing can speed up the development process,
especially during prototyping and iterative development.
development process, especially during prototyping and iterativedevelopment.

6 Object-Oriented Programming (OOP): Python fully supports object- oriented


programming, which helps in organizing code into reusable components. By
utilizing classes and objects, developers can model real- world entities and
relationships, enhancing code modularity and readability. OOP principles, such as
inheritance and polymorphism, enable the creation of complex systems while
promoting code reuse and maintainability.

7 Community and Ecosystem: The Python community is vast and diverse,


contributing to an ever-expanding ecosystem of libraries and frameworks. Popular
frameworks like Django and Flask for web development, Pandas and NumPy for
data analysis, and TensorFlow and PyTorch for machine learning have emerged from
this collaborative environment. Additionally, community forums, conferences, and
meetups provide opportunities for learning and sharing knowledge, making Python
a continuously evolving language.

8 Versatile Applications: Python is used across various domains, including:


 Web Development: Frameworks like Django and Flask facilitate building robust web
applications with minimal effort.
 Data Science and Analysis: Libraries such as Pandas, NumPy, and Matplotlib allow
for powerful data manipulation and visualization.
 Machine Learning and AI: Tools like TensorFlow, Koras, and Scikit- learn enable
developers to create advanced machine learning models.
 Automation and Scripting: Python is often used for automating repetitive tasks, such
as web scraping and file manipulation.
 Game Development: Libraries like Pygame make it easier to develop games and
multimedia applications.

10
 Data Integrity: SQL ensures data consistency and integrity, especially with features like
foreign key constraints, which help maintain relationships between different tables (e.g.,
users and borrowed books).

 Database

SQLite

SQLite is a game-changer if you’re looking for a lightweight, self-contained


RDBMS. Let’s break down how SQLite stacks up, similar to what we’ve seen with
MySQL, but with its own unique spin:

What is SQLite?
SQLite is an open-source, embedded database engine that’s totally different from traditional
client– server models like MySQL, SQL Server, or Oracle Database. Instead of running as a
separate service, the SQLite engine gets embedded right into your application. This means no
server setup, no configuration hassles—just a simple, single file that holds your entire database.
It’s super popular for mobile apps, small to medium websites, and even in desktop applications,
thanks to its speed and simplicity.

11
Key Features of SQLite

1. Lightweight and Zero-Configuration


SQLite is designed to be “just there” without any hassle. You don’t need to set up a server
or manage extra processes—perfect if you’re aiming for a frictionless experience across
different devices.

2. Database Operations
SQLite supports all the essential operations on tables, rows, columns, and indexes. This
means it’s straightforward to create, read, update, and delete data without needing a full-
blown server infrastructure.

3. Relational Structure
Just like other relational databases, SQLite lets you define relationships between tables
(i.e., rows and columns). This setup keeps your data well-organized and ensures
everything remains meaningful and easy to query.

4 Referential Integrity
SQLite supports foreign keys and referential integrity to keep table relationships
consistent—though you might need to enable this feature in your database settings. This is
crucial for maintaining data accuracy in multi-table setups.

5 Automatic Indexing
While SQLite doesn’t automatically update indexes as aggressively as some server-based
systems, it does offer robust tools for creating and managing indexes. This approach helps
keep your queries snappy and your data retrieval efficient.
6 SQL Support
SQLite allows you to run a broad range of SQL queries for fetching and manipulating data.
You can even combine multiple tables in a single query to produce dynamic, powerful
results, all within a self-contained environment.

12
How Does SQLite Work?
SQLite is unlike traditional databases such as MySQL, which rely on a client–server model.
Instead, SQLite operates as a serverless, embedded system, meaning it runs within your
application rather than as a separate service. Below is a breakdown of its core components
and workflow.

1 Database Creation:
SQLite creates a single database file on disk, containing all tables, indexes, and data. This
single-file design makes it exceptionally portable and easy to integrate into various
environments, from mobile apps to desktop software.

2 Application Integration:
Because SQLite is embedded, your application interacts directly with the SQLite library. Whether
you’re using a graphical user interface (GUI), a command line, or a specific programming language, all
SQL queries are executed within the same process as your application. This setup removes the need for
separate network communication and simplifies deployment.

3 Data Processing:
The SQLite engine processes all SQL instructions internally. When your
application sends a query, SQLite reads from or writes to the database file and
then returns the results—no external server required. This direct
communication reduces latency and keeps performance high, especially for
smaller-scale or single-user applications.

5 Lightweight Architecture:
SQLite’s design philosophy prioritizes minimal overhead without
sacrificing essential database functionality. Because it doesn’t require a
dedicated server or additional services, it’s well-suited for devices with
limited resources, such as mobile phones and IoT devices. Its small
footprint also streamlines development, since you don’t have to configure
or maintain a separate server environment.

13
14
2.1.4 Software Requirements:

To develop, test, and run the "Face Recognition Attendance" system, the following
software tools are essential:
 Operating System:
The development environment is built on Windows 10 Home Single Language,
which provides a stable platform for coding and testing.
 Visual Studio Code:
This is the primary code editor used for writing HTML, CSS, JavaScript, and PHP. It
supports numerous extensions and offers debugging, version control, and
customization features, making it an ideal environment for application development

15
 Excel:
Microsoft Excel is a powerful spreadsheet program that is part of the Microsoft Office suite.
It is widely used for data analysis, financial modelling, and various business applications.
With its robust features, Excel allows users to organize, format, and calculate data
effective

 Face Recognition Algorithms


o Haar Cascades: An early method for face detection using machine learning, suitable
for real-time applications but less accurate than newer methods.
o LBPH (Local Binary Patterns Histograms): A method for face recognition that uses
the texture of images, effective in varying lighting conditions.

 Deep Learning Models:


o CNNs (Convolutional Neural Networks): Highly effective for feature extraction
and classification in face recognition tasks.
o Pre-trained Models: Models like VGGFace, FaceNet, and OpenFace can be fine-
tuned for specific applications

16
2.1.5 Hardware Requirements:

The hardware specifications ensure that the development environment can handle the
application’s requirements and run smoothly.
 Device name: DESKTOP-3GJCSNE.

The device used for development is a desktop computer with sufficient processing power
and memory to manage the application’s demands.
 Name of Processor:

The system is powered by the Intel(R) Core (TM) i5-10400F CPU @ 2.90GHz
2.90 GHz, providing adequate performance for running developmenttools, virtual
environments, and local servers.
 RAM:

With 8 GB of RAM, the system can handle multitasking, allowing the development
environment, database server, and web server to run simultaneously without performance
degradation.
 System type:

The system runs on a 64-bit operating system, x64-based processor, ensuring


compatibility with modern software tools and allowing the application to be developed
efficiently.

 Hardware Components

Cameras: High-resolution cameras are essential for capturing clear images. Options
include:

Webcams: Affordable and suitable for small setups.

IP Cameras: Ideal for remote access and larger environments.

Processing Units: Powerful CPUs or GPUs are needed for real-time processing,
especially when using deep learning models

17
CHAPTER 3
REQUIREMENTS AND ANALYSIS

18
3.1 Problem Definition
A face recognition attendance system aims to automate attendance tracking in work field like
schools and workplaces by using face recognition technology to its maximum, but they face
several operational challenges.

Key Problems:
Accuracy and Reliability: Achieving high levels of accuracy in facial recognition can be
challenging. Factors such as lighting conditions, varying angles, age, and temporary changes
in appearance (like facial hair or glasses) can lead to false positives or negatives, undermining
the trustworthiness of the system.

Privacy and Data Security: The use of biometric data raises significant privacy concerns.
Ensuring that the system complies with data protection regulations, such as GDPR, is crucial.
Users may be wary of how their facial data is collected, stored, and used, necessitating
transparent policies and robust security measures to protect this sensitive information.

Integration with Existing Systems: Integration of the facial recognition attendance system
with current institutional or organizational infrastructure, like learning management systems
or HR tools, can be complex. This requires ensuring compatibility and smooth data flow
between different platforms, which can be technically challenging.

Environmental Variability: The performance of a face recognition attendance system can


be significantly affected by external environmental factors. Changes in lighting, background
noise, or even weather conditions (for outdoor settings) can hinder the system's ability to
accurately recognize faces.

19
3.2 Requirements Specification
To address the challenges outlined in the problem definition, the "Face
Recognition Attendance System” must meet the following functional
and non- functional requirements:

1. Functional Requirements
User Authentication: The system must allow users to register by capturing multiple facial
images under diverse conditions (varied lighting, angles, and expressions) to enhance
recognition accuracy.
Real-Time Attendance Marking: The system must provide real-time attendance
marking by instantly comparing the captured facial data with the registered users during
check-in.
Error Handling: The system must handle recognition errors gracefully, offering options
for manual attendance marking in case of failure to identify a user.
Reporting and Analytics: He system must generate customizable and downloadable
attendance reports, including features like absenteeism trends, average attendance rates,
and user statistics.
User Management: The system should provide functionalities for administrators to
manage user profiles, including adding, updating, or deleting user records.
Integration: The system must integrate with existing attendance management systems
or databases to allow seamless data exchange and storage.

2. Non-Functional Requirements

Performance: The system must process facial recognition within 2 seconds per individual
under normal operating conditions to ensure efficient attendance marking.

Accuracy: The system should achieve a recognition accuracy rate of at least 95% to
minimize errors in attendance marking.

Scalability: The system must be able to scale to support at least 1,000 concurrent users
without degradation in performance Non-Functional Requirements

Performance: The system must process facial recognition within 2 seconds per
individual under normal operating conditions to ensure efficient attendance marking.

20
Accuracy: The system should achieve a recognition accuracy rate of at least 95% to
minimize errors in attendance marking.
Scalability: The system must be able to scale to support at least 1,000 concurrent
users without degradation in performance.
Security: Biometric data must be encrypted during transmission and storage to prevent
unauthorized access. The system should also implement user access controls to protect
sensitive information.

Usability: The user interface must be intuitive and accessible, allowing users of
varying technical proficiency to navigate and operate the system easily.

 Security: User data, including borrowing history and personal information, must be
securely stored and protected against unauthorized access. The system should also
implement secure login mechanisms.
 Speed: The LMS should process requests quickly, such as searching for books,
generating reports, or managing inventory. Delays could negatively impact user
satisfaction.
 Reliability: The system must always be reliable and available, ensuring that users and
administrators can access it without downtime or significant disruptions.

3.3 Planning and Scheduling


To ensure the successful development and implementation of the " Face Recognition
Attendance System" system, a clear project timeline and resource allocation are necessary.
This section details the phases of the project and the estimated timelines for each phase:

Project Phases:
3. Requirement Analysis (Duration: 2 weeks):

o Stakeholder meetings to gather and confirm requirements.

o Document functional and non-functional requirements.

o Identify regulatory and compliance considerations

21
4. System Design(Duration: 3 weeks):

o Architectural design of the system.

o Database design for user profiles and attendance records.

o Define user interface mock-ups for administrators and users.

5. Development (Duration: 4 weeks):

o Develop backend functionality including database interactions and facial


recognition algorithms.
o Create frontend user interface based on approved mock-ups.
o Integrate APIs for data exchange with existing system

6. Testing (Duration: 3 weeks):

o Perform unit testing of individual components.

o Conduct integration testing to ensure seamless communication between components.

o Execute user acceptance testing (UAT) with a select group of end users.
7. Deployment (Duration: 2 weeks):

O Prepare deployment environment and perform system installation.

O Conduct training sessions for administrators and users.

O Launch the system in a live environment.

6 Post-Deployment Support:

o Monitor system performance and user feedback.

o Address any issues that arise and make necessary updates.

o Provide continued user training and support as needed.

22
3.4 Software and Hardware Requirements
The following software and hardware are required to support the
development and operation of the " Face Recognition Attendance” System:
Hardware Requirements:

 Camera: High-resolution web camera or IP camera for capturing images of faces.

 CPU: Multi-core CPU (Intel i5 or better) to handle image processing efficiently.

 RAM: Minimum of 8GB RAM to run multiple processes smoothly.

 Server: XAMPP to handle local server hosting and database management.

 Storage: Adequate disk space for software installations,


databases, and development files.

Software Requirements:

 Windows/Linux: Compatible operating systems that support the necessary


libraries and dependencies.

 Python: Popular choice for computer vision tasks due to its extensive libraries like
OpenCV and face recognition.

 MySQL: For storing user data, attendance records, and other relevant information.

 IDE: Integrated development environments such as PyCharm or Jupiter


Notebook for Python.

 Version Control: Git for tracking changes and collaboration among different team
members.

 Web Interface: HTML/CSS/JavaScript for front-end development, possibly with


React or Angular for an interactive UI.

 Cloud Services (optional): AWS, Google Cloud, or Azure for hosting the application
and Datab

23
3.5 Preliminary Product Description
Face Track is an advanced Face Recognition Attendance System designed to streamline
attendance tracking in educational institutions, corporate environments, and events. Using
state-of-the-art computer vision and artificial intelligence technology, Face Track automates
attendance, eliminating the need for manual registration and form-based processes.
1. Automatic Face Recognition:

Utilizing state-of-the-art algorithms, Face Track automatically detects and recognizes


faces from live video streams or captured images, allowing for quick and efficient
attendance ecording

2 Real-Time Attendance Tracking:

The system processes incoming facial information in real time, marking attendance as
soon as a person enters a specified location, and ensures that meeting records are instantly
updated
3 User-Friendly Interface:

A web-based dashboard allows administrators, teachers, and employees to easily manage


attendance records, review reports, and configure system settings without technical
expertise

4 Secure Data Management:

Face Track ensures data security through encrypted data transmission and secure storage
methods, complying with relevant data protection regulations.
5 Integration Capabilities:

The system can easily integrate with existing management systems (like LMS or
HRMS) to facilitate seamless data sharing and attendance reconciliation.

6 Reporting and Analytics:

Generate detailed attendance reports, along with analytics on attendancepatterns and


trends, to provide insights for administrative decisions.

7 Scalability:

Designed to support various scales of deployment, from small classrooms to large


corporate offices, accommodating increasing user loads and evolving needs

24
3.6 Conceptual Models
Conceptual models represent the overall structure and relationships between key
components of the " Face Recognition Attendance " System. These models guide the
design of the system and help visualize how different parts of this system interact

3.6.1 Zero Level DFD:

25
3.6.2 First Level DFD:

26
3.6.3 Entity-Relationship Diagram:

27
3.6.4 State Chart Diagram:

28
3.6.5 Use Case Diagram:

29
3.6.6 Activity Diagram:

30
3.6.7 Component Diagram

31
3.6.7 Class Diagram:

32
3.6.8 Sequence Diagram:

33
CHAPTER 4
SYSTEM DESIGN

34
1. 4.1 Basic Modules

1. Capture Module
 Camera Integration: Interfaces with webcams or IP cameras to capture real-time
video or images of individuals.

 Image Pre-processing: Enhances image quality, corrects lighting, and focuses on


faces to ensure accurate recognition.

2. Face Detection Module

 Face Localization: Identifies and locates faces in the captured images using
techniques like Haar Cascades, Local Binary Patterns (LBP), or deep learning models
(e.g., MTCNN).

 Multiple Face Detection: Handles scenarios where multiple faces are in the frame.

3. Face Recognition Module

 Feature Extraction: Converts detected faces into feature vectors using algorithms
like Eigenfaces, Fisherfaces, or modern deep learning approaches (e.g., CNNs).
 Matching Algorithm: Matches the extracted features against a database of known
faces to identify individuals.

4. Database Management Module


 User Database: Stores profiles of users with associated images and attendance
records.

 Data Management: Handles CRUD operations (Create, Read, Update, Delete) for
user data.

5. Attendance Tracking Module

 Check-in/Check-out System: Records attendance based on face recognition results,


tracking entry and exit times.

35
6. Report Generation:

 Generates attendance reports over specified periods, providing insights into


attendance patterns. User Interface Module
 Dashboard: Provides a user-friendly interface for administrators to manage users,
view attendance records, and generate reports.

 Alerts and Notifications: Sends notifications for absent users or any discrepancies
in attendance.
7. Security Module

 Data Encryption: Ensures sensitive user information is securely stored.

 Authentication: Verifies user access to the system, ensuring that only authorized
personnel can manage data.

8. User Interface Module

 Dashboard: Provides a user-friendly interface for administrators to manage users,


view attendance records, and generate reports.

 Alerts and Notifications: Sends notifications for absent users or any discrepancies
in attendance.

9 Security Module

 Data Encryption: Ensures sensitive user information is securely stored.

 that only authorized personnel can manage data.

10. Integration Module

 Third-party API Integration: Connects with other systems (like payroll,


educational management systems, etc.) for seamless data flow.

 Export/Import Functions: Allows data to be transferred to and from other formats


or systems (e.g., CSV).

36
4.2 Data Design
This section focuses on structuring the data to support LMS functionality.
Table 1: Users Table

Colum Name Data Type Constraints


user_id INT PRIMARY KEY

first_name VARCHAR (50) NOT NULL

last_name VARCHAR (50) NOT NULL

email VARCHAR (100) UNIQUE KEY

phone VARCHAR (100) CANDIDATE KEY

Gender ENUM DEFAULT_NOW ()

Age INT NOT NULL

Date of Birth: DATE DEFAULT_NOW ()

Department: ENUM DEFAULT_NOW ()

Semester: ENUM DEFAULT_NOW ()

Graduation Year: INT NOT NULL

Roll_no VARCHAR (100) CANDIDATE KEY

Capture_Image BLOB UNIQUE KEY

37
Table 2: Attendance Table

Colum Name Data Type Constraints

attendance_id INT PRIMARY KEY

user_id INT FOREIGN KEY

Check_in_time DATETIME CHECK

check_out_time DATETIME CHECK

status ENUM DEFAULT_NOW ()

date DATE DEFAULT_NOW ()

Table 3: Face Recognition

Colum Name Data Type Constraints

attendance_id INT PRIMARY KEY

user_id INT FOREIGN KEY

recognition_time DATETIME CHECK

confidence_score FLOAT DEFAULT_NOW ()

error_message VARCHAR (255)

38
Table Name: Setting table

Colum Name Data Type Constraints

Setting_id INT PRIMARY KEY

Setting_name VARCHAR (50) NOT NULL

Setting_value VARCHAR (50) NOT NULL

39
 4.2.1 Schema Design:
The schema design is a blueprint for how the data is structured in the LMS. Based on the
provided tables, we can represent the relationships between the entities.

Tables and Relationships:


1. Admin Table:
 This table contains information about the system administrators.
 Fields: ID, FullName, AdminEmail, UserName, Password, updationDate.
2. Students Table:
 Stores data of the students using the LMS.
 Fields: ID, StudentID, FullName, EmailID, PhoneNumber, Password, Status,
RegDate, UpdationDate.
3. Authors Table:
 This table holds information about the book authors in the system.
 Fields: ID, AuthorName, CreationDate, UpdationDate.
4. Books Table:
 Information about books is stored here. Each book has an associated author and
category.
 Fields: ID, BookName, CatID, AuthorID, ISBNNumber, BookPrice, BookImage,
IsIssued, RegDate, UpdationDate.
5. Category Table:
 This table stores categories for books.
 Fields: ID, CategoryName, Status, CreationDate, UpdationDate.
6. IssuedBookDetails Table:
 Stores details about which books have been issued to students, along with issue and
return status.
 Fields: ID, BookID, StudentID, IssuesDate, ReturnDate, ReturnStatus, Fine.
Relationships:
 Admin table is independent.
 Books table has foreign keys: CatID (Category), AuthorID (Author).
 IssuedBookDetails table links Books (BookID) and Students (StudentID).

40
1.1 4.2.2Data Integrity and Constraints:
• Primary Key Constraints

o Ensure that each table has a unique identifier for its rows (e.g., user_id,
attendance_id, recognition_id, setting_id).
• Foreign Key Constraints
o Maintain referential integrity between related tables (e.g., user_id).
• Unique Constraints
o To maintain the uniqueness of certain fields (e.g., Profile Image)
• Not Null Constraints
o Fields that must always contain a value should have a NOT NULL constraint
(First_name, Last_name, capture_image, user_id, check_in_time, date, and
status, etc).
• Default Values
o Setting default values can help maintain data integrity by providing a fallback
for certain fields (e.g., Status).
• Check Constraints
o Check constraints can enforce specific business rules directly at the database level
(status, check_out_time, check_in_time, confidence_score)
• Cascade Updates and Deletes
o Define cascading actions on foreign keys if appropriate (remove or nullify
related records).

41
4.3 Procedural Design
This focuses on how the system will operate functionally.

4.3.1 Logic Diagrams:


Creating a procedural design for a face recognition attendance system involves
outlining the various processes that will be executed within the system. This design
will cover the workflow from capturing images to recording attendance, ensuring that
each step is clearly defined.

Activity Diagram

42
4.3.2 Data Structures:
Data structures are critical for managing data in the Face Recognition Attendance
System (FRAS). The following will be utilized:

1. Arrays:
o Store collections of User, Attendance, FaceRecognition, and Settings records
for quick, indexed access.
o Example: Array of User objects with attributes user_id, first_name, last_name,
email, phone, capture_image, and roll_no.
2. Linked Lists:
o Manage dynamic attendance records in strict chronological order.
o Example: Linked list of AttendanceRecord nodes, each containing user_id,
check_in_time, check_out_time, status, and date, allowing O(1) insertion of
new events.
3. Hash Tables:
o Enable O(1) lookups by unique identifiers.
o Example:
 Hash table mapping user_id → User details for instant profile retrieval.
 Hash table mapping recognition_id → FaceRecognition details
(user_id, recognition_time, confidence_score, image_data,
error_message).
 Hash table mapping setting_name → setting_value for config access.
4. Trees:
o Organize hierarchical or sorted data, e.g. configuration settings or decision
logic.
o Example: Binary search tree of Settings entries for efficient retrieval by
setting_name.
5. Graphs:
o Represent relationships or state-transitions, such as attendance flows or
recognition pipelines.
o Example: Directed graph modelling transitions between attendance statuses
(e.g. Present → Absent, Absent → Late).

43
6. Queues:
o Handle incoming face-recognition jobs and pending attendance check-ins in
FIFO order.
o Example: Queue of recognition tasks, each with recognition_id, user_id, and
image_data, ensuring orderly processing.

• 4.3.3 Algorithm Design:

User (students) Registration Algorithm

This algorithm is responsible for registering new users in the system.

Steps:

1.Input: User details (first name, last name, email, phone number, profile image).
2.Validate Input:

 Check for empty fields.

 Validate email format using regex.

 Check for existing users by querying the Users table.


3.Store User Data:

 Insert user details into the Users table with created_at


and updated_at timestamps.
 Store the profile image in the profile_image column as BLOB.
4.Feature Extraction:

 Perform face detection on the profile image.

 Extract facial features (using a library like OpenCV).


5.Output: Return a success message with the user ID or an error message.

44
• Attendance Tracking Algorithm

This algorithm tracks attendance for users based on face recognition.


Steps:

1.Input: Captured image from a webcam.


2.Pre-process Image:
 Resize and normalize the captured image.

3.Face Detection:

 Use a face detection model (e.g., Haar Cascade or DNN) to identify faces.
4.Feature Extraction:

 Extract facial features from the detected face.


5.Recognition:

 Compare extracted features with the data in the Face Recognition table.

 Calculate a confidence score for the match.


6.Check Attendance:

 If confidence score exceeds a predefined threshold:

 Log the attendance:

 Check-in: If it’s the first time for the day.

 Check-out: If it’s the end of the day.

 Insert/update attendance record in the Attendance table.

 Store recognition details:

 Insert data into the FaceRecognition table with the user ID, recognition time,
confidence score, and any error message if applicable.
7.Output: Confirm attendance status (Present or Absent) along with a recognition success
message

45
• Attendance Reporting Algorithm

This algorithm generates attendance reports.


Steps:

1. Input: User ID, date range (start date, end date).


2. Query Attendance Records:

 Retrieve records from the Attendance table based on the user ID and specified
date range.

3. Process Data:

 Count total present and absent days.

 Calculate attendance percentage.

4. Output: Return a summary report with attendance statistics.

• Settings Management Algorithm

This algorithm manages the system's configuration settings.


Steps:

1.Input: Setting name and value.


 Check Existing Setting
 Query the Settings table for the specified setting.

2.Update or Insert:

 If it exists, update the setting value.

 If it doesn’t exist, create a new entry.

3.Output: Return a success message confirming the setting was updated or cerate.

46
4.4 User Interface Design
The user interface (UI) design for a Face Recognition Attendance System should focus on
simplicity, clarity, and ease of use. The following key UI components are included in the
"Face Recognition Attendance" system:
1. Login Screen

 Purpose: Allows administrators or users to log in to the system.


 Elements:

o Email/Username Field: Input box for entering the user's email or username.

o Password Field: Secure password input box.

o Login Button: Button to submit credentials.

o Forgot Password: Link for password recovery.

o Facial Recognition Option: For admins who wish to use facial login instead
of typing in credentials.

 Actions: Upon successful login, the user is redirected to the dashboard.

2. Admin Dashboard
 Purpose: Central control panel for administrators to view attendance, manage users,
and configure settings.
 Elements:

o Navigation Menu: Links to different sections: Attendance Overview, User


Management, Face Recognition Logs, and Settings.

o Attendance Overview: Displays a calendar view or table view of attendance


records.

o Recent Recognitions: List of most recent face recognition logs showing


user, time, and confidence score.

47
3. User Management Screen

 Purpose: Admin can manage user information.


 Elements:

o User List: Table with users' information (Name, Email,


Phone, Roll No.).

o Search Bar: Search for users by name, email, or roll number.

o Add User Button: Opens a form to add a new user.

o Edit/Delete Icons: For each user, admin can edit or


delete their information.

o View Details: Option to view detailed information of a


particular user, including their facial image.

 Actions: Allows adding, editing, and deleting users.

4. Face Recognition Screen


 Purpose: Takes input from the camera, processes the
face, and marks attendance.
 Elements:

o Live Camera Feed: Displays the current video feed from


the user's camera.

o Capture Button: Button to capture an image for recognition.

o Recognition Results: Displays whether the recognition


was successful and the associated user’s details (Name,
Roll No.).

o Attendance Status: Automatically marks the user as


"Present" if successfully recognized.
Actions: Based on successful recognition, the system logs the check-in or check-out time.

48
5 Attendance Records Screen

 Purpose: Allows users or admins to view attendance records for


a specific period.
 Elements:

o User Dropdown: Select the user whose attendance record is to be viewed.

o Date Range Selector: Choose the period for the attendance report.

o Attendance Table: Displays a list of attendance entries


(Date, Check- In Time, Check-Out Time, Status).

o Export Button: Option to export attendance records to


CSV or PDF format.

o Filter: Filter based on class, status (Present/Absent).

6 Settings Screen

 Purpose: Provides system-wide settings for facial


recognition, timeouts, confidence score thresholds, and others.
 Elements:

o Setting Name: Text field for setting name (e.g., recognition threshold).

o Setting Value: Input field for the value (e.g., 85% confidence score).

o Save Button: Saves the updated setting.

 Actions: Allows modification of system configure

49
4.5 Security Issues
Security is a critical aspect of the system, particularly when dealing with user data such as
their E-mail, Phone_no, and etc. The "Face Recognition Attendance System” addresses the
following security issues:
1. Biometric Data Security:

o Encrypt all facial data at rest and in transit

o Use secure, standardized encryption algorithms such as AES-256 for stored


images.

o Ensure proper access controls and restrict access to sensitive biometric data to
authorized personnel only.
2. Data Breaches and Hacking:

o Regularly update the system with security patches and protect against common
vulnerabilities (e.g., SQL injection, cross-site scripting).
o Implement firewalls and intrusion detection systems (IDS) to monitor for suspicious
activity.

o Encrypt sensitive data both in transit and at rest, and ensure secure API
communication using HTTPS and TLS.
3. Privacy Concerns:

o Ensure compliance with data protection laws by clearly outlining data collection,
storage, and usage policies.

o Obtain explicit consent from users before capturing and using their facial data.

o Provide users with the ability to request deletion of their biometric data when they
leave the organization.

4. False Positives and False Negatives:

o Continuously improve and update face recognition algorithms with diverse and large
datasets to reduce error rates.

o Combine face recognition with additional authentication methods to minimize the risk
of incorrect identification.
o Set an appropriate confidence threshold for face recognition to reduce false positives

50
5. User Authentication:

o Implement strong password policies (minimum length, complexity).

o Use salted and hashed passwords with algorithms like crypt.

o Multi-factor authentication for added security.

51
4.6 Test Cases Design
Testing ensures that the "Face Recognition Attendance System " works as expected and
is free from bugs. Some of the core test cases include:
1. User Authentication and Login Testing
 Test Scenario: Verify user authentication via face recognition.

 Expected Result: The system correctly identifies the user and logs them in if the
face is recognized with sufficient confidence.
2. Check-in and Check-out Attendance Testing
 Test Scenario: Verify the attendance check-in and check-out process.

 Expected Result: The system should log the check-in and check-out times
accurately for the recognized user.

3. Invalid Face Recognition Attempts Testing


 Test Scenario: Verify system behavior when an unrecognized face
attempts to mark attendance.
 Expected Result: The system should deny access and not record
attendance.
4. Confidence Score Threshold Testing

 Test Scenario: Verify that the system processes face recognition attempts
based on confidence score thresholds.
 Expected Result: If the confidence score falls below the threshold, the
system should reject the recognition attempt.

5. System Performance with High Traffic Testing

 Test Scenario: Test system performance when multiple users try to check in
simultaneously.
 Expected Result: The system should handle multiple check-ins without
slowing down or crashing.

6. System Security and Data Privacy Testing

 Test Scenario: Verify system’s data security and privacy compliance

 Expected Result: The system should prevent unauthorized access to facial data
and ensure logs cannot be altered without proper permissions.

52
7. Data Logging and Audit Trail Testing
• Test Scenario: Verify that all system actions are logged.
• Expected Result: The system should log all actions, including successful and failed
recognition attempts, with timestamps.

8. System Recovery from Failure Testing


• Test Scenario: Verify the system’s ability to recover from a power failure or system crash.
• Expected Result: The system should restart successfully, and all previous attendance
records
• should remain intact.

53
CHAPTER 5
IMPLEMENTATION AND TESTING

54
5.1 CODE
# ---------------------------
# AUTHENTICATION APPLICATION
# ---------------------------
class AuthApp(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Login / Signup")
self.geometry("500x600")
self.resizable(True, True)
self.configure(fg_color="#1a2a6c")
self.conn = get_db_connection()
self.cursor = self.conn.cursor()
self.profile_img_path = None

# Create the form background with width and height in the constructor
self.form_bg = ctk.CTkFrame(self, fg_color="white", corner_radius=20, width=420,
height=540)
self.form_bg.place(relx=0.5, rely=0.5, anchor="center")

self.container = ctk.CTkFrame(self.form_bg, fg_color="white")


self.container.pack(expand=True, fill="both", padx=20, pady=20)
self.show_login()

def clear_frame(self):
for widget in self.container.winfo_children():
widget.destroy()

def show_login(self):
self.clear_frame()
self.profile_img = create_circular_image(None)
self.profile_label = ctk.CTkLabel(self.container, image=self.profile_img, text="")
self.profile_label.pack(pady=(20, 10))
self.login_input = ctk.CTkEntry(self.container, placeholder_text="Username or Email",
width=300, height=40)
self.login_input.pack(pady=10)
self.login_input.bind("<KeyRelease>", self.update_profile_image)
self.password = ctk.CTkEntry(self.container, placeholder_text="Password", show="*",
width=300, height=40)
self.password.pack(pady=10)
self.login_error = ctk.CTkLabel(self.container, text="", text_color="red")
self.login_error.pack()
self.login_btn = ctk.CTkButton(self.container, text="LOGIN", width=300, height=40,
fg_color="black", command=self.login)
self.login_btn.pack(pady=20)
ctk.CTkLabel(self.container, text="Don't have an account? ").pack()
self.signup_link = ctk.CTkButton(self.container, text="Sign Up",
command=self.show_signup, fg_color="black", hover_color="#1a2a6c")
self.signup_link.pack()

55
def update_profile_image(self, event=None):
login_cred = self.login_input.get().strip()
if login_cred:
self.cursor.execute("SELECT profile_image FROM users WHERE username = ? OR
email = ?", (login_cred, login_cred))
result = self.cursor.fetchone()
img_path = result[0] if result else None
self.profile_img = create_circular_image(img_path)
self.profile_label.configure(image=self.profile_img)

def show_signup(self):
self.clear_frame()
self.profile_img_path = None
self.profile_img = create_circular_image(None)
self.profile_label = ctk.CTkLabel(self.container, image=self.profile_img, text="")
self.profile_label.pack(pady=(20, 10))
self.profile_label.bind("<Button-1>", lambda e: self.upload_image())
self.username_entry = ctk.CTkEntry(self.container, placeholder_text="Username",
width=300, height=40)
self.username_entry.pack(pady=10)
self.email_entry = ctk.CTkEntry(self.container, placeholder_text="Email", width=300,
height=40)
self.email_entry.pack(pady=10)
self.password_entry = ctk.CTkEntry(self.container, placeholder_text="Password",
show="*", width=300, height=40)
self.password_entry.pack(pady=10)
self.confirm_password_entry = ctk.CTkEntry(self.container, placeholder_text="Confirm
Password", show="*", width=300, height=40)
self.confirm_password_entry.pack(pady=10)
self.signup_error = ctk.CTkLabel(self.container, text="", text_color="red")
self.signup_error.pack()
self.signup_btn = ctk.CTkButton(self.container, text="SIGN UP", width=300,
height=40, command=self.signup)
self.signup_btn.pack(pady=20)
ctk.CTkLabel(self.container, text="Already have an account? ").pack()
self.login_link = ctk.CTkButton(self.container, text="Login",
command=self.show_login, fg_color="black", hover_color="#1a2a6c")
self.login_link.pack()

def upload_image(self):
file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg")])
if file_path:
try:
os.makedirs(PROFILE_IMAGES_DIR, exist_ok=True)
filename = f"user_{int(time.time())}.jpg"
save_path = os.path.join(PROFILE_IMAGES_DIR, filename)
Image.open(file_path).convert("RGB").save(save_path)
self.profile_img_path = save_path
self.profile_img = create_circular_image(save_path)
self.profile_label.configure(image=self.profile_img)

56
except Exception as e:
messagebox.showerror("Error", f"Failed to load image: {e}")

def login(self):
self.conn = get_db_connection()
self.cursor = self.conn.cursor()
login_cred = self.login_input.get().strip()
password = self.password.get().strip()
self.cursor.execute("SELECT rowid as id, username, profile_image, role FROM users
WHERE (username = ? OR email = ?) AND password = ?",
(login_cred, login_cred, hash_password(password)))
result = self.cursor.fetchone()
if result:
save_session(result["username"], result["profile_image"] or "")
self.destroy()
if result["role"] == "admin":
AdminPanel(result["id"], result["username"], result["role"]).mainloop()
else:
FaceRecognitionApp().mainloop()
else:
self.login_error.configure(text="Invalid credentials")

def signup(self):
self.conn = get_db_connection()
self.cursor = self.conn.cursor()
username = self.username_entry.get().strip()
email = self.email_entry.get().strip()
password = self.password_entry.get().strip()
confirm_password = self.confirm_password_entry.get().strip()
if not username:
self.signup_error.configure(text="Username cannot be empty")
return
if not re.match(r"^\S+$", username):
self.signup_error.configure(text="Username cannot contain spaces")
return
if not email:
self.signup_error.configure(text="Email cannot be empty")
return
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
self.signup_error.configure(text="Invalid email format")
return
if not password:
self.signup_error.configure(text="Password cannot be empty")
return
if password != confirm_password:
self.signup_error.configure(text="Passwords do not match")
return
try:
role = "admin" if username.lower() == "admin" else "user"

57
self.cursor.execute("INSERT INTO users (username, email, password, role,
profile_image, created_at) VALUES (?, ?, ?, ?, ?, ?)",
(username, email, hash_password(password), role, self.profile_img_path,
datetime.datetime.now().isoformat()))
self.conn.commit()
messagebox.showinfo("Success", "Account created successfully!")
self.show_login()
except sqlite3.IntegrityError:
self.signup_error.configure(text="Username or email already exists")

def mainloop(self):
super().mainloop()

# ---------------------------
# FACE RECOGNITION INTERFACE
# ---------------------------
class FaceRecognitionApp(ctk.CTk):
def __init__(self):
super().__init__()
self.geometry('1200x700+100+50')
self.title('Face Recognition Attendance System')
self.main_frame = ctk.CTkFrame(self)
self.main_frame.pack(fill="both", expand=True)
self.add_menu_items()
self.load_background()
self.add_title_text()
self.update_background()
self.bind("<Configure>", self.on_resize)

def get_logged_in_user(self):
return get_session_user()

def load_background(self):
bg_path = os.path.join(IMAGES_DIR, "interface.jpg")
if os.path.exists(bg_path):
self.bg_image = Image.open(bg_path)
else:
self.bg_image = Image.new("RGB", (100, 100), "gray")
self.bg_photo = None
self.bg_label = ctk.CTkLabel(self.main_frame, text="")
self.bg_label.pack(fill="both", expand=True)

def open_folder(self, folder_path):


try:
if sys.platform == "win32":
os.startfile(folder_path)
elif sys.platform == "darwin":
subprocess.Popen(["open", folder_path])
else:

58
subprocess.Popen(["xdg-open", folder_path])
except Exception as e:
messagebox.showerror("Error", f"Failed to open folder: {e}")

def student_registration(self):
subprocess.Popen(["python", "student_registration_form.py"])

def student_detail(self):
subprocess.Popen(["python", "show_info_window.py"])

def Helpdesk(self):
subprocess.Popen(["python", "helpdesk.py"])

def trian(self):
subprocess.Popen(["python", "train_model.py"])

def Attendance(self):
subprocess.Popen(["python", "Attendance.py"])

def add_menu_items(self):
self.menu_frame = ctk.CTkFrame(self.main_frame, width=250, corner_radius=0,
fg_color="#060d1f")
self.menu_frame.pack(side="left", fill="y", padx=10, pady=10)
username, profile_img = self.get_logged_in_user()
self.add_user_status(username or "Admin", "User", profile_img)
menu_items = [
("Face Recognition", self.Attendance),
("Train Data", self.trian),
("Student Registration", self.student_registration),
("Student Detail", self.student_detail),
("Attendance Record", show_attendance_grid),
("Face Data", lambda: self.open_folder(os.path.join(os.getcwd(),
FACE_IMAGES_DIR))),
("Help Desk", self.Helpdesk),
("Exit", self.logout)
]
for text, command in menu_items:
ctk.CTkButton(
self.menu_frame,
text=text,
font=("Helvetica", 14),
fg_color="black",
hover_color="#000080",
corner_radius=10,
height=40,
width=250,
border_width=2,
border_color="white",
command=command
).pack(fill="x", padx=10, pady=5)

59
def add_user_status(self, username, role, image_path=None, online=True):
self.user_frame = ctk.CTkFrame(self.menu_frame, fg_color="gray", corner_radius=10)
self.user_frame.pack(fill="x", padx=10, pady=10)
self.profile_img = create_circular_image(image_path)
self.user_photo_label = ctk.CTkLabel(self.user_frame, image=self.profile_img, text="",
width=80, height=80)
self.user_photo_label.pack(side="left", padx=5, pady=5)
status_text = "Online" if online else "Offline"
status_color = "lightgreen" if online else "red"
self.user_info = ctk.CTkLabel(
self.user_frame,
text=f"{username}\n({role}) {status_text}",
font=("Helvetica", 12, "bold"),
text_color=status_color,
anchor="w"
)
self.user_info.pack(side="left", padx=5, fill="both", expand=True)
self.dots_label = ctk.CTkLabel(self.user_frame, text="⋮", font=("Helvetica", 20, "bold"),
text_color="white")
self.dots_label.pack(side="right", padx=5)
self.dots_label.bind("<Button-1>", self.toggle_menu)

def toggle_menu(self, event):


if hasattr(self, 'options_combo') and self.options_combo.winfo_exists():
self.options_combo.destroy()
del self.options_combo
else:
self.options_combo = ctk.CTkComboBox(
self.user_frame,
values=["Your Profile", "Admin Panel", "Switch Account", "Logout"],
command=self.handle_user_action,
width=120,
dropdown_fg_color="#2c3b41"
)
self.options_combo.place(relx=1.0, rely=0, anchor="ne")

def handle_user_action(self, action):


self.options_combo.destroy()
del self.options_combo
if action == "Your Profile":
self.open_profile_panel()
elif action == "Admin Panel":
self.open_admin_panel()
elif action == "Switch Account":
current_info = self.user_info.cget("text").split("\n")
new_role = "User" if "Admin" in current_info[1] else "Admin"
self.user_info.configure(text=f"{current_info[0]}\n({new_role}) Online")
elif action == "Logout":
self.logout()

60
def update_user_status_image(self, image_path):
self.profile_img = create_circular_image(image_path)
self.user_photo_label.configure(image=self.profile_img)

def open_profile_panel(self):
profile_panel = ProfilePanel(self)
profile_panel.attributes("-topmost", True)
profile_panel.grab_set()

def open_admin_panel(self):
username, _ = get_session_user()
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT rowid as id, role FROM users WHERE username = ?",
(username,))
result = cur.fetchone()
conn.close()
if result and result["role"].lower() == "admin":
self.destroy()
AdminPanel(result["id"], username, result["role"]).mainloop()
else:
messagebox.showerror("Access Denied", "You are not authorized to access the Admin
Panel.")

def update_background(self):
try:
width = self.winfo_width()
height = self.winfo_height()
resized = self.bg_image.resize((width, height), Image.Resampling.LANCZOS)
self.bg_photo = ctk.CTkImage(light_image=resized, dark_image=resized,
size=(width, height))
self.bg_label.configure(image=self.bg_photo)
except Exception:
pass

def add_title_text(self):
self.title_label = ctk.CTkLabel(
self.main_frame,
text="Face Recognition Attendance System",
font=("Helvetica", 30, "bold"),
text_color="black",
bg_color="#ffffff"
)
self.title_label.place(relx=0.5, rely=0.1, anchor="center")

def on_resize(self, event):


self.update_background()

def logout(self):

61
if os.path.exists(SESSION_FILE):
os.remove(SESSION_FILE)
self.destroy()
os.execl(sys.executable, sys.executable, *sys.argv)

def mainloop(self):
super().mainloop()

# ---------------------- Validation on Save ----------------------


def validate_fields():
fields = {
"Student ID": student_id_entry.get().strip(),
"First Name": first_name_entry.get().strip(),
"Last Name": last_name_entry.get().strip(),
"Email": email_entry.get().strip(),
"Phone": phone_entry.get().strip(),
"Gender": gender_entry.get().strip(),
"Age": age_entry.get().strip(),
"Graduation Year": year_entry.get().strip(),
"Date of Birth": dob_entry.get().strip()
}
for key, value in fields.items():
if not value:
messagebox.showerror("Error", f"{key} is required!")
return False
# Validate ComboBoxes
if department_entry.get() == "Select Department.." or semester_entry.get() == "Select
Semester..":
messagebox.showerror("Error", "Please select valid Department and Semester!")
return False
# Run specific validators
validators = [
(validate_student_id, fields["Student ID"]),
(validate_first_name, fields["First Name"]),
(validate_last_name, fields["Last Name"]),
(validate_email, fields["Email"]),
(validate_phone, fields["Phone"]),
(validate_gender, fields["Gender"]),
(validate_age, fields["Age"]),
(validate_dob, fields["Date of Birth"]),
(validate_year, fields["Graduation Year"])
]
for func, value in validators:
err = func(value)
if err:
messagebox.showerror("Error", err)
return False
age_dob_error = validate_age_dob(fields["Age"], fields["Date of Birth"])
if age_dob_error:
messagebox.showerror("Error", age_dob_error)

62
return False
try:
email_exists, phone_exists = check_unique_email_phone(fields["Email"],
fields["Phone"])
if email_exists:
messagebox.showerror("Error", "Email already registered!")
return False
if phone_exists:
messagebox.showerror("Error", "Phone number already registered!")
return False
except Exception as e:
messagebox.showerror("Database Error", f"Could not verify uniqueness: {e}")
return False
return True

def clear():
global face_data, face_counter
student_id_entry.delete(0, ctk.END)
first_name_entry.delete(0, ctk.END)
last_name_entry.delete(0, ctk.END)
email_entry.delete(0, ctk.END)
phone_entry.delete(0, ctk.END)
age_entry.delete(0, ctk.END)
dob_entry.delete(0, ctk.END)
department_entry.set("Select Department..")
semester_entry.set("Select Semester..")
year_entry.delete(0, ctk.END)
gender_entry.set("Male")
for key in error_labels:
error_labels[key].configure(text="")
face_data = []
face_counter = 0
counter_label.configure(text=f"Captured: {face_counter}/100")

def save_student():
if len(face_data) < 100:
messagebox.showerror("Error", "Face data insufficient! Capture at least 100 images
before saving.")
return
if not validate_fields():
return
student_data = {
"student_id": student_id_entry.get().strip(),
"first_name": first_name_entry.get().strip(),
"last_name": last_name_entry.get().strip(),
"email": email_entry.get().strip(),
"phone": phone_entry.get().strip(),
"gender": gender_entry.get(),
"Age": age_entry.get().strip(),
"dob": dob_entry.get().strip(),

63
"department": department_entry.get(),
"semester": semester_entry.get(),
"year": year_entry.get().strip(),
"created_at": datetime.datetime.now()
}
sanitized_id = re.sub(r"[^\w\-]", "_", student_data["student_id"])
student_folder = os.path.join("face_images", sanitized_id)
try:
os.makedirs(student_folder, exist_ok=True)
for idx, img in enumerate(face_data[:100]):
img_filename = os.path.join(student_folder, f"{sanitized_id}_face_{idx+1:03d}.jpg")
Image.fromarray(img, 'L').save(img_filename, quality=95, optimize=True)
face_array = np.array([img.flatten() for img in face_data[:100]])
np.save(os.path.join(student_folder, f"face_data_{sanitized_id}.npy"), face_array)
insert_student(
student_data["student_id"], student_data["first_name"], student_data["last_name"],
student_data["email"], student_data["phone"], student_data["gender"],
student_data["Age"],
student_data["dob"], student_data["department"], student_data["semester"],
student_data["year"], student_data["created_at"], student_folder
)
messagebox.showinfo("Success", "Student details saved successfully!")
clear()
except Exception as e:
messagebox.showerror("Error", f"Failed to save student: {e}")
if os.path.exists(student_folder):
for filename in os.listdir(student_folder):
file_path = os.path.join(student_folder, filename)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as cleanup_error:
print(f"Error deleting {file_path}: {cleanup_error}")

def toggle_face_capture():
global cap, face_counter, last_capture_time, capturing_active, face_data
if not validate_fields():
return
student_id = student_id_entry.get().strip()
sanitized_id = re.sub(r"[^\w\-]", "_", student_id)
if not sanitized_id:
messagebox.showerror("Error", "Invalid Student ID format!")
return
if cap is None or not cap.isOpened():
try:
face_counter = 0
face_data.clear()
last_capture_time = cv2.getTickCount() / cv2.getTickFrequency()
capturing_active = True
for attempt in range(3):

64
cap = cv2.VideoCapture(attempt % 2, cv2.CAP_DSHOW)
if cap.isOpened():
break
if attempt == 2:
raise RuntimeError("Could not initialize camera after multiple attempts")
cv2.waitKey(500)
capture_button_widget.configure(text="Stop Capture")
counter_label.configure(text=f"Captured: {face_counter}/100")
update_frame()
except Exception as e:
if cap and cap.isOpened():
cap.release()
capturing_active = False
messagebox.showerror("Camera Error", f"Failed to initialize camera: {e}")
else:
capturing_active = False
cap.release()
cap = None
capture_button_widget.configure(text="Start Face Capture")
if face_counter >= 100:
messagebox.showinfo("Capture Complete", "Successfully captured 100 face
images!")
else:
messagebox.showwarning("Capture Incomplete", f"Captured {face_counter} images.
Need at least 100.")

def update_frame():
global cap, face_counter, last_capture_time, capturing_active, face_data
if not capturing_active or cap is None or not cap.isOpened():
return
try:
ret, frame = cap.read()
if not ret:
raise RuntimeError("Failed to read camera frame")
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5,
minSize=(100, 100))
if len(faces) > 0:
(x, y, w, h) = max(faces, key=lambda f: f[2] * f[3])
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 4)
current_time = cv2.getTickCount() / cv2.getTickFrequency()
if face_counter < 100 and (current_time - last_capture_time) > 0.5 and w > 100 and h
> 100:
face_img = cv2.resize(cv2.cvtColor(frame[y:y+h, x:x+w],
cv2.COLOR_BGR2GRAY), (500, 400))
face_data.append(face_img)
face_counter += 1
last_capture_time = current_time
counter_label.configure(text=f"Captured: {face_counter}/100")
display_frame = cv2.resize(frame, (500, 400))

65
display_frame = cv2.cvtColor(display_frame, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(display_frame)
ctk_img = CTkImage(light_image=pil_img, dark_image=pil_img, size=(500, 400))
face_label.configure(image=ctk_img)
face_label.image = ctk_img
if capturing_active and face_counter < 100:
face_label.after(50, update_frame)
else:
toggle_face_capture()
except Exception as e:
capturing_active = False
messagebox.showerror("Capture Error", f"Error during capture: {e}")
if cap:
cap.release()
cap = None

def open_calendar():
def set_date():
dob_entry.delete(0, ctk.END)
dob_entry.insert(0, cal.get_date())
top.destroy()
top = tk.Toplevel(root)
top.title("Select Date of Birth")
cal = Calendar(top, selectmode='day', date_pattern='y-mm-dd')
cal.pack(padx=10, pady=10)
tk.Button(top, text="OK", command=set_date).pack(pady=10)

def show_detail():
try:
subprocess.Popen(["python", "show_info_window.py"])
except FileNotFoundError:
messagebox.showerror("Error", "Student details window not found!")

root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=2)
root.grid_rowconfigure(0, weight=1)

form_frame = ctk.CTkFrame(root, corner_radius=10)


form_frame.grid(row=0, column=0, padx=20, pady=20, sticky="nsew")

# Use a 4-column layout:


# Column 0: Label, Column 1: Input widget, Column 2: Calendar button (for DOB) or
dummy label, Column 3: Error message.
row_counter = 0
fields = [
("Student ID:", ctk.CTkEntry(form_frame, width=220)),
("First Name:", ctk.CTkEntry(form_frame, width=220)),
("Last Name:", ctk.CTkEntry(form_frame, width=220)),
("Email:", ctk.CTkEntry(form_frame, width=220)),
("Phone:", ctk.CTkEntry(form_frame, width=220)),

66
("Gender:", ctk.CTkComboBox(form_frame, values=["Male", "Female", "Other"],
width=220)),
("Age:", ctk.CTkEntry(form_frame, width=220)),
("Date of Birth:", ctk.CTkEntry(form_frame, width=170)),
("Department:", ctk.CTkComboBox(form_frame, values=['Select Department..', 'BSc IT',
'BSc CS', 'B.ed', 'Bcom', 'Baff', 'BSc'], width=220)),
("Semester:", ctk.CTkComboBox(form_frame, values=["Select Semester..", "Semester
1(FY)", "Semester 2(FY)", "Semester 3(SY)", "Semester 4(SY)", "Semester 5(TY)",
"Semester 6(TY)", "Semester 7(FY4)", "Semester 8(FY4)"], width=220)),
("Graduation Year:", ctk.CTkEntry(form_frame, width=220))
]

ordered_entries = []

for label_text, widget in fields:


# Label in col0
ctk.CTkLabel(form_frame, text=label_text).grid(row=row_counter, column=0, padx=10,
pady=5, sticky="w")
# Input widget in col1
widget.grid(row=row_counter, column=1, padx=10, pady=5, sticky="ew")
ordered_entries.append(widget)
# For Date of Birth row, add calendar button in col2; else add dummy label
if "Date of Birth" in label_text:
dob_button = ctk.CTkButton(form_frame, text="📅", width=30,
command=open_calendar)
dob_button.grid(row=row_counter, column=2, padx=10, pady=5, sticky="w")
else:
dummy = ctk.CTkLabel(form_frame, text="", width=30)
dummy.grid(row=row_counter, column=2, padx=10, pady=5, sticky="w")
# Error message in col3
err_label = ctk.CTkLabel(form_frame, text="", text_color="red", font=("Arial", 10))
err_label.grid(row=row_counter, column=3, padx=10, pady=5, sticky="w")
field_name = label_text.replace(":", "")
error_labels[field_name] = err_label
row_counter += 1

# Bind Enter key navigation


for i, widget in enumerate(ordered_entries):
def on_enter(event, index=i):
if index + 1 < len(ordered_entries):
ordered_entries[index + 1].focus_set()
widget.bind("<Return>", on_enter)

student_id_entry, first_name_entry, last_name_entry, email_entry, phone_entry, \


gender_entry, age_entry, dob_entry, department_entry, semester_entry, year_entry = \
[widget for _, widget in fields]

gender_entry.set("Male")
department_entry.set("Select Department..")
semester_entry.set("Select Semester..")

67
# Bind key release events for real time validation
student_id_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Student
ID", validate_student_id))
# Added focus out binding for Student ID to ensure error message appears when leaving the
field
student_id_entry.bind("<FocusOut>", lambda event: real_time_validate(event, "Student ID",
validate_student_id))
first_name_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "First
Name", validate_first_name))
last_name_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Last
Name", validate_last_name))
email_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Email",
validate_email))
phone_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Phone",
validate_phone))
gender_entry.bind("<<ComboboxSelected>>", lambda event: update_error("Gender",
validate_gender(gender_entry.get())))
age_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Age",
validate_age))
dob_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Date of Birth",
validate_dob))
year_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Graduation
Year", validate_year))
department_entry.bind("<<ComboboxSelected>>", lambda event:
update_error("Department", validate_department(department_entry.get())))
semester_entry.bind("<<ComboboxSelected>>", lambda event: update_error("Semester",
validate_semester(semester_entry.get())))

face_frame = ctk.CTkFrame(root, corner_radius=0, border_width=0)


face_frame.grid(row=0, column=1, rowspan=1, padx=20, pady=20, sticky="nsew")
face_label = ctk.CTkLabel(face_frame, text="Camera Feed", font=("Arial", 14, "bold"),
width=500, height=300)
face_label.pack(padx=10, pady=10)

button_frame = ctk.CTkFrame(root, height=30)


button_frame.grid(row=1, column=0, columnspan=2, padx=20, pady=10, sticky="ew")
btn_clear = ctk.CTkButton(button_frame, text="Clear", fg_color="#ff4d4d", width=120,
command=clear)
btn_clear.grid(row=0, column=0, padx=10, pady=5)
btn_save = ctk.CTkButton(button_frame, text="Save", fg_color="#2fa572", width=120,
command=save_student)
btn_save.grid(row=0, column=1, padx=10, pady=5)
capture_button_widget = ctk.CTkButton(button_frame, text="Start Face Capture",
fg_color="#FF8C00", width=140, command=toggle_face_capture)
capture_button_widget.grid(row=0, column=2, padx=10, pady=5)
btn_show = ctk.CTkButton(button_frame, text="Student Details", fg_color="#2fa572",
width=120, command=show_detail)
btn_show.grid(row=0, column=3, padx=10, pady=5)

68
counter_label = ctk.CTkLabel(button_frame, text="Captured: 0/100", font=("Arial", 12),
text_color="black")
counter_label.grid(row=0, column=4, padx=10, pady=5, sticky="e")

def on_closing():
global cap
if cap:
cap.release()
root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

69
import customtkinter as ctk
from tkinter import ttk, messagebox
from students_db import get_all_students, delete_student_from_db, get_student_by_id,
update_student_in_db

ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")

class StudentInfoWindow(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Student Information System")
self.geometry("1500x700")
self.resizable(False, False)

self.all_students = []
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(1, weight=1)
self.create_widgets()
self.load_students()
self.protocol("WM_DELETE_WINDOW", self.on_closing)

def create_widgets(self):
self.search_frame = ctk.CTkFrame(self)
self.search_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")

self.search_var = ctk.StringVar()
self.search_entry = ctk.CTkEntry(self.search_frame, textvariable=self.search_var,
placeholder_text="Search by any field...", width=300)
self.search_entry.pack(side="left", fill="x", expand=True, padx=5, pady=5)
self.search_var.trace_add("write", self.filter_students)

self.update_btn = ctk.CTkButton(self.search_frame, text="Update",


fg_color="#FF8C00", command=self.update_selected)

70
self.update_btn.pack(side="left", padx=5, pady=5)

self.delete_btn = ctk.CTkButton(self.search_frame, text="Delete", fg_color="#ff4d4d",


command=self.delete_selected)
self.delete_btn.pack(side="left", padx=5, pady=5)

self.tree_frame = ctk.CTkFrame(self)
self.tree_frame.grid(row=1, column=0, padx=10, pady=(0, 10), sticky="nsew")
self.tree_frame.grid_columnconfigure(0, weight=1)
self.tree_frame.grid_rowconfigure(0, weight=1)

self.columns = (
"ID", "Student ID", "First Name", "Last Name", "Email", "Phone",
"Gender", "Age", "Date of Birth", "Department", "Semester", "Graduation Year",
"Created At", "Photo Path"
)
self.tree = ttk.Treeview(self.tree_frame, columns=self.columns, show="headings",
selectmode="browse")
self.vsb = ttk.Scrollbar(self.tree_frame, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=self.vsb.set)
self.tree.grid(row=0, column=0, sticky="nsew")
self.vsb.grid(row=0, column=1, sticky="ns")

for col in self.columns:


self.tree.heading(col, text=col)
self.tree.column(col, width=120, anchor="center", minwidth=100)

def load_students(self):
try:
self.all_students = get_all_students()
self.tree.delete(*self.tree.get_children())
for student in self.all_students:
self.tree.insert("", "end", values=student)
except Exception as e:

71
import sqlite3
from utils import get_db_connection, ensure_directories

def check_unique_email_phone(email, phone):


conn = get_db_connection('students.db')
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM students WHERE email=?", (email,))
email_count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM students WHERE phone=?", (phone,))
phone_count = cursor.fetchone()[0]
conn.close()
return (email_count > 0, phone_count > 0)

def initialize_db():
ensure_directories()
conn = get_db_connection('students.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id TEXT UNIQUE NOT NULL,
first_name TEXT,
last_name TEXT,
email TEXT UNIQUE NOT NULL,
phone TEXT UNIQUE NOT NULL,
gender TEXT,
age INTEGER,
date_of_birth TEXT,
department TEXT,
semester TEXT,
year TEXT,
created_at TEXT,
photo_path TEXT
)

72
"""
)
conn.commit()
conn.close()
print("Students database initialized successfully!")

def initialize_attendance_table():
ensure_directories()
conn = get_db_connection('students.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS attendance (
attendance_id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id TEXT NOT NULL,
name TEXT,
department TEXT,
timestamp TEXT,
status TEXT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
)
"""
)
conn.commit()
conn.close()
print("Attendance table initialized successfully!")

def insert_student(student_id, first_name, last_name, email, phone,


gender, age, date_of_birth, department, semester, year, created_at, photo_path):
try:
conn = get_db_connection('students.db')
cursor = conn.cursor()
cursor.execute("""
INSERT INTO students (
student_id, first_name, last_name, email, phone,

73
gender, age, date_of_birth, department, semester, year, created_at, photo_path
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (student_id, first_name, last_name, email, phone,
gender, age, date_of_birth, department, semester, year, str(created_at), photo_path))
conn.commit()
conn.close()
print("Student saved successfully!")
except sqlite3.Error as e:
print("Failed to save student:", e)
import cv2
import os
import numpy as np
import customtkinter as ctk
from tkinter import messagebox, filedialog
from PIL import Image
import time
import sqlite3
import json
from utils import get_db_path, get_image_path, get_db_connection, ensure_directories

# ---------------------- Setup Appearance ----------------------


ctk.set_appearance_mode("System") # "System", "light", or "dark"
ctk.set_default_color_theme("blue")

# ---------------------- Paths & Constants ----------------------


ensure_directories()
CHOSEN_DB = get_db_path("students.db")
# Initial dataset folder is the face_images folder
IMAGE_DIRECTORY = get_db_path("face_images") # using get_db_path to ensure
dynamic path
MODEL_SAVE_PATH = get_image_path("", "face_recognizer_model.xml")
LABEL_MAP_PATH = get_image_path("", "label_map.json")

74
if not os.path.exists(CHOSEN_DB):
messagebox.showerror("DB Error", "No database file found (students.db).")
raise SystemExit("No DB file found.")

# ---------------------- Initialize Face Recognizer ----------------------


try:
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
except AttributeError:
messagebox.showerror("Error", "LBPHFaceRecognizer not found. Make sure you have
opencv-contrib installed.")
raise SystemExit("LBPHFaceRecognizer not available.")

# ---------------------- Helper Functions ----------------------


def folder_in_db(student_id):
"""
Return True if 'student_id' (e.g., "TYIT24053") is found in the 'students' table.
If you want to train on ALL folders (ignoring the DB), remove this check or always return
True.
"""
try:
conn = get_db_connection("students.db")
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM students WHERE student_id=?",
(str(student_id),))
count = cursor.fetchone()[0]
conn.close()
return count > 0
except Exception as e:
print(f"[DEBUG] DB error checking folder: {e}")
return False

def load_label_map():
"""Load existing label_map.json if it exists; otherwise return empty dict."""
if os.path.exists(LABEL_MAP_PATH):

75
with open(LABEL_MAP_PATH, "r") as f:
return json.load(f) # e.g. { "TYIT24053": 0, "JohnDoe": 1, ... }
return {}

def save_label_map(label_map):
"""Save label_map to disk as JSON."""
with open(LABEL_MAP_PATH, "w") as f:
json.dump(label_map, f, indent=2)

def load_images_and_labels(image_directory, label_map):


"""
Load images & labels from a chosen folder.
If the chosen folder directly contains images, treat it as a single person folder.
Otherwise, iterate over its subfolders (each representing one person).
Only folders that pass the folder_in_db check are processed.
Returns: (images, labels, updated_label_map, student_list)
"""
images = []
labels = []
student_list = []

# Check if the chosen directory directly contains image files


files = os.listdir(image_directory)
image_files = [f for f in files if f.lower().endswith(('.jpg', '.jpeg', '.png'))]

# Determine the next label value based on current label_map


existing_labels = list(label_map.values())
next_label = 0 if not existing_labels else max(existing_labels) + 1

if image_files:
folder_name = os.path.basename(image_directory)
if not folder_in_db(folder_name):
print(f"[DEBUG] Skipping folder '{folder_name}' - not in DB.")
else:

76
if folder_name not in label_map:
label_map[folder_name] = next_label
assigned_label = label_map[folder_name]
student_list.append(folder_name)
for file in image_files:
img_path = os.path.join(image_directory, file)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is not None:
images.append(img)
labels.append(assigned_label)
else:
# Assume folder contains subfolders for each person
for folder_name in os.listdir(image_directory):
person_dir = os.path.join(image_directory, folder_name)
if not os.path.isdir(person_dir):
continue
if not folder_in_db(folder_name):
print(f"[DEBUG] Skipping folder '{folder_name}' - not in DB.")
continue
if folder_name not in label_map:
label_map[folder_name] = next_label
next_label += 1
assigned_label = label_map[folder_name]
student_list.append(folder_name)
for file in os.listdir(person_dir):
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
img_path = os.path.join(person_dir, file)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is not None:
images.append(img)
labels.append(assigned_label)
return images, labels, label_map, student_list

def show_images_during_training(images):

77
"""Briefly display each training image in a window called 'Training Image'."""
for img in images:
cv2.imshow("Training Image", img)
# Wait 50 ms, and allow breaking if a key is pressed
if cv2.waitKey(50) & 0xFF != 255:
break
cv2.destroyWindow("Training Image")

def train_or_update_face_recognizer():
"""
Incrementally train (or update) an LBPH model using images from the chosen dataset
folder.
Loads existing model and label_map if available, trains or updates, and then saves them.
"""
train_button.configure(state="disabled")
status_label.configure(text="Gathering images...")
app.update_idletasks()

# Load or initialize label map


label_map = load_label_map()

# Collect images and labels (this will update label_map if new folders are found)
images, labels, label_map, student_list = load_images_and_labels(IMAGE_DIRECTORY,
label_map)

if not images:
train_button.configure(state="normal")
messagebox.showerror("Error", "No images found for training! Check your dataset
folder.")
return

# Optionally show training images


status_label.configure(text="Displaying training images...")
app.update_idletasks()

78
show_images_during_training(images)

# Check if a model already exists


model_exists = os.path.exists(MODEL_SAVE_PATH)
if model_exists:
face_recognizer.read(MODEL_SAVE_PATH)

# Train or update
status_label.configure(text="Training in progress...")
app.update_idletasks()
start_time = time.time()
try:
if model_exists:
face_recognizer.update(images, np.array(labels))
print("[INFO] Updated existing LBPH model with new images.")
else:
face_recognizer.train(images, np.array(labels))
print("[INFO] Trained new LBPH model from scratch.")
except Exception as e:
messagebox.showerror("Training Error", f"An error occurred during training: {e}")
train_button.configure(state="normal")
return

# Save the updated model and label map


face_recognizer.save(MODEL_SAVE_PATH)
train_time = round(time.time() - start_time, 2)
save_label_map(label_map)

status_label.configure(text=f"Training completed in {train_time} seconds!")


train_button.configure(state="normal")
messagebox.showinfo("Success", f"Model training/updating complete!\nStudents
processed: {len(student_list)}")

def show_dataset_info():

79
"""
Quickly load images (without training) to see dataset info.
"""
label_map = load_label_map()
images, labels, label_map, student_list = load_images_and_labels(IMAGE_DIRECTORY,
label_map)

if not images:
messagebox.showinfo("Dataset Info", "No images found in the current dataset folder.")
else:
info_text = (
f"Total Images: {len(images)}\n"
f"Unique Student Folders: {len(student_list)}\n"
f"Folder Names (IDs): {', '.join(student_list)}"
)
messagebox.showinfo("Dataset Info", info_text)

def select_dataset():
"""
Allow the user to choose either the main dataset folder (with subfolders)
or a specific person's folder for training.
"""
global IMAGE_DIRECTORY
folder_selected = filedialog.askdirectory(initialdir=IMAGE_DIRECTORY)
if folder_selected:
IMAGE_DIRECTORY = folder_selected
dataset_label.configure(text=f"Dataset: {IMAGE_DIRECTORY}")

def toggle_theme():
current_mode = ctk.get_appearance_mode()
new_mode = "light" if current_mode == "dark" else "dark"
ctk.set_appearance_mode(new_mode)

def open_settings():

80
messagebox.showinfo("Settings", "Settings dialog placeholder.")

def exit_app():
app.quit()

# ---------------------- GUI Setup ----------------------


app = ctk.CTk()
app.title("Face Recognition - Training Module")
app.geometry("800x500")
app.resizable(False, False)
app.protocol("WM_DELETE_WINDOW", exit_app) # Handle window cancel gracefully

# Main content frame


main_frame = ctk.CTkFrame(app)
main_frame.pack(padx=20, pady=20, fill="both", expand=True)

title_label = ctk.CTkLabel(main_frame, text="Face Recognition - Training Module",


font=("Arial", 20))
title_label.grid(row=0, column=0, columnspan=3, pady=(0, 10))

train_button = ctk.CTkButton(main_frame, text="Train/Update Model",


command=train_or_update_face_recognizer)
train_button.grid(row=1, column=0, padx=5, pady=5, sticky="ew")

info_button = ctk.CTkButton(main_frame, text="Show Dataset Info",


command=show_dataset_info)
info_button.grid(row=1, column=1, padx=5, pady=5, sticky="ew")

select_button = ctk.CTkButton(main_frame, text="Select Dataset", command=select_dataset)


select_button.grid(row=1, column=2, padx=5, pady=5, sticky="ew")

dataset_label = ctk.CTkLabel(main_frame, text=f"Dataset: {IMAGE_DIRECTORY}")


dataset_label.grid(row=2, column=0, columnspan=3, pady=5, sticky="w")

81
model_label = ctk.CTkLabel(main_frame, text="Model Selection:")
model_label.grid(row=3, column=0, sticky="e", padx=5)

model_var = ctk.StringVar(value="LBPH")
model_dropdown = ctk.CTkComboBox(main_frame, values=["LBPH", "EigenFace",
"FisherFace"], variable=model_var)
model_dropdown.grid(row=3, column=1, sticky="w", padx=(0, 10))

settings_button = ctk.CTkButton(main_frame, text="Settings", command=open_settings)


settings_button.grid(row=3, column=2, sticky="ew", padx=(0,5))

theme_button = ctk.CTkButton(main_frame, text="Theme Toggle",


command=toggle_theme)
theme_button.grid(row=4, column=1, pady=5, sticky="ew")

exit_button = ctk.CTkButton(main_frame, text="Exit", command=exit_app)


exit_button.grid(row=4, column=2, padx=5, pady=5, sticky="ew")

progress_frame = ctk.CTkFrame(main_frame)
progress_frame.grid(row=5, column=0, columnspan=3, pady=10, sticky="ew")

progress_var = ctk.DoubleVar(value=0)
progress_bar = ctk.CTkProgressBar(progress_frame, variable=progress_var,
orientation="horizontal")
progress_bar.pack(fill="x", expand=True, padx=10, pady=5)

status_label = ctk.CTkLabel(progress_frame, text="Status: Idle")


status_label.pack(pady=5)

bottom_frame = ctk.CTkFrame(main_frame)
bottom_frame.grid(row=6, column=0, columnspan=3, sticky="nsew", pady=(10,0))
main_frame.grid_rowconfigure(6, weight=1)
for col in range(3):
main_frame.grid_columnconfigure(col, weight=1)

82
# ---------------------- Main Loop ----------------------
if __name__ == "__main__":
app.mainloop()
def save_attendance_to_db():
try:
finalize_attendance()
conn = sqlite3.connect(STUDENTS_DB)
cursor = conn.cursor()
today = datetime.date.today().strftime("%Y-%m-%d")
cursor.execute("DELETE FROM attendance WHERE date(timestamp) = ?", (today,))
for record in attendance.values():
cursor.execute(
"""
INSERT INTO attendance (student_id, name, department, timestamp, status)
VALUES (?, ?, ?, ?, ?)
""",
(
record["student_id"],
record["name"],
record["department"],
record["timestamp"],
record["status"],
),
)
conn.commit()
conn.close()
messagebox.showinfo("Success", "Attendance saved to database!")
except Exception as e:
messagebox.showerror("Error", f"Database save failed: {str(e)}")

def export_attendance_csv():
finalize_attendance()
try:
with open(ATTENDANCE_CSV, "w", newline="") as f:

83
writer = csv.DictWriter(f, fieldnames=["student_id", "name", "department",
"timestamp", "status"])
writer.writeheader()
for record in attendance.values():
writer.writerow(record)
messagebox.showinfo("Success", f"Attendance exported to:\n{ATTENDANCE_CSV}")
except Exception as e:
messagebox.showerror("Error", f"CSV export failed: {str(e)}")

# ---------------------- GUI Application ----------------------


class AttendanceApp(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Face Recognition Attendance System")
self.geometry("1200x800")
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
self.resizable(False, False)

self.cap = None
self.is_running = False
self.after_id = None
self.auto_save = ctk.BooleanVar(value=True)
self.logged_today = set()
self.current_date = datetime.date.today()

# Variables for stable recognition


self.last_label = None
self.same_label_count = 0
self.min_consecutive_frames = 5

initialize_globals()
self.create_widgets()

84
def create_widgets(self):
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)

# Sidebar
self.sidebar = ctk.CTkFrame(self, width=300, corner_radius=0)
self.sidebar.grid(row=0, column=0, rowspan=4, sticky="nsew")
ctk.CTkLabel(self.sidebar, text="Attendance System", font=("Arial",
16)).pack(pady=20)
ctk.CTkButton(self.sidebar, text="Start", command=self.start_camera).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Stop", command=self.stop_camera).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Save to DB",
command=save_attendance_to_db).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Export CSV",
command=export_attendance_csv).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Train Model",
command=self.train_model).pack(pady=10)

# Always-visible Time Slot chooser


ctk.CTkLabel(self.sidebar, text="Select Time Slot:", font=("Arial", 12)).pack(pady=10)
options = list(TIME_SLOTS.keys()) + ["Custom"]
self.time_slot_var = ctk.StringVar(value=CURRENT_TIME_SLOT)
self.time_slot_menu = ctk.CTkOptionMenu(self.sidebar, values=options,
variable=self.time_slot_var,
command=self.on_time_slot_change)
self.time_slot_menu.pack(pady=5)

# Also include a "Set Time Slot" button for custom times


ctk.CTkButton(self.sidebar, text="Set Custom Time",
command=self.open_time_settings).pack(pady=10)
ctk.CTkCheckBox(self.sidebar, text="Auto Save",
variable=self.auto_save).pack(pady=10)

85
# Video frame
self.video_frame = ctk.CTkFrame(self, corner_radius=10)
self.video_frame.grid(row=0, column=1, padx=20, pady=20, sticky="nsew")
self.video_label = ctk.CTkLabel(self.video_frame, text="")
self.video_label.pack(fill="both", expand=True, padx=10, pady=10)

# Log frame
self.log_frame = ctk.CTkFrame(self, corner_radius=10)
self.log_frame.grid(row=1, column=1, padx=20, pady=20, sticky="nsew")
self.log_text = ctk.CTkTextbox(self.log_frame, wrap="word")
self.log_text.pack(fill="both", expand=True, padx=10, pady=10)
self.log_text.insert("0.0", "Attendance Log:\n")

def on_time_slot_change(self, choice):


global PRESENT_CUTOFF_TIME, LATE_CUTOFF_TIME,
CURRENT_TIME_SLOT
if choice == "Custom":
# If "Custom" is selected, open the custom dialog.
self.open_time_settings()
else:
PRESENT_CUTOFF_TIME = TIME_SLOTS[choice]["present"]
LATE_CUTOFF_TIME = TIME_SLOTS[choice]["late"]
CURRENT_TIME_SLOT = choice
messagebox.showinfo("Info", f"Time slot set to: {choice}")

def open_time_settings(self):
top = ctk.CTkToplevel(self)
top.title("Set Custom Time Slot")
top.geometry("350x300")

ctk.CTkLabel(top, text="Custom Time Slot", font=("Arial", 14)).pack(pady=10)

ctk.CTkLabel(top, text="On Time (Present) Cutoff (HH:MM)").pack(pady=5)


present_entry = ctk.CTkEntry(top)

86
present_entry.insert(0, "08:35")
present_entry.pack(pady=5)

ctk.CTkLabel(top, text="Late Cutoff (Late Present) (HH:MM)").pack(pady=5)


late_entry = ctk.CTkEntry(top)
late_entry.insert(0, "08:50")
late_entry.pack(pady=5)

def save_times():
global PRESENT_CUTOFF_TIME, LATE_CUTOFF_TIME,
CURRENT_TIME_SLOT
try:
new_present = datetime.datetime.strptime(present_entry.get(), "%H:%M").time()
new_late = datetime.datetime.strptime(late_entry.get(), "%H:%M").time()
if new_present > new_late:
messagebox.showerror("Error", "On Time cutoff must be earlier than Late
cutoff.")
return
PRESENT_CUTOFF_TIME = new_present
LATE_CUTOFF_TIME = new_late
CURRENT_TIME_SLOT = "Custom"
self.time_slot_var.set("Custom")
messagebox.showinfo("Success", "Custom time slot set!")
top.destroy()
except Exception as e:
messagebox.showerror("Error", f"Invalid time format. Please use
HH:MM.\n{str(e)}")

ctk.CTkButton(top, text="Save", command=save_times).pack(pady=20)

def train_model(self):
try:
from train_model import train_or_update_face_recognizer as train_main
train_main()

87
initialize_globals()
messagebox.showinfo("Success", "Model retrained successfully!")
except Exception as e:
messagebox.showerror("Error", f"Training failed: {str(e)}")

def start_camera(self):
if not self.is_running:
self.cap = cv2.VideoCapture(0)
if not self.cap.isOpened():
messagebox.showerror("Error", "Failed to access camera")
return
self.is_running = True
self.update_frame()

def stop_camera(self):
if self.is_running:
self.is_running = False
if self.cap:
self.cap.release()
self.cap = None
if self.auto_save.get():
save_attendance_to_db()
if self.after_id is not None:
try:
self.after_cancel(self.after_id)
except TclError:
pass
self.after_id = None

def update_frame(self):
if not self.winfo_exists():
return
if self.is_running and self.cap:
ret, frame = self.cap.read()

88
if ret:
processed_frame = self.process_frame(frame)
img = Image.fromarray(cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB))
ctk_image = ctk.CTkImage(light_image=img, size=img.size)
self.video_label.configure(image=ctk_image)
self.video_label.image = ctk_image
try:
self.after_id = self.after(30, self.update_frame)
except TclError:
pass

def process_frame(self, frame):


if datetime.date.today() != self.current_date:
self.logged_today.clear()
self.current_date = datetime.date.today()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
current_time_str = datetime.datetime.now().strftime("%A, %Y-%m-%d %H:%M:%S")
cv2.putText(frame, current_time_str, (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)

for (x, y, w, h) in faces:


cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
face_roi = gray[y:y+h, x:x+w]
label, confidence = face_recognizer.predict(face_roi)

if label != self.last_label:
self.same_label_count = 0
self.last_label = label
else:
self.same_label_count += 1

if label not in label_map_inverse or confidence >= CONFIDENCE_THRESHOLD:

89
cv2.putText(frame, "Unknown", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
continue

if self.same_label_count < self.min_consecutive_frames:


cv2.putText(frame, "Stabilizing...", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 0), 2)
continue

student_id = label_map_inverse.get(label)
if student_id:
details = get_student_details(student_id)
if details:
sid, fname, lname, dept = details
status, timestamp = determine_attendance_status()
text_color = (0, 255, 0)
if status == "Late Present":
text_color = (0, 255, 255)
elif status == "Absent":
text_color = (0, 0, 255)

y_start = y + h + 20
line_height = 25
cv2.rectangle(frame, (x - 10, y_start - 10),
(x + 300, y_start + (4 * line_height) + 10),
(0, 0, 0), -1)
cv2.putText(frame, f"ID: {sid}", (x, y_start),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1)
cv2.putText(frame, f"Name: {fname} {lname}", (x, y_start + line_height),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)
cv2.putText(frame, f"Dept: {dept}", (x, y_start + 2 * line_height),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)
cv2.putText(frame, f"Status: {status}", (x, y_start + 3 * line_height),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)

90
mark_attendance(sid, status, timestamp)

if sid not in self.logged_today:


self.log_text.insert("end", f"{timestamp}: {fname} {lname} - {status}\n")
self.logged_today.add(sid)

return frame

91
5.2 TESTING APPROACH
5.2.1 UNIT TESTING

Unit testing was a crucial part of the development process to ensure that each individual
function or module of the Face Recognition System worked as expected before integrating it
with other components. Testing was done manually by simulating real-world input and
observing outputs.

Tested Components

1. Login System
 Admin Login Test: Entered correct and incorrect credentials to verify that only valid
users could log in.
 Student Login Test: Confirmed session redirection for invalid users and successful
login for registered students.
 Session Handling: Checked if session states are correctly set and unauthorized access
redirects to login screen.

2. User Management (Signup)

 Add New User: Tested both addition with valid and missing fields. Verified
insertion into SQLite database and visibility in system.
 Duplicate Email Check: Checked whether duplicate email IDs are detected
and blocked.
 Delete User: Verified that user accounts are deleted properly and no longer
appear in UI or DB on refresh.
 User Display: Verified that profile picture, name, and user type
(admin/student) render accurately in the main dashboard.

3. Face Detection and Recognition

 Face Capture: Tested webcam live feed and ensured face detection boxes
appear for real human faces.
 Face Encoding Storage: Verified that face encodings are stored with correct
user mapping.

92
 Recognition Logic: Tested with known and unknown faces. Verified system
correctly recognizes or denies access.
 Multiple Face Handling: Ensured the app either prompts or handles multiple
faces smartly.

4. Fine Calculations / Logs (if applicable)


 Access Logs: Manually triggered log entries for face detection, login, and logout.
Verified logs reflect real-time events.
 Time Check: Simulated late/early access to see how the system logs timing violations
(optional)

5. Validation and Error Handling

 Entered blank fields, invalid data types, and SQL-sensitive inputs to confirm
proper error handling and prevention of injection.
 Checked application responses to camera failures, DB disconnection, or
corrupted face image files.

6. UI Feedback
 Verified if success/error alerts and modal messages appear appropriately after actions.
 Tested responsiveness of all GUI elements on various screen resolutions.

 Issue Book: Tested borrowing flow to ensure dates are stored correctly.

 Return Book: Verified the update of return date and calculation of


overdue fines if applicable.

2. Fine Calculation

 Manually simulated late returns by manipulating date_returned and


date_due.

 Verified that the system correctly computes the fine based on the number
of overdue days.

93
3. Validation and Error Handling

 Entered blank fields, invalid data types, and SQL-sensitive inputs to


confirm proper error handling and prevention of injection.

4. UI Feedback

 Verified success/error alerts and modal messages appear appropriately


after actions.

Sample Unit Test Case:

Test Case ID Description Expected Status


Result

UT-001 Login with Redirect to Pass


valid dashboard
credentials

UT-002 Login with Display error Pass


incorrect message
password

UT-003 Add book with Book saved in Pass


valid details database

UT-004 Attempt SQL Blocked and Pass


injection in error shown
login form

UT-005 Issue a book Display issue Pass


already issued restriction
to user message

94
5.2.2 INTEGRATION TESTING
Once unit testing is completed, components are combined to verify full workflows like user
management, book issue-return cycle, and admin controls.
Testing Methodology:
 Combine multiple modules (login → search → issue book → return book) to ensure
seamless operation.
 Test interactions between the admin panel and the user dashboard.
 Manual testing conducted through browser sessions simulating real user behavior.

Application in the Project:

 Deployed the app on a local Apache/MySQL setup with seeded edge-case data.
 Simulated full user workflow: register → login → search → issue → return.
 Exercised issue/return endpoints in Postman to verify JSON responses and HTTP
codes.
 Tested concurrent issuance of the last copy and deletion of users with active
loans.
 Reran integration tests after each bug fix to prevent regression

95
Sample Integration Test Plan:

Test Case ID Description Expected Result Status

IT-001 Login → Search Book details display Pass


Book → View Book correctly
IT-002 Admin Adds Book → Book issued and Pass
User Issues Book recorded in DB
IT-003 Issue Book → Return Pass
Book
Status updated and
book stock refreshed
IT-004 Admin Deletes User Access restricted Pass
→ User Cannot
Login
IT-005 Add Book → Delete Data reflected Pass
→ Re-Add Book correctly in inventory

96
CHAPTER 6
RESULTS AND DISCUSSION

97
Login/Signup page
Admin Home Page

Main Window:-

98
Face Recognition interface:

99
Model Training Interface:

Attendance Record Window: -

100
Student Registration window:

Help Desk Window:

101
Record View Window: -

102
CHAPTER 7
CONCLUSIONS

103
7.1 CONCLUSION
In wrapping up the project, our Face Recognition Attendance System stands out as a robust
blend of computer vision, database management, and user authentication. We built the system
using Python, OpenCV for face detection and recognition, and CustomTkinter for a sleek GUI
interface. The project integrates attendance marking by automatically detecting faces via a
trained LBPH model, fetching student details from an SQLite database, and recording
attendance status based on predefined timing thresholds. While the core functionalities—such
as real-time recognition, data export (to CSV and database), and model training—are
operational, the project also paves the way for more streamlined user management and robust
security measures as demonstrated in the integrated authentication module.

7.1.1 SIGNIFICANCE OF THE SYSTEM


 Efficiency: Replaces manual book records with a digital and searchable system.
 Accessibility: Students and staff can access the system to check book status or history
from any device on the network.
 Time-Saving: Speeds up operations like issuing, returning, and tracking of books.
 Record Accuracy: Reduces the chance of data entry mistakes and loss of physical
records.
 User Management: Offers controlled access levels for students and administrators.

7.2 LIMITATIONS
The Face Recognition System brings a modern, secure, and efficient approach to identity
verification and user management, replacing traditional authentication methods such as
manual logins and ID cards. This system leverages computer vision and machine learning to
detect and recognize human faces in real-time using a webcam and compares them with pre-
registered data for access control.

Key Significance Points:

1. Enhanced Security

The system ensures only authorized individuals gain access, reducing the risk of
impersonation or password theft. Face recognition provides a biometric layer of security that’s
difficult to forge.

104
2. User Convenience

Eliminates the need for remembering passwords or carrying ID cards. Users can authenticate
themselves simply by facing the camera.

3. Automation and Efficiency

Automates the authentication process, reducing manual effort in attendance systems, log
maintenance, or admin approvals—especially useful in institutions or offices.

4. Real-Time Processing

The system processes facial data in real-time, making it suitable for time-sensitive scenarios
like check-ins, surveillance, or access control gates.

5. Scalable for Multiple Use-Cases

With minor modifications, the system can be adapted for applications such as:

 Classroom attendance automation

 Employee entry tracking

 Library systems

 Smart home access

 Data Integration and Logging

The use of SQLite allows centralized storage of user data, face encodings, and log entries for
monitoring or analytics.

6. Educational Value

From a development standpoint, this system provides hands-on experience with technologies
such as OpenCV, SQLite, Tkinter GUI, and Python scripting—making it a valuable learning
project.

105
7.3 FUTURE SCOPE OF THE PROJECT
Looking ahead, we can upgrade to deep learning, add mobile support, move to cloud for
scalability, and boost security and UX.
 Enhanced Accuracy:

Consider upgrading from the traditional LBPH approach to deep learning-based


models (Like CNNs) for improved recognition accuracy, especially in challenging
conditions (Low light, occlusions, etc.).
 Mobile Integration:

Bringing the attendance system to mobile devices could make on-the-go attendance
tracking and remote learning management super accessible.
 Cloud Integration and Data Analytics:

Migrating the backend to cloud-based services would not only enhance scalability but
also allow real-time analytics and machine learning integration for attendance trends
and predictive insights.
 Security Enhancements:

Introducing multi-factor authentication, encryption of sensitive data, and robust error-


handling mechanisms can make the system more secure.
 User Experience Improvements:

An upgraded UI/UX could leverage more dynamic interfaces, real-time notifications,


and even gamified elements to boost engagement.
 Extended Use Cases:

The system could be adapted for broader applications like event management,
workplace attendance, and even integration with Learning Management Systems
(LMS) for holistic academic tracking.

106
REFERENCES

107
Content

1. OpenCV Documentation: https://docs.opencv.org/


2. CustomTkinter GitHub Repository:
https://github.com/TomSchimansky/CustomTkinter
3. SQLite Documentation: https://www.sqlite.org/docs.html
4. Stack Overflow – Face Recognition Discussions: https://stackoverflow.com/
5. Official Tkinter Tutorial (Docs): https://docs.python.org/3/library/tkinter.html
6. LBPH Face Recognition Paper:
https://pyimagesearch.com/2015/12/07/local-binary-patterns-
with-python-opencv

108

You might also like