0% found this document useful (0 votes)
4 views

Voteguard Draft (1)

Uploaded by

raksha.g5155
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)
4 views

Voteguard Draft (1)

Uploaded by

raksha.g5155
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
You are on page 1/ 114

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

“Jnana Sangama”, Belagavi-590018

A PROJECT REPORT
ON
“VoteGuard”

Submitted in the partial fulfillment of the requirements for


the award of

BACHELOR OF ENGINEERING DEGREE


In
COMPUTER SCIENCE & ENGINEERING-DATA SCIENCE
Submitted by
Atiya Noor 4AD21CD004
Ayesha Tul Kubra 4AD21CD006
Pragathi M 4AD21CD036
Raksha H G 4AD21CD040

Under the guidance of


Ms. Ambika V
Associate Professor
Department of CSE-Data Science

DEPARTMENT OF CSE-Data Science

ATME College of Engineering,


13th Kilometer, Mysore-Kanakapura-Bangalore Road
Mysore-570028
2024-2025
VISVESVARAYA TECHNOLOGICAL UNIVERSITY
Belagavi-590018
ATME College of Engineering
13th Kilometer, Mysore-Kanakapura-Bangalore Road

Department of CSE-DATA SCIENCE

CERTIFICATE

This is to certify that the project work entitled “VoteGuard” is the bonafide work carried out
by the students Atiya Noor (4AD21CD004), Ayesha Tul Kubra (4AD21CD006), Pragathi
M (4AD21CD036), Raksha H G (4AD21CD040) in partial fulfillment for the award of degree
of Bachelor of Engineering in CSE-Data Science from the Visvesvaraya Technological
University, Belagavi during the year 2024-2025. It is certified that all the corrections and
suggestions indicated for internal assessment have been incorporated in the Major-project
report deposited in the department library. The Major- Project report has been approved and
satisfies the academic requirement with respect to Major-project work prescribed for Bachelor
of Engineering degree.

Signature of Guide Signature of HOD Signature of Principle

Name of Examiners Signature

1.
2.
ACKNOWLEDGEMENT

The successful completion of our Major-project would be incomplete without the mention
of the names of the people who have made it possible. We are indebted to several
individuals who have helped us to complete the project report.

We are thankful to Dr. L Basavaraj, Principal, ATME College of Engineering for having
granted us permission and extended full use of the college facilities to carry out this project
successfully.

We express our profound gratitude to Dr. Anitha D B, HOD & Associate Professor,
Department of Computer Science and Engineering-Data Science for her consistent co-
operation and support.

At the outset we express our profound gratitude to our guide Ms. Ambika V, Associate
Professor, Department of Computer Science and Engineering-Data Science for his
consistent co-operation and support.

We are greatly indebted to our project coordinator Dr Neethi M V, Assistant Professor,


Department of Computer Science and Engineering-Data Science for their timely inquiries
into the progress of the project.

Lastly we would like to thank our family and friends for their cooperation and support for
success full completion of our project.

ATIYA NOOR (4AD21CD004)

AYESHA TUL KUBRA (4AD21CD006)

PRAGATHI M (4AD21CD036)

RAKSHA H G (4AD21CD040)
ABSTRACT

This project presents a secure and efficient voting system combining block chain technology
and face recognition for voter authentication. Developed using the Python Flask framework,
the system features two key modules: Election Authorities and Voters Election Authorities
manage the voting process, logging in via credentials stored in a MySQL database. Once
authenticated, authorities can add constituencies, register candidates with their respective
political parties, and map them to specific constituencies. Voters are added by recording
essential information such as Aadhar ID, Voter ID, and constituency. During registration,
voters' facial data is captured and trained using Python’s built-in face recognition module,
ensuring identity verification. Voters can log in using their Voter ID and Aadhar ID, after
which a live face recognition process is initiated. If the face and details match, the system
verifies whether the voting session for the respective constituency is active. If active, the voter
receives a list of candidates and their party details and can cast a vote. Once the vote is cast,
it is stored on a custom block chain, ensuring tamper-proof record-keeping. Voters are logged
out automatically, and repeated voting attempts are blocked, ensuring a one-time vote per user.
Election authorities can activate or deactivate constituency voting and access vote counts for
each candidate in real time. The votes are fetched securely from the block chain, providing
transparency and integrity in the election process. This system enhances electoral security by
using block chain for immutability and face recognition for biometric voter authentication,
preventing identity fraud, and ensuring a reliable and transparent voting experience.

i
CONTENTS
Particulars Page No

Abstract i
Contents ii
List of Figures and Tables iii
CHAPTER 1: INTRODUCTION 1-9
1.1 Preamble 1
1.2 Motivation 3
1.3 Problem Statement 5
1.4 Objectives of the project 6
1.5 Organization of the report 8

CHAPTER 2: LITERATURE SURVEY 10-16


2.1 Introduction 10
2.2 Related works/Literature review 12
2.3 Outcome of the literature review 15
CHAPTER 3: SYSTEM REQUIREMENTS AND SPECIFICATION 17-24
3.1 Hardware Requirement 17
3.2 Software Requirement 17
3.3 Tools and Technologies Used 17
3.4 Functional Requirements 22
3.5 Non-Functional Requirements 23
CHAPTER 4: SYSTEM ANLAYSIS AND DESIGN 25-31
4.1 System Analysis 25
4.2 System Architecture 26
4.3 Detailed Design 29
CHAPTER 5: METHODOLOGY & IMPLEMENTATION 32-50
5.1 Methodology 32
5.2 Implementation 33

CHAPTER 6: TESTING 51-55


6.1 Unit Testing 51

6.2 System Testing 53

6.3 Validation Testing 54


CHAPTER 7: DESCUSSION OF RESULTS 56-62

CHAPTER 8: CONCLUSION & FUTURE SCOPE 63-64

REFERENCES 65-66

APPENDIX 67-99
LIST OF FIGURES

Figure No. Figure Title Page No.


4.1 Proposed model Architecture 28
5.1 33
Flowchart of Election Authority module
5.2 Flowchart of voter module 38
7.1 Home Page for E-voting System 56
7.2 Login Page for Election Authority 57
7.3 Election authority page to Add Candidates 57
7.4 To View Candidates 58

7.5 To Add Constituencies 58


7.6 To view List of Constituencies 59
7.7 Voter Register portal 59
7.8 Face Detection for Voter Register 60
7.9 View Vote Counts 61
7.10 Login Page for Voter 61
7.11 Voter Portal to cast Vote 62
7.12 Voting Successful initiated page 62

iii
VoteGuard 2024-2025

CHAPTER 1
INTRODUCTION

1.1 Preamble

The basis of any democratic society rests on the precept of unfastened, honest, and
transparent elections. The integrity of the electoral technique is paramount to ensuring public
agree with and participation in governance. However, traditional balloting structures regularly
face challenges along with voter fraud, logistical inefficiencies, and confined accessibility. To
deal with these problems, integrating advanced technology which include blockchain and face
recognition offers a progressive approach to modernizing and securing the vote casting
technique. Conventional voting systems, whether paper-primarily based or digital, are not
proof against vulnerabilities. Issues together with poll tampering, double voting, and human
error can undermine the accuracy and legitimacy of election consequences. Moreover, these
structures may additionally fail to house the wishes of faraway citizens, individuals with
disabilities, and people in geographically remoted regions. This requires an answer that is
stable, scalable, and inclusive. The advent of blockchain technology and advancements in
artificial intelligence (AI) have opened new avenues for innovation. Blockchain’s
decentralized and immutable nature ensures transparency and consider, whilst AI-powered
face popularity can enhance voter authentication and save you identity fraud. Combining these
technology can pave the way for a next-era e-balloting machine that addresses current
shortcomings while fostering self assurance in the electoral process. Blockchain is a dispensed
ledger machine that records transactions in a secure and transparent manner. Each transaction
is stored as a block and related to the previous one, growing a series this is resistant to
tampering. In the context of e-balloting, blockchain offers numerous benefits. Its transparency
guarantees that each vote cast is recorded and may be established in actual-time with out
compromising voter anonymity. The decentralized nature of blockchain makes it nearly
impossible for a single entity to modify or manipulate the records. Additionally, blockchain
allows far flung vote casting, making sure inclusivity for individuals not able to visit polling

Department of CSE-Data Science, ATMECE, Mysuru Page 1


VoteGuard 2024-2025

stations. By leveraging blockchain, an e-voting gadget can provide a secure and transparent
platform where every vote counts and every voter’s voice is heard. Face popularity era,
powered by AI, complements the accuracy and performance of voter identity. Traditional
strategies of voter authentication, such as ID playing cards or passwords, are vulnerable to
forgery or theft. Face recognition, however, gives a biometric solution that is unique to each
character. Advanced algorithms make sure excessive precision in matching a voter’s facial
features with pre-registered facts, making the system accurate and reliable. This generation
additionally gives convenience, allowing electorate to authenticate themselves seamlessly
without the want for bodily files or PINs. Furthermore, face recognition gets rid of the hazard
of impersonation and guarantees that every man or woman votes most effective once.
Integrating face reputation with e-balloting now not handiest streamlines the authentication
manner however also enhances security and consumer revel in. The synergy between
blockchain and face popularity creates a strong framework for e-balloting. In this gadget,
voters register through providing their private information and a facial scan, with the
information encrypted and securely saved at the blockchain. On election day, citizens
authenticate themselves using face popularity, getting access to the balloting platform upon
successful verification. They then solid their votes, which are recorded as transactions at the
blockchain. Each vote is time-stamped and encrypted to hold confidentiality, and election
authorities and stakeholders can verify the consequences by means of getting access to the
immutable facts on the blockchain. This incorporated approach guarantees a unbroken, stable,
and obvious vote casting technique, addressing the constraints of conventional systems. The
proposed machine offers several advantages. The aggregate of blockchain’s immutability and
face recognition’s biometric accuracy minimizes the chance of fraud and unauthorized get
admission to. Remote vote casting competencies make it easier for people in remote areas or
with mobility challenges to participate in elections. Transparent and auditable processes
improve public confidence in the electoral machine, even as reducing reliance on physical
polling stations and guide processes can lower operational fees. While the proposed device
gives significant advantages, it is important to deal with potential demanding situations
including privateness issues, technical infrastructure necessities, and consumer adoption.

Department of CSE-Data Science, ATMECE, Mysuru Page 2


VoteGuard 2024-2025

Storing biometric and personal records calls for sturdy data protection measures to protect
voter privateness. Implementing this type of system necessitates ok technological
infrastructure and internet get admission to. Additionally, instructing electorate about the new
gadget and addressing resistance to trade are crucial for achievement.

1.2 Motivation
The following are the motivation for the project:-

 The primary motivation behind this system is to enhance security, transparency,


and efficiency in the voting process. Traditional elections often face challenges
like identity fraud and vote tampering, which can undermine public trust.

 By incorporating block chain technology, this system creates an immutable and


tamper-proof record of votes, ensuring accuracy and transparency. Additionally,
face recognition provides robust voter authentication, preventing identity fraud
and double-voting.

 This approach modernizes the voting process, allowing election authorities to


manage candidates and constituencies efficiently while enabling real-time access
to voting data. With a secure, transparent, and one-vote-per-person setup, this
system supports a trustworthy and reliable electoral experience, fostering greater
confidence in democratic processes.

 The intention of creating a blockchain and facial recognition based e-voting


system stems from the need to solve the drawbacks of traditional voting systems
while also progressing towards technologically advanced measures aimed at
ensuring the elections are conducted in a robotic, and fair fashion. There is no
doubt that elections are important when it comes to democratic social systems, and
that’s why the voting process has to be trustworthy.

 In the past, practices like cross-checking an individual’s document with their


photographs were cumbersome and open to impersonation abuses. With the
Department of CSE-Data Science, ATMECE, Mysuru Page 3
VoteGuard 2024-2025
growing adoption and accuracy of face recognition systems, it has now become
effortless to authenticate voters. This eliminates the likely possibility of either
multiple people voting or one person stealing another person’s identity and voting.
With the quick and easy nature of face recognition, the process becomes more
enjoyable and democratic for voters.

 The fact that this project may assist persons with disabilities is one of the other
major considerations. In most voting systems, people with limited movement,
people living in remote areas or even citizens of other countries often find it
incredibly difficult to vote. Introducing a blockchain and face recognition e voting
system could help all of the eligible voters to vote irrespective of where they live
and it would secure the voting so that all the volets can see that their votes have
equally worth.

 Moreover, the high expenses and organizational difficulties of carrying out


elections on such a large-scale make it clear that a better system should be
implemented. It doesn’t matter how the elections are conducted, election booths,
ballots and counting of votes on a large scale is expensive and takes a vast amount
of time. A blockchain-enabled e voting system eliminates the red tape, thereby
significantly lowering a number of expenditures, at the same time providing results
in a more rapid and precise manner.

 The increasing adoption of technology in this day and age also serves as
motivation for this development. Since the population is growing dependent on
digital means on banking, shopping and communication, then there is a need to
transfer this easy usage to voting. At the same time, there is no way to avoid using
such modern technologies as blockchain and face recognition because they are part
of social evolution.

 To conclude, the general idea of implementing such systems is aimed more about
the adoption of a system, where democracy will be enhanced, because such
systems will enable people to vote without excuses.

Department of CSE-Data Science, ATMECE, Mysuru Page 4


VoteGuard 2024-2025

1.3 Problem Statement


The following are the problem statement for the project:-

 The current voting systems often face challenges related to voter authentication, electoral
fraud, and data integrity. Traditional methods, such as paper ballots or electronic voting
machines, are susceptible to tampering, multiple voting attempts, and identity
misrepresentation.

 Additionally, maintaining transparency and ensuring secure, tamper-proof record-


keeping of votes remains a significant concern.

 There is a need for a secure, efficient, and transparent voting system that leverages
advanced technologies to address these issues. Such a system should ensure reliable voter
authentication, prevent fraudulent activities, and provide real-time, immutable vote
tracking while maintaining user privacy and system scalability.

 This project aims to develop a block chain-based voting system integrated with face
recognition technology for biometric voter authentication. The solution will enhance
electoral security, prevent identity fraud, and provide a transparent and tamper-proof
voting process.

 Many of the current systems being used for voting, for example, voter fraud,
manipulation, inefficiencies, or accessibility issues, greatly undermine the faith people
have in democracy. Traditional approaches can be altered, identities can be stolen, and
there will be chances of logistical, thus these approaches fail to make election secure and
transparent. Besides, there are many voters, say, having mobility disabilities or those
residing in sparsely populated areas who do not find it easy to vote because of the
inadequate number of polling centers.

Department of CSE-Data Science, ATMECE, Mysuru Page 5


VoteGuard 2024-2025

1.4 Objective

The following are the objectives of the project:-


 To Enhance Electoral Security and Integrity: - Implement biometric face recognition
to authenticate voters, ensuring that only eligible individuals can cast a vote. Use block
chain technology to store votes securely, preventing tampering or alteration and ensuring
the integrity of the voting process.

 To Ensure a Transparent and Fraud-Free Voting System: - Utilize block chain’s


immutability to create a transparent and auditable voting record, making it impossible for
votes to be modified or deleted. This guarantees a fraud-resistant election process by
preventing identity theft, duplicate voting, and vote manipulation.

 To Improve Voter Management and Election Efficiency: - Develop a streamlined


process for election authorities to manage constituencies, register candidates and voters,
and activate or deactivate voting. The system provides real-time tracking of votes,
improving the efficiency and transparency of managing elections at various levels.

 Enhanced Voting Security:


Block chain technology provides a secure and tamper-proof voting process. When a vote
is cast, it is recorded in a decentralized system that cannot be altered or erased. This
feature makes it extremely difficult for hackers or malicious individuals to interfere with
the results. The system remains highly reliable, even when faced with cyber threats,
ensuring that every vote is counted as intended.

 Voter Identity Verification:


Facial recognition technology is employed to confirm the identity of each voter. This
helps to prevent fraudulent actions such as multiple voting or unauthorized participation.
It guarantees that only eligible voters can enter the system and cast their ballots. The
system is built to quickly and accurately identify faces, adding an extra layer of
confidence in the electoral process.

Department of CSE-Data Science, ATMECE, Mysuru Page 6


VoteGuard 2024-2025

 Transparency in Elections:
Voting records are kept on a block chain, making them publicly verifiable. This enables
both voters and authorities to confirm that votes are accurately recorded while keeping
voter identities confidential. Such transparency fosters trust among all participants and
alleviates concerns regarding the fairness of the election. The system guarantees that
every action taken during the election process is traceable and can be audited. This instills
confidence in the final results.

 Prevention of Tampering and Fraud:


The decentralized structure of blockchain provides strong protection against tampering
and fraud. In contrast to traditional systems that have a single point of failure, blockchain
spreads data across numerous nodes. This means that even if one node is compromised,
the others stay secure. Additionally, face recognition technology helps prevent identity
impersonation or misuse. When combined, these technologies make fraud nearly
impossible.

 Data Privacy and Anonymity:


The system employs encryption to safeguard voter information and maintain privacy.
Although votes are documented for transparency, personal selections stay confidential.
This approach helps to prevent any coercion or influence on voters during the election
process. The design guarantees that even system administrators are unable to view how
an individual voted. Voters can engage in the process without worrying about their
choices being revealed.

 Ease of Use and Accessibility:


The voting platform is crafted to be straightforward and easy to navigate. Voters can
submit their ballots with ease, regardless of their technical skills. With face recognition
technology, there's no need to remember passwords or carry identification cards.
Additionally, the system can be adapted for remote voters, allowing participation from
any location.

Department of CSE-Data Science, ATMECE, Mysuru Page 7


VoteGuard 2024-2025

1.5 Organization of the report

Chapter 1: Introduction This chapter introduces the VoteGuard project using the Secure
Voting with Trusted Block Chain and Face Recognition System, outlining the motivation
behind the project and the challenges of the current voting systems. It defines the problem
statement, focusing on challenges related to voter authentication, electoral fraud, and data
integrity. The chapter concludes with the project objectives.

Chapter 2: Literature Survey This chapter reviews previous work related to, Secure
Voting with Trusted Block Chain and Face Recognition System highlighting key
methodologies and technologies used in the field. It identifies gaps in existing research, setting
the context for the current project.

Chapter 3: System Requirements and Specifications This chapter details the hardware
and software requirements for the project, including database management system, Python
environment, and necessary libraries. It also defines the functional requirements needed to
authenticate an E – Voting system.

Chapter 4: System Analysis and Design This chapter outlines the system’s architecture
and design, explaining how different components interact. It includes diagrams to illustrate the
system structure and design approach.

Chapter 5: Methodology and Implementation Chapter 5 explains the approach taken to


develop the system, implementation of voting system, and the scripting needed to simulate
voting process.

Chapter 6: Testing and Validation This chapter covers the testing process, including unit,
system, and validation testing to ensure the system meets the project’s objectives. It discusses
how the system’s performance was verified.

Department of CSE-Data Science, ATMECE, Mysuru Page 8


VoteGuard 2024-2025

Chapter 7: Discussion of Results this chapter analyses the results of testing, comparing
them to the project’s goals. It highlights successes of the implementation.

Chapter 8: Conclusion and Future Work The final chapter summarizes the project’s
achievements and suggests areas for future improvement, such as incorporating advanced
algorithms and 3D Facial Recognition.

References and Appendix : This section lists all the references used throughout the
project and includes supplementary materials, such as code snippets.

Department of CSE-Data Science, ATMECE, Mysuru Page 9


VoteGuard 2024-2025

CHAPTER 2

LITERATURE SURVEY
2.1 Introduction

A literature review is a rigorous review of available published knowledge using


summaries, classifications, comparisons, literature reviews, and journal articles of previous
research studies and examines the work of scholars who there is now on this topic, perhaps for
a limited time. It is a collection of data collected from a variety of sources, organized to address
a topic, research objective, or problem issue. For blockchain and facial recognition based e-
voting systems, the integration of these technologies has been explored to improve the security,
transparency and voting processes.

The paper titled "Biometric Voting System Using Blockchain" was published by M.
Madusanka et al. It incorporates blockchain and biometric verification, including facial
fingerprint recognition, to prevent double voting. It also highlights increased voter verification
and enhanced privacy through the use of open source technology. Similarly, "electronic voting
using blockchain technology" by Victor Batista et al. It focuses on a blockchain-enabled
electronic voting system that uses cryptographic protocols for secure and verifiable voting.
This study addresses the effectiveness of non-corruptible election storage and real-time results
aggregation to ensure voter anonymity.

"Blockchain-Based Secure Voting System" by using Usama Chaudhry et al. Discusses a


blockchain-based voting gadget that emphasizes immutability and the advantages of
decentralized ledgers. The proposed framework guarantees secure vote recording and
transparent outcomes, with improved vote integrity and decreased fraud threat confirmed the
usage of Ethereum blockchain. Another huge contribution, "A Secure E-Voting System
Combining Blockchain and Biometric Authentication" with the aid of Xiaoming Zhang et al.,
integrates biometric authentication, specially face reputation, with blockchain for stable and
verifiable elections. The look at demonstrates a considerable discount in identification fraud
and guarantees steady voter participation in disbursed environments.
Department of CSE-Data Science, ATMECE, Mysuru Page 10
VoteGuard 2024-2025

A broader perspective is supplied via "Blockchain and Cryptographic Protocols in E-


Voting: A Systematic Review" through Assel Nurusheva et al., which systematically analyzes
blockchain programs in e-balloting. This paper explores cryptographic improvements that
address protection and transparency troubles, identifying innovations that beautify privateness,
immutability, and trustworthiness in vote casting systems.

Lastly, "Face Recognition-Based Biometric Voting System with Blockchain Integration"


with the aid of Ankit Shukla et al. Develops a blockchain-based totally vote casting system
using stay face reputation to authenticate citizens. This observe emphasizes one-time voting
and fraud prevention, with improved authentication reliability and voter convenience as
compared to standard structures.

These studies collectively underscore the potential of mixing blockchain and biometric
technology to address the challenges of conventional balloting structures. They provide a basis
for developing secure, transparent, and inclusive e-vote casting platforms that could transform
democratic processes global.

Department of CSE-Data Science, ATMECE, Mysuru Page 11


VoteGuard 2024-2025

2.2 Literature Review

 A Review on Blockchain Technology and its applications

Swan, M. (2015) in the book "Blockchain: Blueprint for a New Economy" provides
foundational knowledge about blockchain technology and its potential applications in
secure systems including elections. The author explores how the decentralized and
immutable nature of blockchain can transform traditional systems by introducing
transparency, security and efficiency. The book explores the mechanisms that enable
blockchain to act as an unreliable and distributed ledger, making it an ideal foundation
for secure voting processes Through detailed explanations and examples Swan
establishes blockchain's transformative power over areas that require not only votes but
high levels of trust and credibility. This work provides the necessary insights to
understand the implications of blockchain technology and its role in the modern secure
system, serving as a cornerstone for research and development in e-voting systems.
Together, these studies highlight the potential of combining blockchain and biometric
technologies to address the challenges of traditional voting systems. They provide the
basis for developing secure, transparent and inclusive e-voting platforms that can
transform democratic processes around the world.

 Exploring Blockchain and Biometric Technologies for Secure and Transparent


E – Voting Systems

Zhang , L. , White , J. , Schmidt , D.K. C., & Lenz, G. (2018) in their paper "Applying
blockchain technology for secure electoral processes" for considering the use of
blockchain in electoral processes and highlight the benefits of security transparency. The
authors detail how decentralized blockchain infrastructure ensures vote intangibility and
real-time integrity while preserving voter registration. In this study, blockchain shows a
transformational tool that can overcome the weaknesses and

Department of CSE-Data Science, ATMECE, Mysuru Page 12


VoteGuard 2024-2025

inefficiencies of traditional voting mechanisms. Focusing on distributed ledger


technology, the paper highlights the potential for creating a secure, transparent and
reliable voting system. The findings highlight the flexibility of blockchain technology to
meet the evolving demands of modern electoral systems, making this a significant step
forward in ensuring democratic integrity in the digital age.

 Comprehensive review of Blockchain and Biometric Approaches in E – Voting


Systems

Sharma, T. K. and Bhushan, B. (2020) in the article “Blockchain and Secure


Election Process for Voter Identity Verification” presented Blockchain and Biometric
technology as important tools in verification. Verify voters' identities and ensure a
secure voting system. The authors highlight how integrating these technologies
addresses weaknesses in traditional electoral processes by providing a transparent and
tamper-proof mechanism for verifying voter eligibility. The study explains how the
decentralized and immutable nature of blockchain improves the reliability and security
of voting systems. Meanwhile, biometric technology allows for accurate and unique
voter identification. This approach reduces the risk of fraud, duplication, and distortion.
Make the election process more reliable and efficient. This article highlights the
practical applications of blockchain in modernizing voting systems. and achieve
greater transparency and security in the democratic process.

 Innovative Pathways in Secure E-Voting: A review of Blockchain and Biometric


Integration

Nguyen, Q. The study highlights how to leverage blockchain's decentralized and


transparent nature to create a tamper-proof voting system that guarantees election
integrity. This article highlights the role of blockchain in enhancing security and
increasing trust in election systems. Addressing the weaknesses in the traditional
voting process, it also addresses the broader implications of using blockchain
technology for sustainable development. It demonstrates its adaptability and reliability

Department of CSE-Data Science, ATMECE, Mysuru Page 13


VoteGuard 2024-2025

in various applications. This research demonstrates the potential of blockchain as a


transformative tool to modernize and secure voting systems. This contributes to
broader sustainability goals.

 Foundational Concepts of Deep Neural Networks in Biometric Verification of E-


Voting Systems

Hinton, G., Deng, L., Yu, D., et al. (2012). Although this article mainly focuses
on improving speech recognition, But the ability of deep neural networks to model
complex patterns and properties has also been explored. These insights are highly
relevant to biometric systems. This is because the same principles can be applied to
increase the accuracy and reliability of facial recognition. This study leverages the
computational power of deep learning to reveal how neural networks can process vast
amounts of data to identify unique patterns. This makes neural networks an essential
component of modern biometric systems. This work highlights the importance of
neural network-based approaches in developing safe and effective technologies. for
electronic voting and other applications.

 Machine Learning Innovations in Biometric Verification for Secure Voting


System

King, D. (1999) E. (2009) provides an in-depth discussion of machine learning


techniques used in facial recognition in the report "Dlib-ml: A Machine Learning
Toolkit", which is a key component of this project. Where the real world focuses on
applications It highlights how these techniques contribute to accurate and reliable facial
recognition systems. By processing and analyzing facial characteristics efficiently This
study highlights the importance of effective machine learning tools in improving the
biometric authentication process. This is to ensure a high level of security and user
authentication in systems such as electronic voting. This work serves as a basic
reference for understanding the technological basis for facial recognition and its
integration into security applications.

Department of CSE-Data Science, ATMECE, Mysuru Page 14


VoteGuard 2024-2025

2.3 Outcome of Literature review


Based on the research from the mentioned papers the literature survey highlights that
block chain technology holds promise for revolutionizing voting systems. However,
further research and development are needed to address technical challenges and ensure
the practical implementation of secure and efficient block chain-based on voting solutions.
This approach modernizes the voting process, allowing election authorities to manage
candidates and constituencies efficiently while enabling real-time access to voting data.
With a secure, transparent, and one-vote-per-person setup, this system supports a
trustworthy and reliable electoral experience, fostering greater confidence in democratic
processes. This source provides foundational knowledge for understanding the machine
learning techniques employed in the system, particularly in the domain of face recognition.
This paper delves into machine learning techniques, specifically face recognition, which
are relevant to the technology used in the system being developed. From research from the
documents mentioned A survey of the literature reveals that blockchain technology holds
promise to revolutionize voting systems, however, more research and development is
needed to address the technical challenges. and ensure the safe and efficient practical
implementation of blockchain based on polling solutions. This approach modernizes the
voting process, allowing the EC to effectively manage candidates and constituencies. and
enable access to real-time voting data. By maintaining a secure, transparent, per capita
consensus vote, the system supports a reliable and trustworthy election experience.
Promote greater trust in the democratic process This resource provides a foundation for
understanding machine learning techniques used in systems specific to the field. face
recognition In an in-depth introduction, it is said to be related to the technology used in the
developed system. The literature review highlights the transformative potential of
blockchain and machine learning technology in modernizing voting systems. Blockchain
ensures increased security through tamper-proof records and cryptographic protection.
Reduce election fraud and unauthorized access. Digitizing the voting process also
improves voter access. This makes it possible to vote remotely and securely. This can
increase participation between people with mobility issues or those in remote areas. But

Department of CSE-Data Science, ATMECE, Mysuru Page 15


VoteGuard 2024-2025

scalability remains a major obstacle. This is because supporting millions of voters can
strain network resources. System performance is, and can be, affected. Machine learning
techniques This is especially true in facial recognition. It provides an efficient solution for
voter authentication. Endorse the principle of one person, one vote. Reduces the risk of
impersonation. Additionally, blockchain's immutable ledger supports transparency and
auditability. Promote public confidence in elections Integrating machine learning further
improves the system by enabling fraud detection. Voter Behavior Analysis and balancing
weights during elections. Despite these advantages But there are also ethical and privacy
concerns. This is especially true regarding the management of biometric voting data.
Regulatory and legal barriers must still be resolved to ensure compliance with election law
and data protection standards. In addition, deploying these technologies will require
significant investment in infrastructure, training and Maintenance Overall, blockchain and
machine learning hold great promise in democratizing the voting system by bridging the
gap in traditional methods. This is especially true in areas with unreliable electoral
structures. Promote integration and equality in the democratic process.

Department of CSE-Data Science, ATMECE, Mysuru Page 16


VoteGuard 2024-2025

CHAPTER 3
SYSTEM REQUIREMENTS AND SPECIFICATION

3.1 Hardware requirement

• Ram 4GB
• HDD 20
• Processor Intel I5

• Camera Build IN OR USB Web Cam

3.2 Software requirement

 Operating System Windows 10 OR 11

 Language Python

 Frame Work Flask

 Front End: HTML, CSS, Java Script

 Database: MYSQL

 IDE VS Code

3.3 Tools and Technologies Used

The following are the tools and technologies used in this project:-

 Python:
Python is known for its concise and readable code. Although machine learning and AI
involve complex algorithms and versatile workflows, Python’s simplicity enables
developers to create reliable systems without getting bogged down by the technical details
of the language. This allows them to focus their efforts on solving machine learning
problems. Moreover, Python attracts many developers due to its ease of learning.

Department of CSE-Data Science, ATMECE, Mysuru Page 17


VoteGuard 2024-2025

The code is human-readable, which facilitates the process of building machine learning
models. Many programmers find Python to be more intuitive compared to other
programming languages. Additionally, the abundance of frameworks, libraries, and
extensions available makes it easier to implement various functionalities. It’s widely
recognized that Python is well-suited for collaborative projects involving multiple
developers. As a general-purpose language, Python can handle a range of complex
machine learning tasks and allows for rapid prototyping, enabling quick testing of
machine learning products.

 Visual Studio Code:


Visual Studio Code (VS Code) is a free, open-source, and lightweight code editor
created by Microsoft. It's highly regarded for its performance, flexibility, and strong
ecosystem, making it a top choice for developers in various fields. VS Code supports a
wide array of programming languages, such as Python, JavaScript, C++, Java, and more.
It operates on Windows, macOS, and Linux, ensuring compatibility across platforms.
One of its key features is its extensibility, with a marketplace that offers thousands of
extensions to boost productivity. The built-in terminal allows developers to execute
commands and manage environments without leaving the editor. Advanced tools like
IntelliSense provide smart code completion, syntax highlighting, and error detection,
while integrated debugging tools cater to a variety of programming languages. Smooth
Git and GitHub integration makes version control easier, and the editor's customizability
lets users adjust themes, keyboard shortcuts, and settings to fit their workflows. Even
with its lightweight design, VS Code packs powerful features, and options like Live
Share facilitate effective collaboration among team members.

 Flask:
Flask is a lightweight and flexible web framework for Python that makes building web
applications easier. It follows the microframework philosophy, offering essential tools
for web development while giving developers the freedom to add other libraries and
components as needed. Flask’s user-friendly design and minimalistic approach make it
suitable for a wide range of projects, from simple single-page applications to complex

Department of CSE-Data Science, ATMECE, Mysuru Page 18


VoteGuard 2024-2025

APIs and data-driven platforms. Its modular structure allows for scalability, and its
compatibility with various tools ensures smooth integration for tasks like database
management, authentication, and deployment. With a built-in development server,
comprehensive documentation, and strong community support, Flask enables developers
to write clean and efficient code while keeping flexibility in their applications.

 OpenCV:
OpenCV (Open Source Computer Vision Library) is a widely used and
comprehensive open-source library designed for computer vision and image processing
tasks. Although it is primarily written in C++, it offers strong bindings for Python and
other programming languages, making it accessible to a wide array of developers.
OpenCV finds applications in areas such as object detection, facial recognition, motion
tracking, and image transformation. The library boasts a large collection of optimized
algorithms for real-time computer vision and supports hardware acceleration to
enhance performance. Its versatility allows it to be utilized in various fields, including
robotics, medical imaging, and augmented reality. Additionally, OpenCV integrates
smoothly with machine learning frameworks like TensorFlow and PyTorch, enabling
developers to create powerful AI-driven applications. With extensive documentation
and a supportive community, it serves as a valuable resource for both newcomers and
experienced professionals engaged in innovative vision-based projects.

 HTML:
Hypertext Markup Language (HTML) is the standard markup language used for
creating web pages and web applications. Along with Cascading Style Sheets (CSS)
and JavaScript, it forms a fundamental trio of technologies that underpin the World
Wide Web. Web browsers obtain HTML documents from a web server or local storage
and render them into multimedia web pages. HTML outlines the structure of a web
page semantically and originally included hints for how the document should appear.
HTML elements serve as the building blocks of HTML pages. Using HTML constructs,
images and other objects, like interactive forms, can be embedded into the rendered

Department of CSE-Data Science, ATMECE, Mysuru Page 19


VoteGuard 2024-2025

page. HTML allows for the creation of structured documents by indicating the
structural semantics for text, including headings, paragraphs, lists, links, quotes, and
more. HTML elements are marked by tags, which are written using angle brackets.
Tags like <img /> and <input /> directly insert content into the page, while other tags,
such as <p>, enclose and provide context for the document text and can include other
tags as sub-elements. Although browsers do not display the HTML tags, they use them
to interpret the content of the page.
HTML can also incorporate programs written in scripting languages like JavaScript,
which can influence the behavior and content of web pages. The inclusion of CSS
determines the appearance and layout of the content. The World Wide Web Consortium
(W3C), which oversees both the HTML and CSS standards, has promoted the use of
CSS over explicit presentational HTML since 1997.

 CSS: 
Cascading Style Sheets (CSS) is a style sheet language that describes how a
document written in a markup language, such as HTML, should be presented. CSS is
one of the fundamental technologies of the World Wide Web, alongside HTML and
JavaScript. The purpose of CSS is to separate presentation from content, which
includes aspects like layout, colors, and fonts. This separation enhances content
accessibility, offers greater flexibility and control over presentation characteristics,
allows multiple web pages to share formatting by linking to a single .css file, and
minimizes complexity and redundancy in the structural content.By separating
formatting from content, it becomes possible to display the same markup page in
various styles for different rendering methods, whether on-screen, in print, through
voice (using speech-based browsers or screen readers), or on Braille-based tactile
devices. CSS also includes rules for alternative formatting when content is accessed on
mobile devices.The term "cascading" refers to the priority scheme that determines
which style rule applies when multiple rules match a specific element. This cascading
priority scheme is designed to be predictable.The World Wide Web Consortium (W3C)
maintains the CSS specifications.

Department of CSE-Data Science, ATMECE, Mysuru Page 20


VoteGuard 2024-2025

The Internet media type (MIME type) text/css was registered for CSS use by RFC 2318
in March 1998. The W3C also provides a free validation service for CSS
documents.Besides HTML, other markup languages that support CSS include
XHTML, plain XML, SVG, and XUL.

 MySQL: 
MySQL is a popular open-source relational database management system (RDBMS)
known for its reliability, performance, and user-friendliness. It uses Structured Query
Language (SQL) to manage and manipulate data, making it suitable for everything from
small websites to large enterprise systems. MySQL offers features such as multi-user
access, strong data security, and scalability, which enable it to efficiently handle large
datasets and multiple user operations at the same time. It works well with various
programming languages, including Python, PHP, and Java, making it a flexible choice for
different application environments. Additionally, MySQL provides robust tools for
database backup, replication, and optimization, ensuring high availability and effective
disaster recovery. With a strong community and thorough documentation, MySQL
remains a key technology for developers looking for a reliable and scalable database
solution.

Department of CSE-Data Science, ATMECE, Mysuru Page 21


VoteGuard 2024-2025

3.4 Functional Requirements

1. Voter Registration and Authentication:


o Voters must register with essential details like Aadhar ID, Voter ID, and
constituency.
o During registration, facial data is captured and trained using face recognition for
biometric authentication.
o Voters can log in using their Voter ID and Aadhar ID.
o A live face recognition process is initiated for voter verification.
o The system ensures that only registered voters with matching facial data can
authenticate.

2. Voting Process:
o Voters can view a list of candidates and their political parties once authenticated.
o Voters can cast their vote for a candidate, which is securely stored on a blockchain
to ensure tamper-proof record-keeping.
o Voters can vote only once. Multiple voting attempts from the same voter are
blocked.
o After voting, voters are automatically logged out.

3. Election Authority Management:


o Election authorities can log in using their credentials stored in a MySQL database.
o Authorities can add constituencies, register candidates, and map them to
constituencies.
o Authorities can activate or deactivate voting sessions for constituencies.
o Election authorities can view real-time vote counts for candidates.

4. Blockchain Integration:
o Votes are securely stored on a custom blockchain to ensure the immutability and
transparency of the election process.
o Blockchain records are tamper-proof, ensuring the integrity of the voting data.

Department of CSE-Data Science, ATMECE, Mysuru Page 22


VoteGuard 2024-2025

5. Security and Privacy:


o The system ensures secure login processes for both voters and election authorities.
o Voter details and facial data are securely stored and encrypted to protect user
privacy.

3.5 Non-Functional Requirements

1. Performance:
o The system should be able to handle a large number of simultaneous voter logins
and votes without performance degradation.
o Real-time vote counts and data updates must be fetched from the blockchain
without significant delays.

2. Scalability:
o The system must be scalable to accommodate an increasing number of voters,
constituencies, and candidates as the election size grows.
o The blockchain should be able to scale with the number of votes, ensuring
efficient storage and retrieval.

3. Availability:
o The system must be available 24/7, especially during voting sessions, to ensure
uninterrupted access for voters and election authorities.
o It should be able to handle peak loads during election periods.

4. Reliability:
o The system must ensure high reliability, with minimal downtime and no data loss
during voting and blockchain operations.
o The system should provide error-free authentication and vote logging processes.

Department of CSE-Data Science, ATMECE, Mysuru Page 23


VoteGuard 2024-2025

5. Security:
o The system must ensure secure transmission of data, including voter credentials
and vote information, using encryption protocols.
o The system should prevent unauthorized access to voter data and election records.
o Blockchain transactions should be secured to prevent tampering or fraudulent
voting attempts.

6. Usability:
o The user interface for both voters and election authorities must be simple and
intuitive to use.
o Voters should easily navigate the system for registration, authentication, and
voting.

7. Compliance:
o The system must comply with privacy regulations, ensuring that voter data is
handled and stored securely in accordance with data protection laws.
o The use of biometric data for authentication must follow legal guidelines for
consent and privacy.

8. Maintainability:
o The system should be easy to maintain and update, especially for election
authorities to manage constituencies, candidates, and voting sessions.
o The codebase should be modular to facilitate troubleshooting and enhancements.

Department of CSE-Data Science, ATMECE, Mysuru Page 24


VoteGuard 2024-2025

CHAPTER 4

SYSTEM ANALYSIS AND DESIGN

4.1 System Analysis

The VoteGuard project is designed to ensure the secure and efficient handling of digital
voting processes. The system incorporates various tools and technologies to achieve reliability,
scalability, and user-friendliness. The project’s user interface is developed using lightweight
and responsive web frameworks, ensuring an intuitive user experience for tasks such as
authentication, ballot selection, and vote submission. Flask serves as the backend framework,
providing the necessary structure for server-side logic, database interactions, and secure
communication. MySQL is utilized for database management, storing critical data like user
credentials and voting records, while OpenCV handles image processing tasks such as facial
recognition for added security. Visual Studio Code streamlines the development process with
its versatile coding environment and Git integration for effective collaboration. Security
measures, including encryption and data validation, protect the system from unauthorized
access, while its modular architecture ensures scalability to accommodate growing user
demands. By integrating these technologies, the VoteGuard project addresses modern voting
challenges, prioritizing security, efficiency, and user accessibility.

4.1.1 Feasibility Study: The feasibility of the project is analyzed in this phase and business
proposal is put forth with a very general plan for the project and some cost estimates. During
system analysis the feasibility study of the proposed system is to be carried out. This is to
ensure that the proposed system is not a burden to the company. For feasibility analysis, some
understanding of the major requirements for the system is essential. Three key considerations
involved in the feasibility analysis are as follows:-

 Technical Feasibility:
Integration of proven tools and technologies like Flask, MySQL, and OpenCV.

Department of CSE-Data Science, ATMECE, Mysuru Page 25


VoteGuard 2024-2025

Flask provides a robust backend framework for server-side logic and secure
communication. MySQL offers reliable database management for storing sensitive voting
records and user information.OpenCV enables advanced security measures such as facial
recognition.The technologies are well-documented, widely supported, and capable of
handling project requirements.

 Operational Feasibility:
The system aligns with the needs of modern voting systems by prioritizing security,
accessibility, and efficiency.A user-friendly interface ensures ease of use for voters.The
backend infrastructure supports smooth operations and scalability.Training and support
mechanisms can be implemented for administrators to manage the system effectively.The
system addresses critical concerns such as voter authentication and data integrity.

 Economic Feasibility:
Leverages open-source tools, reducing initial costs significantly.Expenses related to
hardware, hosting, and maintenance are manageable within a reasonable budget.Cost
savings from minimizing manual voting processes and enhancing election security justify
the investment.

Overall, the VoteGuard project demonstrates high feasibility, with strong technical
support, operational efficiency, and cost-effectiveness ensuring its successful
implementation.

4.2 System Architecture

The system architecture for the Blockchain and Face Recognition-Based Voting
System is designed to ensure security, scalability, and efficiency. The architecture includes
three major layers: the User Interface Layer, the Application Layer, and the Data Layer. Each
layer interacts to provide secure voting functionality, face recognition-based authentication,
and blockchain-driven data integrity.

Department of CSE-Data Science, ATMECE, Mysuru Page 26


VoteGuard 2024-2025

1. User Interface Layer (Frontend)


 Voter Interface: A web-based interface developed using HTML/CSS/JavaScript and
Flask templates, allowing voters to log in using their credentials (Voter ID, Aadhar ID),
interact with the face recognition system, and cast their vote.
 Election Authority Interface: A separate login interface for election authorities to manage
constituencies, candidates, and voters, as well as monitor voting results.
 Camera Interface: The system activates the camera through the browser to capture and
verify voter faces using the live camera feed during login.

2. Application Layer (Backend)


 Flask Web Application: The core of the system is built using Python Flask, which serves
the following functionalities:
 Voter Registration and Face Recognition: Implements voter registration, capturing
Aadhar ID, Voter ID, and constituency, and uses the Python `face_recognition` module
to capture and store facial features for biometric authentication.
 Login and Authentication: Voter authentication through a combination of credentials
and face recognition. The system verifies the voter’s identity by comparing the live
camera feed with stored face data.
 Voting Process: Once authenticated, the system checks if voting is active in the voter’s
constituency and presents a list of candidates and their party details. After voting, the
system logs the vote into the blockchain and prevents re-voting.
 Blockchain Voting Ledger: A custom blockchain implementation records each vote.
Each vote transaction is hashed and stored in a block, ensuring immutability and
transparency. The blockchain maintains a distributed ledger that election authorities can
view for real-time results.
 Constituency and Voting Management: Election authorities can activate/deactivate
constituencies and add or manage candidates, constituencies, and voters.

Department of CSE-Data Science, ATMECE, Mysuru Page 27


VoteGuard 2024-2025

3. Data Layer
 MySQL Database: Stores election-related data, including voter credentials (Aadhar ID,
Voter ID), constituency data, and registered candidates. The face recognition data (face
embeddings) is also stored here.
 Blockchain: The blockchain acts as the ledger for storing voting transactions. Each vote
is securely stored in a block with cryptographic hashing, ensuring that once a vote is
recorded, it cannot be altered or tampered with. This layer provides tamper-proof data
storage and real-time tracking of votes for election authorities.

Figure 4.1: Proposed model Architecture

The figure 4.1 shows the proposed model architecture of a secure blockchain and face
recognition based E-voting system.

Department of CSE-Data Science, ATMECE, Mysuru Page 28


VoteGuard 2024-2025

4.3 Detailed Design

The VoteGuard project’s detailed system design aims to establish a secure, efficient, and
user-friendly digital voting platform. The architecture is structured into three main layers:
frontend, backend, and database, each carefully crafted to ensure smooth functionality. The
frontend is built using HTML, CSS, and JavaScript, providing a responsive and interactive user
experience. It includes accessibility features like mobile compatibility to serve a wide range of
users. The user interface is designed to be intuitive, guiding individuals through the processes
of voter registration, ballot selection, and results viewing with ease. The backend utilizes Flask,
a lightweight yet powerful Python framework, which manages server-side logic, user sessions,
and secure API endpoints for data interaction. Flask’s modular design allows for seamless
integration with other technologies and delivers high performance, which is crucial for real-
time voting systems. To enhance security, advanced measures such as OpenCV-based biometric
facial recognition are employed to authenticate voters and prevent unauthorized access,
ensuring that only eligible individuals can participate in the voting process. The database layer
uses MySQL to store and manage essential information, including voter credentials, ballot data,
and voting records. A well-organized schema maintains data integrity through normalization
and employs indexing to improve query performance. Encryption techniques protect sensitive
data, both at rest and in transit, against potential breaches. The database is designed to
efficiently handle concurrent access, supporting scalability for large-scale voting events. The
system is divided into several modules, each focusing on specific functionalities. The
Authentication Module employs hashed passwords and token-based mechanisms to secure user
credentials, enhanced by OpenCV’s capabilities. The Authentication Module utilizes hashed
passwords and token-based mechanisms to secure user credentials, augmented by OpenCV’s
facial recognition for multi-factor authentication. Role-based access control (RBAC) is
implemented to differentiate functionalities between voters and administrators, ensuring
restricted access to sensitive operations. The Voting Module oversees the core voting process,
ensuring that each voter can cast their ballot once and that votes are securely recorded in the
database. It incorporates real-time validation mechanisms to maintain the integrity of the
election process.
Department of CSE-Data Science, ATMECE, Mysuru Page 29
VoteGuard 2024-2025

The Admin Module equips election organizers with tools for setting up and monitoring voting
sessions. Administrators can manage user accounts, create and close voting sessions, and
analyze results through interactive dashboards. The system also includes an Audit Log
Module to maintain a comprehensive record of system activities, enhancing transparency and
accountability. This module tracks user actions, such as login attempts, data modifications,
and administrative operations, enabling thorough audits when required. Security is a
cornerstone of the VoteGuard system. The Security Module implements end-to-end
encryption for all data transmissions using SSL/TLS protocols. Additionally, the system is
fortified against common cyber threats such as SQL injection, cross-site scripting (XSS), and
distributed denial-of-service (DDoS) attacks through input validation, firewalls, and rate-
limiting mechanisms.

The workflow begins with users accessing the platform via the web interface. New users
undergo a registration process involving identity verification, which includes biometric
authentication for voters. Upon successful registration, users can log in to the system and
participate in ongoing voting sessions. The voting process involves selecting a candidate or
option on the ballot, confirming the choice, and securely submitting the vote. The system
records the vote in the database while maintaining anonymity, adhering to privacy standards
are upheld throughout the voting process. After the voting session ends, administrators can
easily calculate and share the results via the admin dashboard. Voters can also access
summaries of their participation without disclosing individual votes, which maintains both
transparency and confidentiality. The testing and quality assurance process guarantees the
reliability and strength of the VoteGuard platform. Unit tests are performed on individual
modules to confirm their functionality, while integration tests check how different
components work together. Security tests are conducted to uncover any vulnerabilities in
authentication, data storage, and transmission. Usability testing ensures that the interface is
user-friendly and accessible to all, including those with limited technical skills. After
deployment, the system is continuously monitored to spot and resolve performance issues and
security threats. Regular database backups and disaster recovery plans are in place to protect

Department of CSE-Data Science, ATMECE, Mysuru Page 30


VoteGuard 2024-2025

data integrity and availability in case of unexpected events. The system is built for
scalability and maintainability. Its modular design allows for the easy addition of new features
or updates without interfering with existing functions. The platform is hosted on cloud
infrastructure to take advantage of elastic scalability and high availability, ensuring reliable
performance even during peak times. Maintenance includes routine software updates, such as
security patches and feature improvements, to keep the system in line with changing
technology and user requirements. Detailed documentation aids developers and administrators
in effectively managing the system.

The comprehensive design of the VoteGuard system combines cutting-edge technologies


such as Flask, OpenCV, and MySQL into a unified framework that emphasizes security,
efficiency, and user experience. By focusing on essential elements like modularity, scalability,
and robustness, the design guarantees that the platform can effectively facilitate digital voting
processes while upholding the core values of democracy.

Department of CSE-Data Science, ATMECE, Mysuru Page 31


VoteGuard 2024-2025

CHAPTER 5

METHODOLOGY AND IMPLEMENTATION

5.1 Methodology

The methodology for developing a Face Recognition and Blockchain-Based E-Voting


System involves several structured phases to ensure an efficient and secure implementation.
First, the project begins with problem definition and requirement analysis, where the need for
a secure and transparent e-voting system is established, and system objectives such as accurate
voter authentication, privacy preservation, and tamper-proof vote recording are defined. Next,
the system design phase includes creating a modular architecture that integrates face
recognition and blockchain technologies. This involves designing a user-friendly interface,
selecting tools for blockchain, and outlining the data flow from voter authentication to vote
storage and result tallying.

For the face recognition module, the methodology includes collecting voter facial data
during registration while ensuring compliance with data protection laws. The collected data is
preprocessed through normalization and enhancement techniques, and unique features are
extracted using deep learning models . Real-time authentication matches live inputs against
stored profiles using similarity metrics, and anti-spoofing measures like liveness detection
prevent fraudulent access. Simultaneously, the blockchain module is established by deploying
a permissioned blockchain with a suitable consensus mechanism, such as Proof of Authorit y
(PoA), to ensure efficient and secure vote transactions. Smart contracts automate critical
processes like voter verification, vote submission, and tallying, while cryptographic
techniques like Zero-Knowledge Proofs (ZKP) safeguard voter anonymity and encrypt
sensitive data for storage.The integration phase ensures seamless communication between the
face recognition system and blockchain through an API layer, connecting the frontend
interface, middleware, and backend blockchain. Testing follows, including unit tests for
individual components, integration tests for system interactions, performance tests under high
loads, and security tests to identify vulnerabilities and resistance to attacks. Once validated,

Department of CSE-Data Science, ATMECE, Mysuru Page 32


VoteGuard 2024-2025

the system is deployed on a secure cloud infrastructure, accompanied by user training sessions.
Post-deployment, the system is continuously monitored for performance and security, with
periodic updates to improve algorithms and smart contracts. The methodology concludes with
comprehensive documentation of the system’s architecture, implementation, and testing,
ensuring clarity for stakeholders and enabling future enhancements. This approach ensures
the development of a robust, scalable, and secure e-voting system that addresses the challenges
of traditional voting methods.

5.2 Implementation

ELECTION AUTHORITY:

Figure 5.1 : Flowchart of Election Authority module.



The Figure 5.1 shows the flowchart of Election Authority module outlines the key processes

Department of CSE-Data Science, ATMECE, Mysuru Page 33


VoteGuard 2024-2025

and decision points required to manage an election in a blockchain-based e-voting system.

Election module:
Input:
Voter database (including voter IDs and registration status).
Candidate database (list of candidates and their IDs).
Blockchain ledger (for vote storage and results tallying).
Output:
Voter authentication confirmation.
Vote validation and storage.
Real-time or post-election results.
Steps:
1. Initialize System:
 Load the voter and candidate databases.
 Establish a connection to the blockchain network.
 Deploy necessary smart contracts for vote management.
2. Verify Election Start:
 Ensure the current date/time is within the authorized election period.
 If the election is inactive, deny voting access and notify users.
3. Voter Authentication:
 Receive voter login request with ID and biometric data (e.g., facial image).
 Query the Face Recognition Module for voter authentication.
o If authenticated:
 Verify the voter’s registration and eligibility (e.g., age, region).
 Mark the voter as "active" for this session.
o If authentication fails, deny access and log the attempt.
4. Vote Casting:
 Allow authenticated voters to select their candidate from the candidate list.
 Validate the selection:
o Ensure the candidate ID exists in the database.
Department of CSE-Data Science, ATMECE, Mysuru Page 34
VoteGuard 2024-2025

o Prevent duplicate votes from the same voter ID.


 Generate a secure transaction for the vote:
o Use a one-time session token for security.
o Encrypt the vote data.
5. Blockchain Storage:
 Submit the validated vote as a transaction to the blockchain.
 Confirm successful recording on the blockchain ledger.
6. Monitor Voting Process:
 Continuously monitor the blockchain for vote submissions.
 Maintain a real-time count of votes per candidate.
7. End Voting:
 At the end of the election period:
o Disable new vote submissions.
o Retrieve the final vote tally from the blockchain.
o Verify the integrity of the results using blockchain transaction logs.
8. Result Declaration:
 Announce the results after ensuring no discrepancies.
 Provide a mechanism for public verification via blockchain transaction records.
9. Audit and Reporting:
 Generate an audit report, including:
o Total votes cast.
o Voter turnout (percentage of registered voters who voted).
o Any anomalies or irregularities detected.
 Archive data for regulatory compliance and future reference.

Department of CSE-Data Science, ATMECE, Mysuru Page 35


VoteGuard 2024-2025

This algorithm ensures a transparent, secure, and efficient election process by leveraging
blockchain and biometric technologies.
Algorithm: Election Authority Module
1. [Initialize] Start.
2. [Input Parameters]
 Load voter_database (list of registered voters and their statuses).
 Load candidate_list (list of candidates).
 Connect to the blockchain_network for vote storage.
 Set election period (start_time and end_time).
3. [Verify Election Status]
 If current_time is outside start_time and end_time:
o Display "Election not active."
o Exit.
4. [Authenticate Voter]
 Receive voter_id and biometric_data from the Voter Module.
 Call FaceRecognitionModule(voter_id, biometric_data).
 If authentication fails:
o Return "Authentication failed."
o Log the attempt.
 Else: Check voter_database for:
o Eligibility status.
o Voting status (ensure the voter hasn’t already voted).
o If ineligible or already voted: Return appropriate error and terminate session.
5. [Receive Vote]
 Get candidate_id from the Voter Module.
 Validate the candidate_id:
o If invalid: Return "Invalid candidate."
o Else: Proceed to vote submission.

Department of CSE-Data Science, ATMECE, Mysuru Page 36


VoteGuard 2024-2025

6. [Encrypt and Store Vote]


 Create a secure transaction:
o Include encrypted voter_id, selected candidate_id, and timestamp.
 Submit the encrypted vote to the blockchain.
 If submission is successful:
o Mark the voter as "voted" in the voter_database.
o Return "Vote successfully recorded."
 Else: Return "Vote submission failed."
7. [Monitor Voting Process]
 Continuously track blockchain transactions to tally votes.
 Detect and log any anomalies in real-time.
8. [End Voting]
 After end_time, terminate vote submissions.
 Retrieve final vote tally from the blockchain.
 Verify the integrity of the results using blockchain logs.
9. [Declare Results]
 Announce results:
o Display candidate names and their vote counts.
 Allow stakeholders to verify results via blockchain public records.
10. [Audit and Reporting]
 Generate a comprehensive audit report:
o Total votes cast.
o Voter turnout statistics.
o Any anomalies detected.
 Store the report for compliance and future reference.
11. [Finished] Stop.

Department of CSE-Data Science, ATMECE, Mysuru Page 37


VoteGuard 2024-2025

VOTERS MODULE:

Figure 5.2: Flowchart of voter module.

The Figure 5.2 shows The flowchart for the Voters Module illustrates the step-by-step process
that a voter follows to cast their vote in the blockchain-based e-voting system.

Voter Module
Input:
 Voter ID and biometric data (e.g., facial image).
 Candidate list fetched from the Election Authority Module.
Output:
 Vote submission confirmation.
 Updated voter status.

Department of CSE-Data Science, ATMECE, Mysuru Page 38


VoteGuard 2024-2025

Steps:
1. Initialize the Module:
 Display a welcome message and election information.
 Fetch the candidate list from the Election Authority Module.
 Load configurations (election period, encryption keys, etc.).
2. Voter Login:
 Prompt the voter to enter their Voter ID.
 Capture biometric data (e.g., live facial image).
 Call the Face Recognition Module to authenticate the voter:
o If authentication succeeds:
 Verify the voter’s eligibility and registration status.
 Proceed to vote casting.
o If authentication fails:
 Deny access and notify the voter.
3. Display Candidate List:
 Show the list of candidates, including their names and identifiers.
 Prompt the voter to select a candidate by entering the corresponding ID.
4. Validate Vote:
 Check that the selected candidate ID exists in the candidate list.
 Confirm the voter's choice:
o If confirmed, proceed to submit the vote.
o If not, allow the voter to re-select a candidate.
5. Submit the Vote:
 Create a secure vote transaction:
 Include Voter ID (anonymized or hashed), Candidate ID, and timestamp.
 Encrypt the transaction using a secure encryption method.
 Send the encrypted vote to the Election Authority Module for blockchain storage.

Department of CSE-Data Science, ATMECE, Mysuru Page 39


VoteGuard 2024-2025

6. Confirm Vote Submission:


 Receive acknowledgment from the Election Authority Module.
 If successful:
o Mark the voter as "voted" in the local system.
o Display a confirmation message: "Your vote has been recorded successfully."
 If unsuccessful:
o Notify the voter of the error and provide instructions to retry.
7. Log Out:
 End the voting session.
 Ensure all temporary data is cleared to protect voter privacy.
This structured algorithm ensures secure voter authentication, valid vote submission, and a
smooth user experience.

Algorithm: Voters Module

1. [Initialize] Start.

2. [Input Parameters]

 Read voter_id (unique identifier for the voter).

 Capture biometric_data (e.g., facial image).

 Fetch candidate_list (list of available candidates).

3. [Authenticate Voter]

 Call FaceRecognitionModule(voter_id, biometric_data).

 If authentication is successful:

o Verify voter eligibility using CheckEligibility(voter_id).

 If eligible: Proceed to vote casting.

 Else: Display "Voter not eligible to vote" and terminate session.

 Else: Display "Authentication failed" and terminate session.


Department of CSE-Data Science, ATMECE, Mysuru Page 40
VoteGuard 2024-2025

4. [Display Candidate List]

 Show the names and IDs of all candidates from candidate_list.

 Prompt the voter to select a candidate by entering the candidate ID.

5. [Validate Vote]

 If the entered candidate ID is not in candidate_list:

o Display "Invalid selection" and prompt the voter to re-enter.

 Else: Confirm the voter’s choice.

o If the voter confirms: Proceed to vote submission.

o Else: Allow re-selection.

6. [Submit the Vote]

 Create a secure vote transaction containing:

o Encrypted voter_id, selected candidate_id, and timestamp.

 Send the vote transaction to the ElectionAuthorityModule.

 If submission is successful:

o Mark the voter as "voted."

o Display "Your vote has been successfully recorded."

 Else: Display "Vote submission failed. Please try again."

7. [Log Out]

 End the voting session.

 Clear temporary data to ensure voter privacy.

8. [Finished] Stop.

Department of CSE-Data Science, ATMECE, Mysuru Page 41


VoteGuard 2024-2025

How Blockchain Works in the Election System:

In this project, blockchain acts as the backbone for securely and transparently recording
votes and managing results. Each vote is considered a transaction and is logged on a
decentralized ledger. Smart contracts on the blockchain enforce rules like voter eligibility,
ensuring one person can only vote once, and securely logging votes with timestamps. When a
voter casts their vote, the system encrypts their ID for anonymity, links it to the chosen
candidate's ID, and submits this information as a transaction to the blockchain network. The
network then validates the transaction, confirming its integrity and adherence to election rules
before adding it to the blockchain. Once recorded, the vote is immutable, ensuring that the
records cannot be tampered with. Real-time tallying is possible by querying the blockchain, and
the system's decentralized nature guarantees transparency while preventing unauthorized
access. By utilizing blockchain, stakeholders can verify election results while protecting voter
privacy, making the system secure, auditable, and resistant to manipulation.

Blockchain is used as the backbone for secure, transparent, and tamper-proof vote
recording and result tallying in the e-voting system. Here's a step-by-step explanation of how it
integrates and functions in this project:

1. Decentralized Ledger

 Blockchain is a distributed ledger shared across multiple nodes in a network.

 Each vote is treated as a transaction and is recorded on the blockchain.

 All participants in the network have a synchronized copy of the ledger, ensuring
transparency.

2. Key Features Used in the Project

 Immutability: Once a vote is recorded, it cannot be altered, ensuring tamper-proof records.

 Transparency: Votes are publicly verifiable without compromising voter privacy.

 Security: Cryptographic methods protect the data, preventing unauthorized access.

3. Workflow Integration

Department of CSE-Data Science, ATMECE, Mysuru Page 42


VoteGuard 2024-2025

Step 1: Smart Contract Deployment

 A smart contract is deployed on the blockchain to manage vote submissions.

 The smart contract defines rules such as:

o Ensuring only eligible voters can cast votes.

o Validating that each voter can vote only once.

o Logging votes with associated timestamps.

Step 2: Vote Submission

 When a voter casts a vote:

o A transaction is created containing:

 Encrypted voter ID (to ensure anonymity).

 Candidate ID (indicating the vote choice).

 Timestamp.

o The transaction is sent to the blockchain network.

Step 3: Validation

 The blockchain network validates the transaction:

o Checks the integrity of the data.

o Ensures the voter hasn’t already cast a vote (via the smart contract).

 Once validated, the transaction is added to a new block.

Step 4: Block Creation and Mining

 Transactions are grouped into a block.

 The block is validated and mined (proof of work, proof of stake, or another consensus
algorithm is used depending on the blockchain type).

 The block is added to the blockchain, making the vote permanently recorded.
Department of CSE-Data Science, ATMECE, Mysuru Page 43
VoteGuard 2024-2025

Step 5: Real-Time Tallying

 The smart contract tracks the total votes for each candidate.

 Results can be retrieved in real-time by querying the blockchain.

Step 6: Post-Election Verification

 The blockchain ledger can be publicly verified:

o Anyone with access to the blockchain can audit the transactions.

o The anonymity of voters is preserved as voter IDs are encrypted

Example:

If a voter casts a vote:

The transaction might look like:

"voter_id": "encrypted_hash",

"candidate_id": "C102",

"timestamp": "2024-12-27T10:30:00Z"

This transaction is validated, encrypted, and stored in the blockchain.

When tallying votes:The smart contract queries all transactions on the blockchain and sums up
the votes for each candidate.

Department of CSE-Data Science, ATMECE, Mysuru Page 44


VoteGuard 2024-2025

Algorithm: Blockchain Module

1. [Initialize] Start.

2. [Input Parameters]

 Load voter_id (unique identifier for the voter).

 Receive candidate_id (vote choice selected by the voter).

 Get the current timestamp (time of vote submission).

3. [Preprocess and Encrypt Data]

 Encrypt voter_id using a secure cryptographic algorithm to preserve anonymity.

 Create a vote_transaction object containing:

o Encrypted voter_id.

o candidate_id.

o timestamp.

4. [Validate Transaction]

 Check if voter_id has already voted by querying the blockchain for previous
transactions with the same voter ID:

o If a match is found: Reject the transaction and return "Duplicate vote detected."

o Otherwise: Proceed to the next step.

5. [Create a New Block]

 Gather multiple valid transactions into a block.

 Add metadata to the block, including:

o Previous block hash.

o Current block_number.

o Nonce (for proof-of-work or other consensus mechanisms).


Department of CSE-Data Science, ATMECE, Mysuru Page 45
VoteGuard 2024-2025

6. [Consensus Mechanism]

 Use the network's consensus algorithm (e.g., Proof of Work or Proof of Stake) to
validate the block:

o Miners/validators solve a computational problem or validate stake-based


participation.

o If the block is validated, proceed to the next step.

7. [Add Block to Blockchain]

 Append the new block to the blockchain by linking it to the previous block via its hash.

 Update the blockchain across all nodes in the network to maintain synchronization.

8. [Real-Time Vote Tallying]

 Update the vote count for candidate_id by querying and tallying all transactions
recorded in the blockchain.

9. [Output Results]

 Return confirmation of successful vote submission to the voter.

 Provide a transaction ID for the voter to verify their vote in the blockchain.

10. [Monitor and Audit]

 Continuously monitor blockchain integrity by verifying block hashes and transaction


logs.

 Detect and log anomalies in real time for audit purposes.

11. [Finished] Stop.

Department of CSE-Data Science, ATMECE, Mysuru Page 46


VoteGuard 2024-2025

FACE RECOGNITION MODULE:

The Face Recognition Module in the e-voting system plays a crucial role in ensuring secure and
efficient voter authentication. It does this by verifying a voter's live facial image against the
biometric data that has been pre-registered in the database. When a voter enters their unique
voter ID, the system captures their live facial image through a camera. This image then goes
through preprocessing steps, which include face detection, alignment, and feature extraction,
resulting in a numerical representation of the face known as a feature vector. The system
retrieves the corresponding feature vector from the database and compares the two using
similarity metrics like cosine similarity or Euclidean distance. If the similarity score meets or
exceeds a set threshold, the voter is authenticated and allowed to proceed. If not, access is
denied, and the attempt is logged. Additionally, the module features liveness detection to thwart
spoofing attempts using photos or videos. With encrypted data storage and real-time processing,
the Face Recognition Module guarantees high accuracy, security, and privacy, making it an
essential part of the e-voting system.

How the Face Recognition Module Works in the Project

The Face Recognition Module ensures voter authentication by verifying the voter’s live facial
image against pre-registered biometric data stored in the database. Here's a step-by-step
explanation of its operation:
1. Data Input
 Voter ID: The unique identifier submitted by the voter during login.
 Live Facial Image: Captured in real-time using a camera or webcam.
 Registered Biometric Data: Pre-stored facial data (as feature vectors) in the system’s
database.
2. Preprocessing the Captured Image
 The live facial image is preprocessed to improve accuracy:
o Face Detection: Identify and isolate the face from the captured image using algorithms
CNN-based models.
o Grayscale Conversion: Simplify the image for computational efficiency (if needed).
o Alignment: Align the detected face to ensure consistency with registered data.

Department of CSE-Data Science, ATMECE, Mysuru Page 47


VoteGuard 2024-2025

3. Feature Extraction
 The system extracts unique facial features from the preprocessed image using a deep
learning model (e.g., FaceNet, Dlib, or OpenCV).
 These features are converted into a feature vector, which is a numerical representation of
the face.
4. Comparison with Registered Data
 The feature vector of the live image is compared to the registered feature vector for the
provided voter ID.
 A similarity metric is used, such as:
o Cosine Similarity: Measures the cosine of the angle between two vectors.
o Euclidean Distance: Calculates the straight-line distance between two vectors.
5. Authentication Decision
 The system checks if the similarity score meets or exceeds a predefined threshold:
o Successful Match: If the score is above the threshold, the voter is authenticated and
allowed to proceed.
o Failed Match: If the score is below the threshold, access is denied, and an error
message is displayed.
6. Output and Logging
 If authentication succeeds:
o Display a success message (e.g., "Authentication successful. Welcome!").
o Allow the voter to cast their vote.
 If authentication fails:
o Display an error message (e.g., "Authentication failed. Please try again.").
o Log the failed attempt for security purposes.

Department of CSE-Data Science, ATMECE, Mysuru Page 48


VoteGuard 2024-2025

Algorithm: Face Recognition Module


1. [Initialize] Start.
2. [Input Parameters]
 Accept voter_id (unique identifier for the voter).
 Capture live_facial_image using a camera.
 Load registered_biometric_data from the database associated with voter_id.
3. [Preprocess Input Data]
 Convert the live_facial_image to grayscale if required.
 Detect and extract the face region using a face detection algorithm (e.g., Haar
cascades or CNN-based face detectors).
 Align and normalize the face for consistent feature extraction.
4. [Extract Features]
 Use a pre-trained face recognition model (e.g., FaceNet, Dlib) to generate a feature
vector from the live_facial_image.
5. [Retrieve Registered Features]
 Query the database for the pre-stored feature vector associated with the provided
voter_id.
6. [Compare Features]
 Calculate the similarity between the live_feature_vector and the
registered_feature_vector using a similarity metric:
o Use cosine similarity or Euclidean distance.
7. [Authentication Decision]
 If the similarity score ≥ pre-defined threshold:
o Authentication is successful.
o Allow the voter to proceed.
 Else:
o Authentication fails.
o Deny access and log the failed attempt.
8. [Output Results]
 Return the authentication status (Success or Failure).
Department of CSE-Data Science, ATMECE, Mysuru Page 49
VoteGuard 2024-2025

 Display appropriate messages:


o Success: "Authentication successful. You may proceed."
o Failure: "Authentication failed. Please try again or contact support."
9. [Finished] Stop.
This algorithm ensures that the Face Recognition Module provides secure, accurate, and
efficient voter authentication in the e-voting system. It incorporates preprocessing, feature
extraction, and comparison steps to verify the voter identity effectively.

Department of CSE-Data Science, ATMECE, Mysuru Page 50


VoteGuard 2024-2025

Chapter 6

TESTING

In the context of project development testing is a critical phase that ensures the
functionality, reliability, and performance of the system. This testing process can be broken
down into various levels, with unit testing, system testing, and validation testing being some
of the primary stages. Each of these testing phases plays an essential role in verifying that a
system behaves as expected under different conditions. Testing is the process of systematically
examining a system to ensure that it conforms to required standards and functions as intended.
Testing for a blockchain face recognition based secure e-voting system includes ensuring that
the blockchain effectively stores and records votes consistently while maintaining transparency
ensuring that facial recognition technology accurately identifies voters and prevents
unauthorized access. In addition, testing examines the reliability of the system under various
circumstances, its usefulness to candidates, and its ability to handle multiple tasks Security
testing is critical to identify and fix vulnerabilities, ensuring that system is not resistant to
hacking and fraud. Overall, the testing validates the performance, accuracy, and reliability of
the system prior to its use in real-world election scenarios.

6.1 Unit Testing

Unit testing is one of the earliest and most fundamental levels of testing, focusing on
verifying the individual components or functions of a system in isolation. The main goal of
unit testing is to ensure that each small unit of code performs as expected before combining
them into larger subsystems or the final product. Unit testing is an important step in designing
a secure blockchain keynote-based e-voting system, as it focuses on checking how individual
components work separately Each module of the system is tested separately to ensure that it
performs as expected before installing it into the overall system . Unit testing for the blockchain
module ensures that votes are recorded accurately, data remains unaltered, and encryption
mechanisms work safely without any vulnerabilities as well as stringent testing in the face

Department of CSE-Data Science, ATMECE, Mysuru Page 51


VoteGuard 2024-2025

recognition module to ensure it properly identifies voters, addresses conditions such as light or
facial changes and unauthorized access obstruction. Interconnections between these modules
are also tested to ensure a smooth flow of data, such as ensuring that verified voter data is
properly encrypted and recorded on the blockchain Unit testing also includes aspects such as
the user interface, to ensure that it is intelligible and error-free, and users through the voting
process In this process to successfully navigate Conditions such as invalid inputs, network
failures, or errors that occur during polling are tested to ensure that the system can properly
handle and recover from such events Unit testing by handling potential errors at this stage is
supported provide a secure, reliable, and credible e-voting platform ready for integration and
further testing Being this detailed and focused approach is the basis of the system It ensures
that it is robust, and paves the way for transparent and unalterable digital voting solutions.
Additionally, unit testing examines the performance of the system under various conditions to
ensure that it can handle real-world issues, such as high numbers of concurrent deployments
with simultaneous validation attempts at peak voting times or edge issues such as more voters
or faster voting Can tune It also helps to validate the integration of external hardware such as
cameras and biometric devices, ensuring that accurate and consistent data is provided de use
Security is an important focus, such as identifying weaknesses in encryption algorithms during
testing, potential for data integrity -detecting threats, The system also includes blocking
unauthorized access Full unit testing includes maintaining error logs, and debugging to further
improve the code. By investing significant effort in this phase, the development process
minimizes risks and ensures the smooth operation of each component, creating confidence in
the system’s ability to deliver a safe, accurate and effective will in areas and examines more in
it lays the foundation.

Department of CSE-Data Science, ATMECE, Mysuru Page 52


VoteGuard 2024-2025

6.2 System Testing

Once individual components are verified through unit testing, the next step is system
testing. System testing involves combining all the individual units into a complete system and
testing their interaction to ensure that they work together as expected. System testing is an
important part of the software development life cycle where the entire system is tested as a
complete and integrated unit. The main objective of system testing is to ensure that all
application components and modules work together seamlessly and meet specified
requirements. For a secure blockchain and recognition-based e-voting system, this ensures that
every part of the system, including the blockchain, recognition module, user interface, and
hardware integration works in unlike integration unit testing, focusing on individual
components , system overall system testing under real-world-like conditions Tests overall
performance, efficiency and safety. In this context, system testing begins by analyzing the end-
to-end design of the e-voting system. It starts with voter registration and verification through
face recognition. The system is tested with facial information to verify the authenticity of
voters, and to prevent undocumented individuals from accessing the platform. This step
includes dealing with edge issues, such as when a candidate is partially obscured or when
lighting conditions vary widely. Once the voter is authenticated, the system is tested again so
that the vote can be submitted while maintaining the confidentiality and authenticity of the
information. This involves ensuring that votes are encrypted and securely stored on the
blockchain, ensuring that there are no tamperings or duplications. System testing also focuses
on the interaction between facial recognition and blockchain modules. For example, it tests
whether the system switches from voter recognition to voter registration seamlessly without
delays or errors. Testing consists of scenarios in which the machine may face community
interruptions, heavy person loads, or hardware malfunctions to make sure it handles those
demanding situations gracefully. The blockchain is evaluated to confirm that it keeps
transparency and immutability, preventing any unauthorized adjustments to recorded votes.
Furthermore, the machine is examined for its capacity to synchronize records across nodes in
the blockchain community, ensuring consistency and reliability even in disbursed
environments.
Department of CSE-Data Science, ATMECE, Mysuru Page 53
VoteGuard 2024-2025

The person interface (UI) performs a important function in the gadget’s usability, and device
testing guarantees that it's miles intuitive, responsive, and errors-loose. Testers examine
whether or not users can effortlessly navigate the balloting technique, from authentication to
vote submission, with out encountering issues or confusion. For example, the device is tested
to verify that it affords clear remarks for mistakes, consisting of incorrect facial recognition or
invalid information enter, and publications customers on a way to remedy these troubles. The
UI need to additionally accommodate electorate with specific levels of technical talent,
ensuring inclusivity and accessibility. Another important aspect of system testing is security.
An e-voting system must withstand cyber threats such as hacking, data breaches, or denial
attacks. Testers simulate these scenarios to identify and address vulnerabilities, and ensure the
system remains robust and secure. For example, facial recognition modules are tested to ensure
that authorized users cannot be fooled by spoofing techniques such as using images or videos
while blockchain is tested to ensure that it protects against unauthorized access roadside and
maintains the confidentiality and integrity of voter data.
In summary, system testing ensures that a secure blockchain and facial recognition based
e-voting system is ready for real-world deployment by verifying its functionality, effectiveness
and security to ensure full functionality by rigorously evaluating the system under real
conditions, this phase helps identify and address potential issues, Smooth, safe and reliable
elections for users. The experience ensures that System testing establishes the reliability of the
system to fulfill its intended purpose and paves the way for better electoral adoption.

6.3 Validation Testing

While unit and system testing focus on verifying individual components and the overall
system, validation testing is concerned with ensuring that the system meets its intended goals
and performs well in realistic conditions. Validation testing is the process of ensuring that a
system meets user needs and expectations while meeting all specified requirements. In secure
blockchain and face recognition-based e-voting systems, verification testing is essential to
ensure that the system works as intended in real-world situations.

Department of CSE-Data Science, ATMECE, Mysuru Page 54


VoteGuard 2024-2025

This position ensures that the election process provides a seamless, safe and accurate
experience for voters, election administrators, and other stakeholders. Unlike other testing
steps that focus on technical correctness, certification testing focuses on whether the system is
fit for purpose and provides value to users. Verification testing for this e-voting system
involves simulating the entire voting process from voter acceptance to final vote count,
confirming that all components work as designed Testing to test face recognition module have
been checked to ensure that they match real-world types. Identifies authorized voters
accurately in different world conditions, such as lighting, facial expressions, or environment
Differences in environment. This ensures that legal voters can easily access the system and
effectively block undocumented voters. Additionally, the testing process verifies whether the
blockchain properly records votes and maintains their confidentiality, ensuring that the entire
voting process is tamper-proof and transparent. Practical experience is another important
aspect of certification testing. This includes testing the system’s interface to ensure that it is
intuitive and accessible, even for candidates with limited technical skills. Voters can vote
without any doubt or mistake, and the system provides clear instructions and answers at every
step. Validation checking out additionally verifies that the gadget handles facet cases, along
with community disruptions or consumer mistakes, gracefully, ensuring that no votes are
misplaced and customers can whole their obligations without frustration. Security is an
important a part of validation checking out for this e-voting gadget. Test scenarios are designed
to verify that the gadget resists ability threats, including unauthorized get admission to,
statistics breaches, or hacking attempts. The blockchain is demonstrated to make sure it
maintains the immutability of votes, at the same time as the face recognition gadget is
examined against spoofing strategies to ensure its reliability. By validating the machine's
capacity to shield person data and voting integrity, this segment ensures trustworthiness within
the electoral method.In precise, validation trying out guarantees that the secure blockchain and
face reputation-based totally e-vote casting system isn't best technically sound however
additionally practical, person-pleasant, and stable for its meant motive. It bridges the gap
among gadget necessities and person expectancies, ensuring the platform is ready for real-
world deployment and able to turning in a transparent, reliable, and green balloting experience.

Department of CSE-Data Science, ATMECE, Mysuru Page 55


VoteGuard 2024-2025

CHAPTER 7

DISCUSSION OF RESULTS

The blockchain a secure and face-awareness-based e-voting system successfully


completed all default testing scenarios, demonstrated reliable performance in terms of voter
authentication and securely recorded the same vote access to the system within can ensure that
the blockchain module is properly encrypted and records votes, maintaining data integrity and
preventing any duplication of changes or transactions. The system featured seamless
integration between facial recognition and blockchain components, ensuring a smooth
transition from voter recognition to voter registration consistently overriding security measures
and exhibiting few bugs , and confirms its ability to handle virtual e-voting operations in a
controlled environment. They also confirm the readiness to safely manage the required voting
operations and emphasize that it has been done well. The following are the results of our
E-Voting System :-

Figure 7.1: Home Page for E-voting System

The figure 7.1 shows the homepage of the VoteGuard project featuring an attractive
main web page that visitors typically see first when they arrive at a site.

Department of CSE-Data Science, ATMECE, Mysuru Page 56


VoteGuard 2024-2025

Figure 7.2: Login Page for Election Authority

The figure 7.2 shows the login page where Election Authorities manage the voting
process, supplementing access to votes by registering vital information such as Aadhaar ID,
voter ID and constituencies. During registration, voter facial information is captured and
trained using Python’s built-in facial recognition module, which ensures identification while
voting.

Figure 7.3: Election authority page to Add Candidates

Department of CSE-Data Science, ATMECE, Mysuru Page 57


VoteGuard 2024-2025

The figure 7.3 shows Once authenticated, authorities can add constituencies, register
candidates with their respective political parties, and map them to specific constituencies.

Figure 7.4: To View Candidates

The figure 7.4 shows the candidates registered for election and details of their
constituency and the party they are standing for.

Figure 7.5: To Add Constituencies

Department of CSE-Data Science, ATMECE, Mysuru Page 58


VoteGuard 2024-2025

The figure 7.5 shows a page to add constituencies, an area for which a body of
representative could stand for election which could be entitled to a place or region.

Figure 7.6: To view List of Constituencies

The figure 7.6 shows the List of Constituencies registered or added, Election
authorities can activate or deactivate constituency voting from this page. If active, the voter
receives a list of candidates and their party details and can cast a vote.

Figure 7.7: Voter Register portal

Department of CSE-Data Science, ATMECE, Mysuru Page 59


VoteGuard 2024-2025

The figure 7.7 shows a page to register voter through filling necessary credentials like
name, phone no, aadhar id, voter id, gender, constitution for which they want to vote and user
authenticated password.

Figure 7.8: Face Detection for Voter Register

The figure 7.8 shows face detection module initiated before voter register which is
authenticated for 5 times to ensure successful register of voter. This technology ensures that only
registered voters can cast their vote, preventing identity theft and impersonation.

Department of CSE-Data Science, ATMECE, Mysuru Page 60


VoteGuard 2024-2025

Figure 7.9: View Vote Counts

The figure 7.9 shows a portal to view vote counts after successful completion of
voting process among the respective registered constituencies.

Figure 7.10: Login Page for Voter

The figure 7.10 shows a login page for Voter where in which voters can log in using
their Voter ID and registered password, after which a live face recognition process is initiated.

Department of CSE-Data Science, ATMECE, Mysuru Page 61


VoteGuard 2024-2025

Figure 7.11: Voter Portal to cast Vote

The figure 7.11 shows the voter directed to cast vote for the registered constituency
only after face detection initiated successfully as only authorized voter will be directed
otherwise it will show as failed.

Figure 7.12: Voting Successful initiated page

The figure 7.12 shows the successful completion of voting process and secures the data
of vote in blockchain.

Department of CSE-Data Science, ATMECE, Mysuru Page 62


VoteGuard 2024-2025

CHAPTER 8

CONCLUSION & FUTURE SCOPE


Conclusion
In conclusion, the Blockchain and Face Recognition-Based Voting System offers a
secure, transparent, and efficient solution to modern-day voting challenges. By integrating
biometric face recognition for voter authentication and blockchain technology for storing
votes, the system ensures the highest levels of security, preventing voter fraud and ensuring
that votes remain tamper-proof. The system's ability to prevent multiple voting and provide
real-time tracking of results enhances trust in the electoral process. Moreover, its scalability
and adaptability make it suitable for various applications, from national elections to corporate
and organizational decision-making. This innovative approach not only modernizes traditional
voting methods but also establishes a more reliable, trustworthy, and accessible voting platform
for the future. In addition to addressing security and transparency worries, the Blockchain and
Face Recognition-Based Voting System reduces administrative prices related to traditional
vote casting strategies, along with paper ballots, guide counting, and logistical inefficiencies.
By automating those tasks and streamlining the balloting mechanism, the gadget improves
universal performance and decreases the time required to behaviour elections. Furthermore,
the decentralized nature of blockchain guarantees that no single entity has manipulate over the
vote statistics, minimizing the dangers of corruption and ensuring the integrity of the electoral
machine. This technological advancement additionally promotes inclusivity, particularly for
far off or marginalized populations, who may additionally in any other case face boundaries to
accessing conventional vote casting strategies. As the arena continues to conform, embracing
digital answers like this gadget no longer handiest complements democratic participation but
additionally paves the manner for extra inclusive, transparent, and secure governance
frameworks. In summary, blockchain and facial recognition based voting systems provide a
secure, transparent and efficient way to conduct elections. Using biometric facial recognition
for voter authentication and blockchain to store votes, the system ensures the integrity of the
voting process, prevents fraud and consistent results.

Department of CSE-Data Science, ATMECE, Mysuru Page 63


VoteGuard 2024-2025

This system also reduces administrative costs, it provides increases employment and makes
voting more accessible, especially for marginalized or marginalized people. With its scalability
and adaptability, this approach modernizes electoral processes and builds trust in democratic
processes, creating a more reliable and transparent future for elections.

Future Enhancement
Future enhancements for Blockchain and Face recognition based E-Voting System involve
various aspects for improve. Here are some potential future enhancements:-

• Advanced Algorithms: The use of deep studying fashions like convolutional neural
networks (CNNs) can similarly beautify the accuracy of face reputation structures,
making them greater proof against variations in lighting, facial expressions, or growing
older.

• Three-D Facial Recognition: Implementing 3D face recognition systems might


enable the device to investigate depth, now not simply the 2D surface of the face,
enhancing security against spoofing (e.g., with photographs or videos).

• Edge Computing: Using facet devices (including smartphones or dedicated hardware)


to process face reputation regionally can reduce latency and enhance velocity, bearing
in mind quicker voter verification at polling stations with out counting on important
servers.

• Continuous Monitoring: Continuous facial popularity all through the voting manner
(e.g., ensuring the voter’s face is captured throughout the session) can prevent
impersonation or balloting fraud.

• Enhanced User Experience (UX) and Accessibility: Focus on developing consumer-


pleasant interfaces and accessibility features to make certain ease of use, in particular
for elderly or tech inexperienced electorate.

Department of CSE-Data Science, ATMECE, Mysuru Page 64


VoteGuard 2024-2025

REFERENCES
[1] Swan, M. (2015). Block chain: Blueprint for a New Economy. O'Reilly Media. This
book provides foundational knowledge about block chain technology and its potential
applications in secure systems, including voting.

[2] Zhang, L., White, J., Schmidt, D. C., & Lenz, G. (2018). Applying Block chain
Technology for Secure Voting Systems. In Proceedings of the 18th ACM International
Conference on Distributed Applications and Interoperable Systems (DAIS 2018). This
paper discusses the implementation of block chain in voting systems and the benefits of
security and transparency it brings.

[3] Sharma, T. K., & Bhushan, B. (2020). Block chain for Voter Identity Verification
and Secure Election Process. In International Journal of Computer Applications, 176(24),
8-12. This article presents block chain and biometric technologies in voter identity
verification and secure voting systems.

[4] Nguyen, Q. K. (2016). Block chain A Financial Technology for Future Sustainable
Development. In Proceedings of the 3rd International Conference on Green Technology and
Sustainable Development (GTSD). The paper explores the application of block chain
beyond finance, including its potential use in secure voting mechanisms.

[5] Hinton, G., Deng, L., Yu, D., et al. (2012). Deep Neural Networks for Acoustic
Modeling in Speech Recognition. In IEEE Signal Processing Magazine, 29(6), 82-97. -
While this paper focuses on speech recognition, it provides foundational concepts related
to biometric verification systems like face recognition, which is central to this project.

[6] King, D. E. (2009). Dlib-ml: A Machine Learning Toolkit. Journal of Machine


Learning Research, 10, 1755-1758. The paper details machine learning techniques used in
face recognition, which is important for understanding the technology utilized in this
system.

Department of CSE-Data Science, ATMECE, Mysuru Page 65


VoteGuard 2024-2025

[7] Flask Documentation (n.d.). Flask: A Micro Web Framework based on Python.
Retrieved from https://flask.palletsprojects.com/en/latest/ - This official documentation
provides insights into Flask's web framework, which is used to develop the system's
backend.

Department of CSE-Data Science, ATMECE, Mysuru Page 66


VoteGuard 2024-2025

Appendix

# importing necessary libraries

import hashlib

import json

from time import time

import pickle

class Block:

def __init__(self, index, timestamp, candidate_id, vote, voter_id, previous_hash):

self.index = index

self.timestamp = timestamp

self.candidate_id =

candidate_id

self.vote = vote

self.voter_id = voter_id

self.previous_hash = previous_hash

self.hash = self.calculate_hash()

def calculate_hash(self):

block_string = json.dumps(self.__dict__, sort_keys=True)

return hashlib.sha256(block_string.encode()).hexdigest()

'''class Blockchain:

Department of CSE-Data Science, ATMECE, Mysuru Page 67


VoteGuard 2024-2025

def __init__(self):

self.chain = []

self.create_genesis_block()

def create_genesis_block(self):

# Manually create the first

block (genesis block)

genesis_block = Block(0,time(), None, None, None,"0")

self.chain.append(genesis_block)

def add_block(self, candidate_id,

vote, voter_id):

previous_block = self.chain[-1]

new_block = Block(len(self.chain), time(),

candidate_id, vote, voter_id, previous_block.hash)

self.chain.append(new_block)

def get_blocks(self):

return [(block.index, block.timestamp, block.candidate_id, block.vote, block.voter_id,

block.hash ) for block in self.chain[1:]]'''

class Blockchain:

def __init__(self):

self.chain = []
Department of CSE-Data Science, ATMECE, Mysuru Page 68
VoteGuard 2024-2025

self.create_genesis_block()

self.load_chain() # Load the existing blockchain data if it exists

def create_genesis_block(self):

genesis_block = Block(0, time(), None, None, None, "0")

self.chain.append(genesis_block)

def add_block(self, candidate_id, vote, voter_id):

previous_block = self.chain[-1]

new_block = Block(len(self.chain), time(), candidate_id, vote, voter_id, previous_block.hash)

self.chain.append(new_block)

def save_chain(self):

with open('blockchain_data.pkl', 'wb') as file:

pickle.dump(self.chain, file)

def load_chain(self):

try:

with open('blockchain_data.pkl', 'rb') as file:

self.chain = pickle.load(file)

except FileNotFoundError:

# If the file does not exist, just create a new chain

self.create_genesis_block()
Department of CSE-Data Science, ATMECE, Mysuru Page 69
VoteGuard 2024-2025

def get_blocks(self):

return [(block.index, block.timestamp, block.candidate_id, block.vote,

block.voter_id, block.hash) for block in self.chain[1:]]

# Example usage

if __name__ == "__main__":

# Create a blockchain

blockchain = Blockchain()

# Add blocks with candidate ID,

vote, and voter ID

'''blockchain.add_block("1", "yes", "123")

blockchain.add_block("1", "no", "456")

blockchain.add_block("2", "yes", "789")'''

# Get blocks from the blockchain

blocks = blockchain.get_blocks()

#print("Blocks in the blockchain:")

for block in blocks:

print(block[2])
Department of CSE-Data Science, ATMECE, Mysuru Page 70
VoteGuard 2024-2025

import face_recognition

import cv2

import numpy as np

import pickle

from datetime import datetime, timedelta

import winsound

unknowncounter=0

counter=0

def detectPerson():

global unknowncounter

global counter

# Load reference data from pickle files

with open("ref_name.pkl", "rb")

as f:

ref_dict = pickle.load(f) #

ref_dict = ref vs name

with open("ref_embed.pkl", "rb")

as f:

embed_dict = pickle.load(f) # embed_dict- ref vs embedding

Department of CSE-Data Science, ATMECE, Mysuru Page 71


VoteGuard 2024-2025

# Initialize arrays for known face encodings and names

known_face_encodings = []

known_face_names = []

# Populate known_face_encodings and

known_face_names

for ref_id, embed_list in embed_dict.items():

for embed in embed_list:

known_face_encodings.append(embed)

known_face_names.append(ref_id)

# Initialize video capture from the default camera

video_capture = cv2.VideoCapture(0)

# Main loop for face recognition

while True:

# Capture a single frame of video

ret, frame = video_capture.read()

# Resize frame of video to 1/4

size for faster processing

small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)


Department of CSE-Data Science, ATMECE, Mysuru Page 72
VoteGuard 2024-2025

# Convert the image from BGR color to RGB

color (required by face_recognition)

rgb_small_frame = small_frame[:, :, ::-1]

# Find all face locations and encodings in the current frame

face_locations =

face_recognition.face_locations(rgb_small_frame)

face_encodings =

face_recognition.face_encodings(rgb_small_frame, face_locations)

# Initialize list to store names of

recognized faces

face_names = []

name=""

# Iterate through each face in the frame

for face_encoding in face_encodings:

# Compare the face encoding

with known face encodings

if known_face_encodings:

matches =

face_recognition.compare_faces(known_face_encodings,
Department of CSE-Data Science, ATMECE, Mysuru Page 73
VoteGuard 2024-2025

face_encoding)

name = "Unknown"

# Find the best match for

the face

if matches:

face_distances =

face_recognition.face_distance(known_face_encodings, face_encoding)

best_match_index =

np.argmin(face_distances)

if

matches[best_match_index]:

name = known_face_names[best_match_index]

face_names.append(name)

else:

face_names.append("Unknown") # No known face encodings available

# Display the results

for (top, right, bottom, left), name in zip(face_locations, face_names):

# Scale back up face


Department of CSE-Data Science, ATMECE, Mysuru Page 74
VoteGuard 2024-2025

locations since the frame was scaled

to 1/4 size

top *= 4

right *= 4

bottom *= 4

left *= 4

# Draw a rectangle around the face

cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

# Draw a label with the name below the face

cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)

font = cv2.FONT_HERSHEY_DUPLEX

cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

# Display the resulting image

cv2.imshow('Video', frame)

# Process detected faces

if name!="Unknown" or

name!="":

unknowncounter+=0
Department of CSE-Data Science, ATMECE, Mysuru Page 75
VoteGuard 2024-2025

counter+=1

print("known",counter)

if counter==10:

video_capture.release()

cv2.destroyAllWindows()

print("detection",name)

counter=0

return name

elif name=="Unknown" or

name=="":

counter+=0

unknowncounter+=1

print("unknown",unknowncounter)

if unknowncounter==10:

counter=0

video_capture.release()

cv2.destroyAllWindows()

return "failed"

# Exit loop if 'q' key is pressed

if cv2.waitKey(1) & 0xFF == ord('q'):


Department of CSE-Data Science, ATMECE, Mysuru Page 76
VoteGuard 2024-2025

counter=0

video_capture.release()

cv2.destroyAllWindows()

break

# Release video capture

counter=0

video_capture.release()

cv2.destroyAllWindows()

# Call the function to start the

detection process

#res =detectPerson()

import sys

#sys.path.append('/home/shivam/Downloads/lib/python3.6/site-packages')

import cv2

import face_recognition

import pickle

def trainPerson(voterid,aadharid):

name= aadharid

ref_id= voterid
Department of CSE-Data Science, ATMECE, Mysuru Page 77
VoteGuard 2024-2025

print("function called")

try:

f=open("ref_name.pkl","rb")

ref_dictt=pickle.load(f)

f.close()

except:

ref_dictt={}

ref_dictt[ref_id]=name

f=open("ref_name.pkl","wb")

pickle.dump(ref_dictt,f)

f.close()

try:

f=open("ref_embed.pkl","rb")

embed_dictt=pickle.load(f)

f.close()

except:

embed_dictt={}
Department of CSE-Data Science, ATMECE, Mysuru Page 78
VoteGuard 2024-2025

for i in range(5):

key = cv2. waitKey(1)

webcam = cv2.VideoCapture(0)

while True:

check, frame = webcam.read()

# print(check) #prints true as long as the webcam is running

# print(frame) #prints matrix values of each frame

cv2.imshow("Capturing", frame)

small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

rgb_small_frame = small_frame[:, :, ::-1]

key = cv2.waitKey(1)

if key == ord('s') :

face_locations =

face_recognition.face_locations(rgb_small_frame)

if face_locations != []:

face_encoding =

face_recognition.face_encodings(frame)[0]

if ref_id in embed_dictt:
Department of CSE-Data Science, ATMECE, Mysuru Page 79
VoteGuard 2024-2025

embed_dictt[ref_id]+=[face_encoding]

else:

embed_dictt[ref_id]=[face_encoding]

webcam.release()

# img_new = cv2.imread('saved_img.jpg',

cv2.IMREAD_GRAYSCALE)

# img_new

= cv2.imshow("Captured Image",

img_new)

cv2.waitKey

(1)

cv2.destroy

AllWindows()

break

elif key == ord('q'):

print("Turning

off camera.")

webcam.release(

print("Camera

off.")
Department of CSE-Data Science, ATMECE, Mysuru Page 80
VoteGuard 2024-2025

print("Program

ended.")

cv2.destroyAllWi

ndows()

break

f=open("ref_embed.pkl","wb")

pickle.dump(embed_dictt,f)

f.close()

print("face trained")

from flask import Flask,

render_template, request, redirect,

url_for, flash, session,jsonify

import mysql.connector as mq

from mysql.connector import Error

from markupsafe import Markup

from datetime import datetime

from werkzeug.utils import

secure_filename

from datetime import datetime

from collections import Counter


Department of CSE-Data Science, ATMECE, Mysuru Page 81
VoteGuard 2024-2025

import embeddings

import recognition

import blockchain

from collections import Counter

app = Flask(__name__)

app.config['SECRET_KEY'] =

'secret_key'

myblockchain =

blockchain.Blockchain()

def dbconnection():

con =

mq.connect(host='localhost',

database='facebvotingweb',user='ro

ot',password='root')

return con

@app.route('/')

def home():

return
Department of CSE-Data Science, ATMECE, Mysuru Page 82
VoteGuard 2024-2025

render_template('index.html',

title='home')

@app.route('/loginpage')

def loginpage():

return

render_template('login.html',title='lo

gin')

@app.route('/registerpage')

def registerpage():

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

constituencies")

res = cursor.fetchall()

return

render_template('register.html',res=

res)

@app.route('/addcandidatepage')
Department of CSE-Data Science, ATMECE, Mysuru Page 83
VoteGuard 2024-2025

def addcandidatepage():

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

constituencies")

res = cursor.fetchall()

return

render_template('addcandidate.html'

,res=res)

@app.route('/addconstituencypage')

def addconstituencypage():

return

render_template('addcons.html')

@app.route('/login',

methods=['GET', 'POST'])

def login():

if request.method == 'POST':

user = request.form['user']

password =
Department of CSE-Data Science, ATMECE, Mysuru Page 84
VoteGuard 2024-2025

request.form['password']

ltype = request.form['ltype']

if ltype=='eauthority':

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

eauthority where userid='{}' and

pass='{}'".format(user,password))

res = cursor.fetchall()

if res==[]:

message =

Markup("<h3>Failed! Invalid User

Id or Password</h3>")

flash(message)

return

redirect(url_for('loginpage'))

else:

return

redirect(url_for('addconstituencypag

e'))

elif ltype=='voter':
Department of CSE-Data Science, ATMECE, Mysuru Page 85
VoteGuard 2024-2025

con = dbconnection()

cursor = con.cursor()

voterid =

recognition.detectPerson()

cursor.execute("select * from

voters where voterid='{}' and

pass='{}'".format(user,password))

res = cursor.fetchall()

if res==[]:

message =

Markup("<h3>Failed! Invalid voter

id or Password</h3>")

flash(message)

return

redirect(url_for('loginpage'))

elif res[0][8]=="voted":

message =

Markup("<h3>Failed! You have

already voted</h3>")

flash(message)

return
Department of CSE-Data Science, ATMECE, Mysuru Page 86
VoteGuard 2024-2025

redirect(url_for('loginpage'))

elif res[0][8]=="notvoted":

cid = res[0][6]

cursor.execute("select *

from constituencies where

id={}".format(int(cid)))

res2 = cursor.fetchall()

if res2[0][2]=="Inactive":

message =

Markup("<h3>Failed! voting has

not yet stated to this

constitution</h3>")

flash(message)

return

redirect(url_for('loginpage'))

elif voterid==res[0][5]:

print(res[0][0])

session['vid']=res[0][0]

return

redirect(url_for('vviewcandidates',ci

d=res[0][6]))
Department of CSE-Data Science, ATMECE, Mysuru Page 87
VoteGuard 2024-2025

else:

message =

Markup("<h3>Failed! Face and

Entered Voterid did not

match</h3>")

flash(message)

return

redirect(url_for('loginpage'))

@app.route('/savecandidate',

methods=['GET', 'POST'])

def savecandidate():

if request.method == 'POST':

name = request.form['name']

party = request.form['party']

cid = request.form['cid']

uploaded_file =

request.files['photo']

if uploaded_file.filename != '':

# Save the uploaded file to a


Department of CSE-Data Science, ATMECE, Mysuru Page 88
VoteGuard 2024-2025

specific folder

filename =

'static/uploads/partyimages/' +

uploaded_file.filename

onlyfilename=uploaded_file.f

ilename

print(filename)

uploaded_file.save(filename)

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

candidates where cname='{}' and

party='{}' and

cid='{}'".format(name,party,int(cid))

res = cursor.fetchall()

if res==[]:

cursor.execute("insert into

candidates(cname,party,symbol,cid)v

alues('{}','{}','{}',{})".format(name,p

arty,onlyfilename,cid))
Department of CSE-Data Science, ATMECE, Mysuru Page 89
VoteGuard 2024-2025

con.commit()

con.close()

message =

Markup("<h3>Success! Candidate

Added!</h3>")

flash(message)

return

redirect(url_for('addcandidatepage')

else:

message =

Markup("<h3>Failed! Candidate

Already Exists!</h3>")

flash(message)

return

redirect(url_for('addcandidatepage')

@app.route('/viewcandidatespage')

def viewcandidatespage():

con = dbconnection()
Department of CSE-Data Science, ATMECE, Mysuru Page 90
VoteGuard 2024-2025

cursor = con.cursor()

cursor.execute("select * from

candidates inner join constituencies

on

candidates.cid=constituencies.id")

res = cursor.fetchall()

if res==[]:

message =

Markup("<h3>Failed! Details not

found</h3>")

flash(message)

return

render_template('viewcandidates.ht

ml', title='candidates')

else:

return

render_template('viewcandidates.ht

ml', title='candidates',res=res)

@app.route('/saveconstituency',

methods=['GET', 'POST'])
Department of CSE-Data Science, ATMECE, Mysuru Page 91
VoteGuard 2024-2025

def saveconstituency():

if request.method == 'POST':

consname =

request.form['consname']

status = 'Inactive'

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

constituencies where

consname='{}'".format(consname))

res = cursor.fetchall()

if res==[]:

cursor.execute("insert into

constituencies(consname,status)valu

es('{}','{}')".format(consname,status)

con.commit()

con.close()

message =

Markup("<h3>Success! Details

Added!</h3>")
Department of CSE-Data Science, ATMECE, Mysuru Page 92
VoteGuard 2024-2025

flash(message)

return

redirect(url_for('addconstituencypag

e'))

else:

message =

Markup("<h3>Failed! Constitution

already exists!</h3>")

flash(message)

return

redirect(url_for('addconstituencypag

e'))

@app.route('/viewconstituenciespag

e')

def viewconstituenciespage():

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

constituencies")

res = cursor.fetchall()
Department of CSE-Data Science, ATMECE, Mysuru Page 93
VoteGuard 2024-2025

if res==[]:

message =

Markup("<h3>Failed! Details not

found</h3>")

flash(message)

return

render_template('viewcons.html',

title='constitutions')

else:

return

render_template('viewcons.html',

title='constitutions',res=res)

@app.route('/deactivate')

def deactivate():

id =request.args.get('id')

status = 'Inactive'

con = dbconnection()

cursor = con.cursor()

cursor.execute("update

constituencies set status='{}' where


Department of CSE-Data Science, ATMECE, Mysuru Page 94
VoteGuard 2024-2025

id={}".format(status,int(id)))

con.commit()

con.close()

message =

Markup("<h3>Success! constituency

Deactivated</h3>")

flash(message)

return

redirect(url_for('viewconstituenciesp

age'))

@app.route('/activate')

def activate():

print("active")

id =request.args.get('id')

status = 'Active'

con = dbconnection()

cursor = con.cursor()

cursor.execute("update

constituencies set status='{}' where

id={}".format(status,int(id)))
Department of CSE-Data Science, ATMECE, Mysuru Page 95
VoteGuard 2024-2025

con.commit()

con.close()

message =

Markup("<h3>Success! constituency

Activated</h3>")

flash(message)

return

redirect(url_for('viewconstituenciesp

age'))

@app.route('/register',

methods=['GET', 'POST'])

def register():

if request.method == 'POST':

name = request.form['name']

phone = request.form['phone']

aadharid =

request.form['aadharid']

voterid =

request.form['voterid']

gender =
Department of CSE-Data Science, ATMECE, Mysuru Page 96
VoteGuard 2024-2025

request.form['gender']

cid = request.form['cid']

password =

request.form['password']

status="notvoted"

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

voters where aadharid='{}' or

voterid='{}'".format(aadharid,voteri

d))

res = cursor.fetchall()

if res==[]:

try:

embeddings.trainPerson(v

oterid,aadharid)

cursor.execute("insert into

voters(name,phone,gender,aadharid,

voterid,cid,pass,status)values('{}','{}'

,'{}','{}','{}',{},'{}','{}')".format(name,

phone,gender,aadharid,voterid,int(ci
Department of CSE-Data Science, ATMECE, Mysuru Page 97
VoteGuard 2024-2025

d),password,status))

con.commit()

con.close()

message =

Markup("<h3>Registration

Success</h3>")

flash(message)

return

redirect(url_for('registerpage'))

except Exception as e:

print("An error

occurred:", e)

message =

Markup("<h3Could not complete

registration</h3>")

flash(message)

return

redirect(url_for('registerpage'))

else:

message =

Markup("<h3>Failed! aadharid or
Department of CSE-Data Science, ATMECE, Mysuru Page 98
VoteGuard 2024-2025

voterid already exists</h3>")

flash(message)

return

redirect(url_for('registerpage'))

@app.route('/vviewcandidates/<int:

cid>')

def vviewcandidates(cid):

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

candidates inner join constituencies

on candidates.cid=constituencies.id

where

candidates.cid={}".format(int(cid)))

res = cursor.fetchall()

if res==[]:

message =

Markup("<h3>Failed! Details not

found</h3>")

flash(message)
Department of CSE-Data Science, ATMECE, Mysuru Page 99
VoteGuard 2024-2025

return

render_template('vviewcandidates.ht

ml', title='candidates')

else:

return

render_template('vviewcandidates.ht

ml', title='candidates',res=res)

@app.route('/savemyvote')

def savemyvote():

#print("hello")

cid =request.args.get('id')

status = "voted"

vid = session['vid']

con = dbconnection()

cursor = con.cursor()

cursor.execute("update voters set

status='{}' where

id={}".format(status,int(vid)))

con.commit()

myblockchain.add_block(cid,
Department of CSE-Data Science, ATMECE, Mysuru Page
100
VoteGuard 2024-2025

"yes", vid)

myblockchain.save_chain()

blocks =

myblockchain.get_blocks()

for block in blocks:

print(block)

message = Markup("<h3>Sucess!

Thank you for voting your vote is

safe in blockchain</h3>")

flash(message)

return

redirect(url_for('loginpage'))

@app.route('/viewvotecountspage')

def viewvotecountspage():

con = dbconnection()

cursor = con.cursor()

cursor.execute("select * from

candidates")

res = cursor.fetchall()

Department of CSE-Data Science, ATMECE, Mysuru Page


101
VoteGuard 2024-2025

votes = []

blocks =

myblockchain.get_blocks()

# Collect votes from blocks

for block in blocks:

if block[2] is not None: #

Ensure block[2] is not None

votes.append(block[2])

counter = Counter(votes)

unique_ids = list(counter.keys())

frequencies =

list(counter.values())

finalresult = []

for number, frequency in

zip(unique_ids, frequencies):

if number is not None: #

Ensure number is not None before

processing
Department of CSE-Data Science, ATMECE, Mysuru Page
102
VoteGuard 2024-2025

cursor.execute("select * from

candidates inner join constituencies

on candidates.cid=constituencies.id

where

candidates.id={}".format(int(number

)))

res1 = cursor.fetchall()

for sublist in res1:

modified_sublist =

list(sublist)

modified_sublist.append(st

r(frequency))

finalresult.append(modifie

d_sublist)

print(finalresult)

return

render_template('viewvotecount.html

', title='votes', res=finalresult)

@app.route('/search_cons',
Department of CSE-Data Science, ATMECE, Mysuru Page
103
VoteGuard 2024-2025

methods=['POST'])

def search_cons():

data = request.get_json()

search_term =

data['searchTerm'].lower() # Get

the search term from the request

con = dbconnection()

cursor = con.cursor()

# Query to filter candidates based

on constituency name

cursor.execute("""

SELECT candidates.id AS cid,

candidates.cname AS

candidate_name, candidates.party

AS party,

constituencies.consname

AS constituency_name

FROM candidates

INNER JOIN constituencies ON

candidates.cid = constituencies.id
Department of CSE-Data Science, ATMECE, Mysuru Page
104
VoteGuard 2024-2025

WHERE

LOWER(constituencies.consname)

LIKE %s

""", ('%' + search_term + '%',))

results = cursor.fetchall()

final_result = []

# Process results to include vote

counts

votes = [block[2] for block in

myblockchain.get_blocks()] #

Extract candidate IDs from

blockchain votes

counter = Counter(votes)

for candidate in results:

cid = candidate[0]

candidate_name =

candidate[1] # Adjust based on the

selected fields
Department of CSE-Data Science, ATMECE, Mysuru Page
105
VoteGuard 2024-2025

party = candidate[2]

constituency_name =

candidate[3]

# Get vote count from the

counter

vote_count =

counter.get(str(candidate[0]), 0) #

Make sure you pass the correct ID

for counting

# Add the required data to the

final result

final_result.append([candidate_

name, party, constituency_name,

str(vote_count)])

return jsonify(final_result) #

Return results as JSON

@app.teardown_appcontext
Department of CSE-Data Science, ATMECE, Mysuru Page
106
VoteGuard 2024-2025

def

shutdown_session(exception=None):

myblockchain.save_chain() #

Save the blockchain data when the

app context is torn down

if __name__ == '__main__':

app.run(debug=True,host='0.0.0.

0',port=5000)

Department of CSE-Data Science, ATMECE, Mysuru Page


107

You might also like