0% found this document useful (0 votes)
34 views77 pages

Petition Doc 29

The document is a project report for an AI-powered petition analysis and categorization tool developed by students at K. Ramakrishnan College of Engineering. It outlines the system's objectives, which include enhancing digital governance through efficient petition management using Natural Language Processing (NLP) techniques. The report details the project's design, implementation, and the significance of user authentication in ensuring system integrity and transparency.

Uploaded by

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

Petition Doc 29

The document is a project report for an AI-powered petition analysis and categorization tool developed by students at K. Ramakrishnan College of Engineering. It outlines the system's objectives, which include enhancing digital governance through efficient petition management using Natural Language Processing (NLP) techniques. The report details the project's design, implementation, and the significance of user authentication in ensuring system integrity and transparency.

Uploaded by

t2c.photographee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

AI POWERED PETITION ANALYSIS AND

CATEGORIZATION TOOL USING spaCy ALGORITHM


A PROJECT REPORT

Submitted by

DONA VERGINIYA N (8115U21CS036)

HEMAVATHI G (8115U21CS047)

KEERTHANA K (8115U21CS059)

KHAVIYA K (8115U21CS062)

in partial fulfilment of the award of the degree of


BACHELOR OF ENGINEERING
IN
COMPUTER SCIENCE AND ENGINEERING

K.RAMAKRISHNAN COLLEGE OF ENGINEERING


(AUTONOMOUS), SAMAYAPURAM, TRICHY – 621 112.
MAY 2025
K.RAMAKRISHNAN COLLEGE OF ENGINEERING
(AUTONOMOUS)
BONAFIDE CERTIFICATE

Certified that this project report “AI POWERED PETITION


ANALYSIS AND CATEGORIZATION TOOL USING SPACY
ALGORITHM” is the Bonafide work of “ DONA VERGINIYA N,
HEMAVATHI G, KEERTHANA K, KHAVIYA K” who carried out
the project work under my supervision.

SIGNATURE SIGNATURE
Dr. T.M. NITHYA, M.E., Ph.D., Dr. L. AMUDHA, M.E., Ph.D.,

Associate Professor Assistant Professor

HEAD OF THE DEPARTMENT SUPERVISOR

Computer Science & Engineering Computer Science & Engineering

K. Ramakrishnan College of Engineering K. Ramakrishnan College of Engineering

(Autonomous) (Autonomous)

Samayapuram, Samayapuram,

Trichy – 621112 Trichy – 621112

Submitted for the Project Viva-Voce Examination held on ………………….

INTERNAL EXAMINER EXTERNAL EXAMINER


i
ACKNOWLEDGEMENT
We thank the almighty GOD, without whom it would not have been
possible for us to complete our project.
We wish to address our profound gratitude to Dr.K.
RAMAKRISHNAN, Chairman, K. Ramakrishnan College of Engineering
(Autonomous), who encouraged and gave us all help throughout the course.
We express our hearty gratitude and thanks to our honourable and
grateful Executive Director Dr.S.KUPPUSAMY, B.Sc., MBA., Ph.D.,
K.Ramakrishnan College of Engineering (Autonomous).
We are glad to thank our principal Dr.D.SRINIVASAN, M.E., Ph.D.,
FIE., MIIW., MISTE., MISAE., C.Engg, for giving us permission to carry
out this project.
We wish to convey our sincere thanks to Dr.T.M.NITHYA, M.E.,
Ph.D., Head of the Department, Computer Science and Engineering for
giving us constants encouragement and advice throughout the course.
We are grateful to Dr. L. AMUDHA, M.E., Ph.D., Assistant Professor
in the Department of Computer Science and Engineering, K.Ramakrishnan
College of Engineering (Autonomous), for her guidance and valuable
suggestions during the course of study.
Finally, we sincerely acknowledge in no less term for all our faculty
members, colleagues, our parents and friends for their co-operation and help
at various stages in this project work

ii
DECLARATION

I hereby declare that the work entitled “AI POWERED PETITION


ANALYSIS AND CATEGORIZATION TOOL USING SPACY
ALGORITHM” is submitted in partial fulfilment of the requirement for the reward
of the degree in B.E., Anna University, Chennai, is a record of our own work carried
out by me during the academic year 2024-2025 under the supervision and guidance
of Dr. L.AMUDHA, M.E., Ph.D., Assistant Professor, Department of Computer
Science and Engineering, K.Ramakrishnan College of Engineering
(Autonomous). The extent and source of information are derived from the existing
literature and have been indicated through the dissertation at the appropriate places.
The matter embodied in this work is original and has not been submitted for the
award of any degree or diploma, either in this or any other University.

DONA VERGINIYA N
(8115U21CS036)

I certify that the declaration made by above candidate is true.

Dr. L. AMUDHA, M.E., Ph.D.,


Assistant Professor/CSE

iii
DECLARATION

I hereby declare that the work entitled “AI POWERED PETITION


ANALYSIS AND CATEGORIZATION TOOL USING SPACY
ALGORITHM” is submitted in partial fulfilment of the requirement for the reward
of the degree in B.E., Anna University, Chennai, is a record of our own work carried
out by me during the academic year 2024-2025 under the supervision and guidance
of Dr. L.AMUDHA, M.E., Ph.D., Assistant Professor, Department of Computer
Science and Engineering, K.Ramakrishnan College of Engineering
(Autonomous). The extent and source of information are derived from the existing
literature and have been indicated through the dissertation at the appropriate places.
The matter embodied in this work is original and has not been submitted for the
award of any degree or diploma, either in this or any other University.

HEMAVATHI G
(8115U21CS047)

I certify that the declaration made by above candidate is true.

Dr. L. AMUDHA, M.E., Ph.D.,


Assistant Professor/CSE

iv
DECLARATION

I hereby declare that the work entitled “AI POWERED PETITION


ANALYSIS AND CATEGORIZATION TOOL USING SPACY
ALGORITHM” is submitted in partial fulfilment of the requirement for the reward
of the degree in B.E., Anna University, Chennai, is a record of our own work carried
out by me during the academic year 2024-2025 under the supervision and guidance
of Dr. L.AMUDHA, M.E., Ph.D., Assistant Professor, Department of Computer
Science and Engineering, K.Ramakrishnan College of Engineering
(Autonomous). The extent and source of information are derived from the existing
literature and have been indicated through the dissertation at the appropriate places.
The matter embodied in this work is original and has not been submitted for the
award of any degree or diploma, either in this or any other University.
.

KEERTHANA K
(8115U21CS059)

I certify that the declaration made by above candidate is true.

Dr. L. AMUDHA, M.E., Ph.D.,

Assistant Professor/CSE

v
DECLARATION

I hereby declare that the work entitled “AI POWERED PETITION


ANALYSIS AND CATEGORIZATION TOOL USING SPACY
ALGORITHM” is submitted in partial fulfilment of the requirement for the reward
of the degree in B.E., Anna University, Chennai, is a record of our own work carried
out by me during the academic year 2024-2025 under the supervision and guidance
of Dr. L.AMUDHA, M.E., Ph.D., Assistant Professor, Department of Computer
Science and Engineering, K.Ramakrishnan College of Engineering
(Autonomous). The extent and source of information are derived from the existing
literature and have been indicated through the dissertation at the appropriate places.
The matter embodied in this work is original and has not been submitted for the
award of any degree or diploma, either in this or any other University.

KHAVIYA K
(8115U21CS062)

I certify that the declaration made by above candidate is true.

Dr. L. AMUDHA, M.E., Ph.D.,


Assistant Professor/CSE

vi
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.


ABSTRACT 9
LIST OF FIGURES 11
LIST OF ABBREVIATIONS 12
1. INTRODUCTION
1.1 INTRODUCTION 13
1.2 DIGITAL GOVERNANCE 14
1.3 NATURAL LANGUAGE PROCESSING (NLP) 13
1.4 USER AUTHENTICATION 17
1.5 SENTIMENT ANALYSIS 18
1.6 CHALLENGES OF AI 19
1.7 CHALLENGES IN PETITION SYSTEMS 21
1.8 CIVIC ENGAGEMENT 23
1.9 AI-DRIVEN DECISION MAKING 24
1.10 AIM & OBJECTIVE 26
2. LITERATURE SURVEY 29
3. SYSTEM ANALYSIS 39
3.1 EXISTING SYSTEM 39
3.1.1 Limitations of Existing System 39
3.2 PROPOSED SYSTEM 41
3.2.1 Advantages of proposed system 43
4. SYSTEM REQUIREMENTS 46
4.1 HARDWARE REQUIREMENTS 46
4.2 SOFTWARE REQUIREMENTS 46
4.3 SOFTWARE DESCRPTION 46
vii
5. SYSTEM DESIGN 49
5.1 USE CASE DIAGRAM 50
5.2 CLASS DIAGRAM 52
5.3 SEQUENCE DIAGRAM 55
5.4 ACTIVITY DIAGRAM 57
6. SYSTEM TESTING 60
6.1 UNIT TESTING 60
6.2 USABILITY TESTING 61
6.3 REGRESSION TESTING 62
7. CONCLUSION AND FUTURE
ENHANCEMENTS 63
APPENDICES 69

REFERENCES 86

ABSTRACT

The Petition Management System is an AI-driven


digital governance platform designed to streamline the
creation, management, and analysis of petitions. It empowers
citizens to submit petitions easily while ensuring transparency,
accountability, and efficient grievance redressal. The system
organizes petitions by relevant departments and issues,
utilizing user authentication details such as name, address, and
location to maintain credibility and integrity. Public users are
provided with varying levels of access, offering a customized
visibility experience based on their roles and needs. To

viii
optimize decision-making, the system integrates Natural
Language Processing (NLP) techniques to analyze petition
content, detect recurring issues, group similar petitions, and
prioritize urgent concerns. Additionally, petitions are ranked
through engagement metrics and sentiment analysis, ensuring
that critical matters receive timely attention. This AI-powered
approach not only minimizes redundancy but also enhances
democratic participation by allowing citizens to have a more
direct and transparent channel for voicing concerns. By
automating categorization, prioritization, and tracking, the
Petition Management System significantly improves the
effectiveness of grievance management and fosters a stronger
connection between citizens and governance structures.
Ultimately, it stands as a progressive step toward a more
responsive, transparent, and accountable public administration
system.

LIST OF FIGURES

FIGURE NO FIGURE PAGE


NO
ix
NAME
FIGURE 5.1.1 ARCHITECTURE DIAGRAM 48

FIGURE 5.2.1 USE CASE DIAGRAM 51

FIGURE 5.3.1 CLASS DIAGRAM 54

FIGURE 5.4.1 SEQUENCE DIAGRAM 56

FIGURE 5.5.1 ACTIVITY DIAGRAM 58

LIST OF ABBREVITIONS
ABBREVITIONS FULL FORM

AI ARTIFICIAL INTELLIGENCE

NLP NATURAL LANGUAGE PROCESSING

UI USER INTERFACE

ML MACHINE LEARNING

ORM OBJECT RELATIONAL MAPPER

x
API APPLICATION PROGRAMMING
INTERFACE

AGI ARTIFICIAL GENERAL INTELLIGENCE

RTI RIGHT TO INFORMATION

BERT BIDIRECTIONAL ENCODER


REPRESENTATION FROM TRANSFORMS
HTML HYPER TEXT MARKUP LANGUAGE

CSS CASCADING STYLE SHEETS

DB DATABASE

CHAPTER 1

INTRODUCTION

The management of public petitions represents a crucial


aspect of governance, reflecting the voices and concerns of the
citizens. Traditionally, this process has been handled
manually, often resulting in inefficiencies such as delays,
redundancy, and lack of transparency. These limitations can
lead to important issues being overlooked and may reduce
public trust in administrative systems. As governance
increasingly transitions into the digital domain, there is a
significant opportunity to modernize petition management
through technological solutions.
xi
The Petition Management System (PMS) aims to offer a
streamlined, digital platform for handling public petitions. It
allows individuals to create, view, and track petitions through
a user-friendly interface, improving accessibility and
organization. Petitions are automatically categorized based on
departments and types of issues, ensuring that they reach the
appropriate authorities more efficiently.
To ensure accountability and system integrity, the platform
integrates user authentication by collecting essential personal
details such as name, address, and location. A role-based
access control mechanism is also incorporated to maintain
information security, allowing differentiated access levels
based on user roles.

1.1 Digital Governance


Digital governance, often referred to as e-governance, is
the integration of digital technologies into the core functions
of public administration and governance. It represents the
modern evolution of administrative practices, leveraging
computational tools and networked infrastructure to provide
citizens with efficient, transparent, and inclusive access to
government services.
The fundamental objective of digital governance is to
streamline bureaucratic procedures, enhance accountability,
and bridge the gap between governments and the public
through the use of information and communication
technologies (ICTs).
Digital governance is characterized by its capacity to
xii
enable real-time information exchange, automate repetitive
administrative tasks, and support data-driven decision-making.
It transforms conventional governance into a collaborative
ecosystem where public feedback, participatory mechanisms,
and service delivery operate through online portals, mobile
apps, and cloud-based systems. At its core, digital governance
promotes openness, transparency, responsiveness, and
inclusivity—hallmarks of a modern democratic society.

atural Language Processing (NLP)

Natural Language Processing (NLP) is a critical sub-


field of artificial intelligence that focuses on the interaction
between human language and computational systems. It
empowers machines with the ability to read, interpret,
understand, and generate human language in a meaningful
way. At the core of NLP lies the challenge of enabling
computers to process linguistic data the way humans do—
accounting for syntax, semantics, sentiment, context, and
ambiguity. The complexity of human language, with its
intricate grammar, varying dialects, idiomatic expressions, and
contextual meanings, makes NLP one of the most intricate
areas of computer science and AI.
In the context of digital platforms such as a petition
management system, NLP plays a transformative role in
automating content analysis and decision-making. The system
must extract meaningful features from large volumes of
unstructured text submitted by users. This includes identifying

xiii
critical keywords, urgency indicators, and relevant
departments. NLP enables automatic classification of petitions
into categories like “Urgent”, “Fast”, and “Normal” based on
the presence of weighted keywords and contextual cues. It also
facilitates the detection of semantic similarities among
petitions, allowing the system to flag or merge duplicate
grievances effectively.
Incorporating NLP into a governance platform marks a
significant step toward intelligent automation and proactive
administration. It enhances responsiveness by identifying
high-priority issues, promotes inclusivity by analyzing diverse
linguistic patterns, and strengthens transparency by uncovering
public sentiment. Ultimately, NLP transforms textual petitions
into actionable insights, laying the foundation for smarter,
data-driven decision-making in digital public service
platforms.

ser Authentication

User authentication is a foundational pillar in the design


of secure digital systems, ensuring that access to resources and
services is granted only to verified and authorized individuals.
In the context of modern web-based applications,
authentication mechanisms are employed to validate user
identities and safeguard sensitive operations from
unauthorized interference.
In this petition management system, authentication is
achieved through Aadhar-based verification, aligning with

xiv
government-grade standards for citizen identity validation. By
requiring users to submit their name, Aadhar number, date of
birth, and location, the system ensures that only legitimate
users are allowed to raise or endorse petitions. This prevents
fraudulent submissions and promotes transparency in the
grievance redressal process.
Furthermore, the system integrates with Flask-Login for
session management and bcrypt for secure password hashing,
enhancing both security and usability.
By implementing multi-layered authentication
procedures, the platform enforces a high standard of identity
assurance, a critical requirement for any digital tool aiming to
support participatory governance and protect citizen data.

entiment Analysis

Sentiment analysis, also known as opinion mining, is a


subfield of Natural Language Processing (NLP) that focuses
on the computational identification and categorization of
emotions, opinions, and attitudes expressed in text. It enables
machines to determine the subjective polarity of textual data—
whether it reflects a positive, negative, or neutral sentiment.
Sentiment analysis plays a pivotal role in understanding public
opinion, gauging user satisfaction, and prioritizing responses
in large-scale text-driven systems.
In digital governance platforms such as the Petition
Management System, sentiment analysis is employed to
evaluate the emotional tone and urgency conveyed by
petitioners. By analyzing the linguistic cues embedded in user-
xv
submitted grievances, the system can infer public mood and
allocate appropriate priority to each case. This allows
administrators to identify high-impact issues based not only on
content frequency or keyword presence but also on the
intensity of citizen concern reflected in language usage.
Technically, sentiment analysis involves multiple
stages, including text preprocessing, feature extraction,
sentiment classification, and result aggregation. The core
methodologies can range from lexicon-based models, which
use predefined dictionaries of sentiment-bearing words, to
machine learning models trained on annotated datasets. These
models utilize statistical and deep learning techniques to
classify sentiment at the document, sentence, or aspect level.

Key functionalities of sentiment analysis include:

 Polarity Detection – determining whether a statement is positive, negative, or


neutral
 Emotion Recognition – identifying emotions such as anger, joy, frustration, or
concern
 Intent Classification – inferring the urgency or purpose behind the user’s message
 Aggregated Scoring – quantifying sentiment trends across multiple petitions

By integrating sentiment analysis, the Petition


Management System enhances its ability to make intelligent,
data-driven decisions.
Petitions expressing strong dissatisfaction or emotional
urgency are flagged for immediate review, enabling authorities

xvi
to act on matters of high social sensitivity. This not only
improves the responsiveness of public service delivery but
also ensures that civic platforms are attuned to the collective
emotional landscape of the population. Sentiment analysis thus
transforms raw textual data into actionable insights,
reinforcing the commitment to participatory governance and
citizen-centric decision-making.

hallenges in Petition Systems

Transparency and accountability are the cornerstones of


any effective public grievance redressal mechanism. Petition
systems, designed to amplify citizen voices and foster
participatory governance, are often burdened by a variety of
operational and structural challenges that hinder their ability to
function transparently and hold authorities accountable.
Despite the noble intent behind petition platforms, traditional
systems frequently fall short of ensuring visibility into the
progress of complaints, traceability of actions taken, and
clarity on the roles of departments involved.
One of the key challenges lies in the opacity of
administrative workflows. Once a petition is submitted,
citizens often have no clear insight into how it is processed,
which authority is responsible, or what the expected timeline
for resolution is. This lack of visibility can lead to mistrust,
disillusionment, and reduced public engagement. An effective
system must therefore incorporate features that enable users to
track the real-time status of their petitions, receive timely
notifications, and access historical records of actions taken—
xvii
all while maintaining the integrity and confidentiality of
administrative procedures.
Another critical aspect is the equitable visibility and
prioritization of petitions. In traditional models, high-
engagement petitions may receive undue attention, while
equally important but less-publicized issues remain
unaddressed. A transparent petition platform must balance
user interactions with sentiment analysis and urgency
classification, so that issues are prioritized based on public
need rather than popularity.
Ultimately, addressing these challenges requires a
holistic approach that combines intelligent automation,
structured workflows, and citizen-centric design. The goal is
to establish a system where every voice is heard, every petition
is traceable, and every action is accountable—thus laying the
foundation for a responsive and transparent digital governance
model.

ivic Engagement

Civic engagement refers to the active participation of


citizens in decision-making processes that shape public life,
policies, and governance. It is vital for strengthening
democracy by ensuring governments remain responsive,
inclusive, and accountable to people's needs. Petition systems
are crucial tools for enabling civic engagement, offering
structured platforms for individuals to voice concerns, propose
changes, and advocate for social issues.
However, limited accessibility poses a major obstacle to
xviii
civic engagement through petition platforms. Many systems
are not designed for users from diverse linguistic, educational,
or geographical backgrounds, creating a digital divide. As a
result, marginalized or rural communities, despite having
important concerns, are often unable to participate fully,
leaving civic voices unevenly represented.
Furthermore, petition saturation and redundancy weaken
the impact of civic action. Citizens may submit similar
petitions without knowing, leading to fragmented efforts and
administrative overload. True civic engagement demands
inclusive, intelligent, and interactive systems that simplify
participation, foster dialogue, and offer clear outcomes.
Through thoughtful design and technological innovation,
petition platforms can become stronger instruments for
democratic expression and social change.

I-Driven Decision Making

Historically, civic administration and petition handling have relied on manual


processes, subjective evaluations, and reactive governance, often resulting in
inefficiencies and delays. The introduction of artificial intelligence (AI) marks a
transformative shift, moving governance models toward proactive, data-driven
frameworks. AI in petition systems aims not just to automate tasks but to enhance
the quality, speed, and fairness of decisions at scale. Drawing parallels to AI
systems like DeepMind’s agents mastering diverse tasks through reinforcement
learning, AI in petition handling learns to generalize across different types of
grievances using NLP and classification models extracting context, urgency,
sentiment, and relevance whether the issue is road maintenance, water supply, or

xix
healthcare.
This convergence of narrow AI techniques is crucial for addressing socio-civic
problems that demand an understanding of language and social context. Much like
machine translation requires comprehension and semantic fidelity, petition
prioritization involves parsing user emotions, factual content, and engagement
metrics to guide action. AI-driven insights help generate dynamic dashboards and
performance indicators for administrators, turning static petition queues into
adaptive, learning systems. While full artificial general intelligence (AGI) remains
distant, current AI implementations already demonstrate a leap toward more
responsive, transparent, and efficient governance, making public administration
increasingly people-centric and data-informed.

OBJECTIVE

This project aims to automate petition handling by solving delays and


mismanagement. It uses NLP and BERT to accurately categorize petitions and route
them to the correct departments. Repeated grievances are detected to avoid
redundancy and improve efficiency. Overall, it ensures faster response, better
transparency, and accountable petition management.

xx
CHAPTER 2
LITERATURE SURVEY

1.Mohamed Ibrahim Abdullahi; Abdirahman Abdiaziz Geesey; Abdirahman


Ali Maow; Mohamed Hasan Omar; Bashir Abdinur Ahmed proposed
“Enhancing Online Petitions in Somalia for Civic Engagement and Policy-
Making Using Blockchain.”

Somalia faces significant challenges in fostering active public participation and


equitable governance due to issues such as limited access to civic platforms, safety
concerns, and centralized systems prone to manipulation and fraud. While citizen
involvement is essential for shaping public policy, creating a secure and transparent
online petition system tailored to Somali-specific needs has been an ongoing
challenge. Traditional engagement methods often fail due to logistical barriers and
security risks.To address these issues, this study focuses on developing a
blockchain-based online petition platform designed specifically for Somalia.
xxi
Blockchain technology ensures data integrity and the authenticity of signatures,
fostering trust in the process. Unlike globalized or generalized systems, the
proposed platform is customized to the Somali context, featuring a user-friendly
interface for creating, signing, and managing petitions. It also provides real-time
monitoring and interactive tools to promote community participation.

2. Yashaswi Sharma; Abhinav Mishra; Nivedita Shukla; Deepika Sharma et al


proposed “Destiny of Legal Petition: Accept or Reject?: A Machine Learning
Approach to Predict the Legal Petition's Initial Decision”

Presently, the Indian judiciary system grapples with around 30 million pending
cases, translating to approximately 73,000 cases per judge. This backlog introduces
biases into the system, compounded by the undue influence of political figures and
affluent individuals, jeopardizing the judiciary's independence. Additionally, issues
such as inconsistent data across different courts, the absence of fixed case
completion deadlines, rising crime rates, and a surge in Public Interest Litigation
(PIL) further exacerbate the problem. Despite the establishment of fast-track courts,
tribunals, and other specialized entities to expedite case resolution, the incorporation
of technology has become indispensable. A rapid and automated decision support
system is urgently required to address backlogs and ensure data coherence within
the judiciary. This study focuses on predicting the initial decision for petitions,
specifically determining whether a petition should proceed to further legal
proceedings based on the statements framed by legal practitioners. The work
employs the ILDC dataset, comprising approximately 7500 data points.

3. Dhananjay Kalbande; Pulin Prabhu; Anisha Gharat; Tania Rajabally


proposed “A Fraud Detection System Using Machine Learning”

xxii
With financial services being an integral part of modern society and online
transactions becoming more prevalent, the complexity and volume of financial
activities have also increased, leading to a rise in fraudulent activities. The authors
identify the need for an automated fraud detection system to combat this alarming
increase in frauds. The sheer volume of transactions in online payments and credit
card systems makes it virtually impossible to manually detect fraudulent activities
with high speed and accuracy. The proposes a Machine Learning-based solution
designed to address this issue efficiently and accurately. The model aims to
distinguish between "fraudulent" and "genuine" transactions in real-time, providing
a scalable solution that can be employed across various sectors involved in finance.
The proposed system is not only robust but also cost-effective, offering an efficient
method to detect and prevent fraudulent activities. By analyzing various factors
during a transaction, it helps assess whether the transaction could potentially be
harmful. The system’s ability to predict and detect fraud before it occurs can
significantly reduce the number of unfortunate incidents related to financial fraud.
The integration of Machine Learning techniques ensures the system's ability to
adapt to evolving fraud patterns, providing an effective and dynamic tool for fraud
detection in today’s fast-paced digital economy.

4.Xiangman Li; Yunke Liu; Jianbing Ni; Yuanyuan He proposed “Securing E-


Petition:

A Privacy-Preserving Fine-Grained Electronic Petition System for Health and


Political Petitions” E-petitions have become a crucial platform for collecting public
opinions and requesting actions from authorities regarding health and political
issues. However, this widespread use of e-petitions poses significant privacy
concerns for the signers involved, as their personal data and opinions may be
exposed. The authors address this issue by proposing a privacy-preserving, fine-
xxiii
grained e-petition system designed to protect signer privacy while ensuring the
credibility of the petition process. The proposed system utilizes attribute-based
identity verification for signers, enabling the definition of specific attribute policies.
These policies ensure that only individuals whose attributes align with the
requirements of the petition can participate. The fine-grained approach is a
significant improvement over traditional e-petitions, as it proactively selects signers
to enhance the trustworthiness of the petition results.
5.Ayesha Rahman; David J. Wilson; Machine Learning Approaches for
Grievance Redressal and Public Petition Management

This by Ayesha Rahman and David J. Wilson, published in 2021, delves into the
integration of machine learning (ML) and Natural Language Processing (NLP)
techniques in the grievance redressal and public petition management domains.
The authors propose an automated framework designed to efficiently handle and
prioritize public grievances, thereby improving the responsiveness and
transparency of the system. By leveraging NLP techniques, the system can process
large volumes of text data from petitions, classify them into relevant categories,
and identify patterns or recurring issues that require attention.
The emphasizes the importance of machine learning in
automating the classification of petitions, detecting urgent
issues, and prioritizing them based on factors like sentiment
and public engagement. This approach significantly reduces
the time spent by human operators in manual processing, thus
enabling quicker resolution of public grievances. The authors
also explore how sentiment analysis can be used to understand
the urgency of a petition and rank issues accordingly, ensuring
that critical concerns are addressed promptly. Ultimately, this
research highlights the potential of AI-driven systems to
xxiv
enhance the efficiency, transparency, and accountability of
grievance redressal processes in public governance.
6.Artificial Intelligence for Public Grievance Management: A Comprehensive
Review Ravi Kumar, Aditi Mehra,2020

The Artificial Intelligence for Public Grievance Management: A Comprehensive


Review by Ravi Kumar and Aditi Mehra (2020) presents a detailed analysis of how
artificial intelligence (AI), especially Natural Language Processing (NLP), can be
utilized to improve the management of public grievances. The study explores the
potential of AI to automate the grievance redressal process, ensuring timely and
efficient handling of public petitions. By employing NLP techniques, the system can
analyze, categorize, and prioritize grievances based on their content, enabling
quicker identification of urgent concerns. This application enhances transparency by
allowing citizens to track the progress of their complaints and receive automated
updates, thus fostering trust in the system. The authors emphasize the role of AI in
reducing manual intervention, minimizing human error, and ensuring accountability
within grievance management frameworks. Additionally, the discusses how AI can
optimize decision-making, facilitate public participation, and contribute to the
overall democratization of grievance management. Ultimately, the provides a
comprehensive review of the advancements in AI for public grievance management,
highlighting its potential to improve citizen engagement and governance processes.
7.The Role of NLP in Petition Analysis and Public Sentiment Detection Kevin
S. Lee, Jessica Wang, 2023

The Role of NLP in Petition Analysis and Public Sentiment Detection, explores the
application of Natural Language Processing (NLP) algorithms in analyzing public
petitions to detect sentiment, prioritize issues, and categorize petition content
effectively. The authors argue that the growing volume of digital petitions demands
xxv
an automated, data-driven approach to ensure timely and accurate responses. The
study demonstrates how NLP techniques, such as sentiment analysis and topic
modeling, can be leveraged to identify recurring themes, emotional tones, and
public concerns in petitions.
The research highlights the potential of sentiment
analysis to evaluate the urgency and emotional intensity of
petitions, allowing authorities to prioritize urgent matters and
address critical issues promptly. Furthermore, the emphasizes
the importance of categorizing petitions into predefined topics
to streamline the decision-making process, ensuring that the
right department or official handles the relevant issues. By
automating these tasks, the system can reduce administrative
burden and enhance public participation in governance,
promoting transparency and accountability. This study lays the
groundwork for future implementations of NLP-driven tools in
petition management systems, providing a foundation for
improving civic engagement.
8.AI-Driven Digital Governance: Improving Petition Systems through
Automation Carla Rodriguez, Peter C. Scott,2024

The explores the revolutionary role of Artificial Intelligence (AI) in transforming


digital governance, particularly focusing on the automation of petition systems. By
leveraging Natural Language Processing (NLP), the study highlights how AI can
automate the processing and management of petitions, significantly reducing
manual effort and human intervention. The authors discuss how NLP algorithms can
be used to analyze large volumes of petition data, automatically categorize petitions,
extract relevant details, and even identify key issues or trends. This automation
improves the efficiency of decision-making by providing quicker insights and
xxvi
enabling the prioritization of critical issues based on sentiment analysis and
urgency. Furthermore, the addresses the transparency and accountability that AI-
driven systems can provide in petition management, allowing stakeholders and the
public to track the progress of petitions in real-time. The integration of AI into
petition systems not only optimizes the workflow but also ensures a more
responsive and inclusive approach to public participation. Ultimately, this
advocates for the adoption of AI technologies to streamline governance processes,
making them more efficient, transparent, and democratic.
9.Public Petition Systems: Leveraging AI for Effective Management and
Resolution Tracking Jason T. Hall, Sophia Collins,2020
In their 2020 study, Public Petition Systems: Leveraging AI for Effective
Management and Resolution Tracking, Jason T. Hall and Sophia Collins investigate
the role of Artificial Intelligence (AI) in modernizing and enhancing the efficiency
of public petition systems. The specifically focuses on the application of Natural
Language Processing (NLP) techniques to automate the tracking, categorization, and
resolution of public grievances. By using NLP, the system is able to analyze large
volumes of petitions, extract key information, and identify recurring issues or
themes. This automation significantly reduces the manual effort required to process
petitions, ensuring that urgent concerns are flagged and addressed promptly.
Furthermore, the authors highlight how AI can prioritize petitions based on
sentiment analysis and public engagement, ensuring that issues with the greatest
public interest are handled first. The study also explores the transparency and
accountability provided by AI-driven petition systems, allowing users to track the
resolution status of their grievances in real-time. Overall, the demonstrates the
transformative potential of AI and NLP in improving public petition systems,
ensuring better governance and responsiveness to citizen concerns.
10.Enhancing Public Participation through AI-Driven Petition Management
Platforms Elena Rivera, Mark F. Thompson 2024
xxvii
This explores the significant role of AI-powered petition management platforms in
enhancing public participation by ensuring greater transparency, accountability, and
efficiency. The authors investigate how Natural Language Processing (NLP)
techniques are utilized to analyze and categorize public petitions and grievances,
automating the process of managing large volumes of data. By employing NLP, the
system can identify key issues, assess the sentiment behind petitions, and prioritize
urgent concerns based on relevance and public interest. This allows for the swift
resolution of critical issues, ensuring that important matters are addressed in a
timely manner.
Furthermore, the highlights how AI can provide real-
time tracking of petition statuses, fostering transparency in the
decision-making process. Citizens can track the progress of
their petitions, thus ensuring accountability in how grievances
are handled. The study emphasizes the role of AI in improving
democratic participation by offering citizens an accessible
platform to voice concerns and engage with governance
systems.

CHAPTER 3
SYSTEM ANALYSIS

3.1 EXISTING SYSTEM

In conventional digital governance frameworks,

xxviii
grievance redressal is typically managed through manual or
semi-automated systems that rely heavily on human
intervention for classification, routing, and prioritization of
petitions. While several platforms enable online petition
submission, they lack intelligent systems to understand the
content and urgency of the issues raised. These systems often
depend on static user-defined categories and manual triaging,
which can result in delays, misclassifications, and redundancy.
The current approaches do not incorporate Natural
Language Processing (NLP) or Artificial Intelligence (AI) in
analyzing textual data. As a result, recurring issues go
undetected, petitions are not prioritized based on urgency or
public sentiment, and duplicate entries overload the system
without offering aggregated insights. Furthermore, user
engagement metrics and feedback mechanisms are either
underutilized or completely absent, leading to limited civic
participation and minimal iterative system improvement.
Although some digital portals allow for department-
wise routing and basic status updates, their lack of automation
in classification, urgency detection, and sentiment analysis
hinders effective decision-making. These limitations highlight
the pressing need for an AI-powered approach that enhances
the petition lifecycle through intelligent automation, making
governance more transparent, efficient.
3.1.1 LIMITATIONS OF EXISTING SYSTEM

xxix
 No Automated Urgency Detection: Current solutions do not incorporate any
mechanism to analyze urgency levels based on petition content, leading to
equal treatment of both minor and critical issues.
 Inability to Detect Duplicates: There is no robust algorithm to detect or merge
similar petitions, causing data duplication, increased admin workload, and
diluted attention to recurring public concerns.
 Absence of Sentiment Analysis: Systems fail to evaluate public tone or
distress through textual cues, thus lacking emotional prioritization or public
mood analysis.

3.2 PROPOSED SYSTEM

Managing petitions in a scalable, intelligent, and transparent manner is critical


for modern digital governance. Traditional systems often fail to understand
underlying concerns, detect urgency, or identify repeating societal issues. To
address these gaps, the proposed system leverages Artificial Intelligence (AI) and
Natural Language Processing (NLP) techniques to automate the entire lifecycle of
petitions from submission to resolution.
This project introduces a solution that uses AI models to analyze the textual
content of user-submitted petitions, categorize them by urgency and department,
and detect recurring issues in real-time. At its core is an NLP-based categorization
pipeline, which processes the subject and description of each petition using
tokenization, lemmatization, stopword removal, and vectorization with models like
TF-IDF or BERT.
The system classifies petitions into urgency levels—Urgent, Fast, and Normal
—using machine learning models such as Logistic Regression, Random Forest, or
Transformer-based classifiers. To route petitions accurately to the right department,
it employs keyword-topic mapping and multi-label classification, matching each

xxx
petition against a curated list of department tags using text similarity techniques.
Duplicate and recurring petitions are detected using semantic similarity
analysis. Sentence embeddings generated through models like SBERT or Universal
Sentence Encoder allow the system to compute cosine similarity scores between
new and existing petitions. High similarity (≥85%) flags petitions as duplicates or
clusters them with similar issues to promote collective resolution.
Sentiment analysis is performed on each petition to gauge public mood and
distress levels. Using pre-trained models like VADER, TextBlob, or fine-tuned
BERT, the system classifies sentiments as Positive, Negative, or Neutral. Petitions
with high negative sentiment and strong public engagement are automatically
escalated for faster administrative response.
The system also tracks engagement metrics such as likes, shares, comments,
and feedback scores. These metrics are integrated into the petition prioritization
process, ensuring that widely supported issues are ranked higher and resolved
sooner, thereby strengthening community participation and trust in the platform.
An admin dashboard enables government officials to view, filter, and manage
petitions efficiently. It features visual analytics like heatmaps, urgency-based
filters, frequency charts for issue categories, and department-specific workloads.
By clustering recurring issues and using continuous feedback to refine its models,
the system promotes a more transparent, efficient, and data-driven approach to
public grievance handling.

3.2.1 ADVANTAGES OF THE PROPOSED SYSTEM

 Real-Time Petition Analysis: The system processes and categorizes petitions


in real time as they are submitted, enabling immediate classification, routing,
and prioritization. This allows concerned departments to respond more

xxxi
swiftly, especially for urgent or emergency-related petitions, enhancing
responsiveness and public trust.
 Scalability and Multi-User Support: Unlike traditional petition systems that
are limited by manual processing, the proposed AI system can analyze and
handle thousands of petitions simultaneously. This scalability makes it highly
suitable for high-traffic platforms involving large urban populations or state-
wide governance bodies.
 Accurate Categorization and Prioritization: By leveraging NLP and machine
learning algorithms, the system provides precise classification of petitions
based on urgency and content. This ensures that critical issues are addressed
promptly, improving the effectiveness of grievance redressal.
 Automated Duplicate Detection: The system uses semantic similarity
detection to identify and flag duplicate or closely related petitions. This
reduces redundancy, minimizes admin workload, and improves the clarity and
focus of issues submitted by the public.
 Sentiment-Driven Escalation: Integration of sentiment analysis allows the
system to assess the emotional tone of the petition (e.g., frustration, anger,
distress), which enhances the ability to prioritize petitions that reflect public
dissatisfaction or emergencies.
 Potential for Integration: The AI model and backend system can be integrated
into existing e-governance portals or mobile applications. This flexibility
increases the system’s adaptability and potential for widespread deployment.

xxxii
CHAPTER 4

SYSTEM REQUIREMENTS

4.1 HARDWARE REQUIREMENTS


Component Specification
System PC or Laptop
Processor Intel i3/i5/i7 or AMD Ryzen Series
RAM Minimum 4 GB (8 GB Recommended for training models)

OFTWARE REQUIREMENTS
Component Specification
Operating System Windows 10 or 11
Programming Language Python
Frontend HTML, CSS, JavaScript
Backend Python
Framework Flask

SOFTWARE DESCRIPTION

PYTHON 3.10+

Python is a flexible and easy-to-learn programming language, widely used for


backend development and data processing. It is the core language used to implement
the petition analyzer and its categorization logic.

xxxiii
FLASK

Flask is a micro web framework written in Python. It is used to create the


server-side of the application, handling routing, sessions, and interactions between
frontend and backend.

spaCy

spaCy is an open-source NLP library designed specifically for production use.


In this project, it processes uploaded petition content to detect keywords and
categorize petitions based on urgency and relevant departments. The model used is
en_core_web_sm.

SQLALCHEMY

SQLAlchemy is the ORM (Object Relational Mapper) used for database


management. It allows easy communication between Python classes and the SQLite
database used to store users, petitions, comments, likes, and verification records.

WTForms & Flask-WTF

These are used for form validations and secure data input from users.

FLASK-LOGIN & FLASK-BCRYPT


Flask-Login manages user sessions and authentication. Flask-Bcrypt is used
to securely hash and validate passwords.

FITZ (PyMuPDF)

xxxiv
Used to extract text content from uploaded PDF petitions so that NLP
processing can be performed seamlessly on text data.

G4F API

A simple chatbot interface powered by the g4f API is integrated for user
interaction and automated assistance.

BASIC USAGE

Upload a petition (TXT or PDF) → Extract content → Analyze text with


spaCy → Classify as “Urgent”, “Fast”, or “Normal” → Identify Department →
Display to users/admins → Enable comments, likes, and verification → Notify upon
resolution via email.

INDENTATION

Python relies on indentation for defining blocks of code rather than curly
braces. This ensures readability and enforces clean code structure.

EXAMPLE USAGE IN CATEGORIZATION:

def categorize_petition(content):
keywords = {
"urgent": ["immediate", "emergency", "critical", "severe", "urgent"],
"fast": ["quick", "rapid", "fast", "soon"],
}
doc = nlp(content.lower())
...
This system enables intelligent petition management and helps officials prioritize
and address public grievances more efficiently.
xxxv
CHAPTER 5
SYSTEM DESIGN

5.1 ARCHITECTURE DIAGRAM


System architecture is the structured framework that
defines the behavior, structure, and more views of a system.
For the AI-Based Petition Management System, the
architecture outlines how various functional components—
such as user interfaces, AI modules, databases, and dashboards
—interact with each other. The goal is to ensure that the
system meets its functional requirements like petition
submission, classification, routing, tracking, and feedback
handling. The architecture supports scalability, modularity,
and real-time interaction between users and administrative
authorities.

xxxvi
Figure 5.1.1
The system follows a client-server model where users
interact with the application via a frontend interface, while
backend services manage classification, routing, duplicate
detection, and data storage.

At the core of the system lies the NLP engine, which


performs real-time analysis and categorization of petitions
using trained machine learning models
.
5.2 USE CASE DIAGRAM

The user initiates the process by registering or logging


into the platform using a secure authentication process. Upon
successful login, the user is taken to a dashboard where they
can raise a petition by filling out a form that includes fields
like subject, description, and location, and allows uploading
xxxvii
supporting documents. When the petition is submitted, it is
processed by the NLP Engine which categorizes the petition
based on urgency and maps it to the relevant department using
predefined classification logic.

Key Use Cases


 User Registration and Login
 Submit Petition
 View Petition Status
 Receive Notifications
 Admin View Petitions
 Admin Route/Assign Petitions
 Admin Update Petition Status
 System Perform NLP Categorization
 System Detect Duplicate Petitions
 User Submit Feedback
 Admin View Analytics

xxxviii
Figure 5.2.1 Usecase Diagram

5.3 CLASS DIAGRAM

The class diagram illustrates a structured object-oriented


model of the Petition Management System, representing the
core components and their interactions. At the top level, the
GUI class acts as the central interface for user interaction,
bridging front-end actions with back-end processing.
Supporting classes include User, Petition, Admin, Department,
and NLP Processor, each responsible for specific subsystems

xxxix
like user management, AI-based categorization, and petition
tracking.

 Class: GUI
Attributes: screenLayout, currentUser
Methods: displayLogin (), showDashboard (), submitPetition (), trackStatus ()
Responsibilities: Manages user interface logic and routes user interactions to backend
logic.
 Class: User
Attributes: userID, name, aadharNumber, address, email, userType
Methods: login (), register (), viewPetitions (), submitPetition ()
Responsibilities: Handles user authentication and petition submission. Differentiates
between public users and officials.
 Class: Petition
Attributes: petitionID, subject, description, location, status, submissionDate, priority
Methods: assignDepartment(), updateStatus(), attachDocuments()
Responsibilities: Represents a user-submitted grievance. Stores status and department
mapping info.
 Class: Admin
Attributes: adminID, name, permissions
Methods: viewAllPetitions(), filterPetitions(), resolvePetition(), sendNotification()
Responsibilities: Manages petitions and oversees the resolution process.
 Class: Department
Attributes: departmentID, name, keywords, assignedPetitions
Methods: mapPetition(), notifyAdmin()
Responsibilities: Receives petition assignments based on keyword-based mapping.
 Class: NLPProcessor
Attributes: modelVersion, similarityThreshold
xl
Methods: classifyPriority(), detectDuplicates(), extractKeywords(),
analyzeSentiment()
Responsibilities: Uses NLP algorithms to categorize and prioritize petitions, detect
duplicates, and conduct sentiment analysis.

Figure 5.3.1 Class Diagram

xli
5.4 SEQUENCE DIAGRAM

The AI-Based Petition Management System operates


through a series of well-defined application states that govern
how a petition moves through its lifecycle from creation to
resolution. The two main system states are "Idle" and
"Active", while the petitions themselves transition through
various states such as "Drafted", "Submitted", "Classified",
"Assigned", "In Progress", and "Resolved".
Initially, the system is in the "Idle" state, waiting for
user interaction. Once the user logs in and initiates a petition
submission, the system transitions to the "Active" state.
Within this active state, the system enters a substate of
"Petition Drafted", where the user fills out and prepares the
petition form. Once the user submits the petition, the system
moves to the "Submitted" state.
Upon submission, the system automatically initiates
NLP classification and sentiment analysis, transitioning the
petition into the "Classified" state. The system then checks for
duplicates using semantic similarity. If no duplicate is found,
the petition proceeds to the "Assigned" state, where it is routed
to the relevant department. If a duplicate is found, the petition
transitions to a "Clustered" state, where it is grouped with
similar petitions.
After assignment, the petition status is updated to "In
xlii
Progress" as the respective department begins working on the
issue. Once the issue is resolved, the state transitions to
"Resolved". At this point, the user is notified and prompted to
give feedback. If feedback is submitted, the petition transitions
to the "Feedback Received" state, after which the process
concludes and the system returns to the "Idle" state, ready for
the next user interaction.
Throughout this process, the application maintains
system-level transitions between "Idle", "Active", and
"Processing" modes, depending on the user and admin actions.

xliii
Figure 5.4.1 Sequence Diagram

5.5 ACTIVITY DIAGRAM

The activity diagram for the AI-Based Petition


Management System begins with the initial node, representing
the launch or start of the application. The system initializes its
components, including the frontend interface, database
connections, and background NLP services. Once the platform
is active, it waits for the user to either register or log in. Upon
xliv
successful login or registration, the system authenticates the
user and grants access to the petition dashboard.

xlv
Figure 5.5.1 Activity Diagram

xlvi
CHAPTER 6
SYSTEM TESTING

Testing is a systematic process aimed at verifying


whether the developed software meets the specified
requirements and functions correctly under defined conditions.
It plays a crucial role in identifying bugs, ensuring quality, and
validating the software’s behavior in real-world scenarios.

Testing Steps:
 Unit Testing
 Usability Testing
 Integration Testing
 Regression Testing

6.1 UNIT TESTING


Unit testing is the initial level of testing performed on
individual components of the system. Each module or function
is tested in isolation to ensure that it operates correctly
according to its design and logic.
In the Petition Management System, unit testing is applied to core units such as:
 User class: login, registration validation
 Petition class: creation, document upload
 NLP Processor: classification and duplicate detection logic
Each test checks specific inputs against expected outputs to
ensure functional accuracy. This phase ensures that all
building blocks of the system behave as intended before
xlvii
integration.

6.2 USABILITY TESTING

Usability testing assessed the interface and user experience of the platform.
 User Interface (UI) Consistency:
Verified that the layout, icons, and navigation were consistent across different modules.
Ensured user-friendly design for both technical and non-technical users.
 Feedback & Error Messages:
Tested how the system responds to invalid inputs
Accessibility:
Evaluated whether the system is usable for people with disabilities (basic color
contrast, font size, etc.).
6.3 INTEGRATION TESTING
Integration testing validated the data flow and interaction
between different modules.
 User Module ↔ Petition Module:
Confirmed that authenticated users could create and view petitions, and data is passed between
modules seamlessly.
 Petition Module ↔ NLP Module:
Verified that petitions are automatically sent to the NLP engine after submission, and
classification results are correctly stored and displayed.
 Admin Dashboard ↔ Public Portal:
Changes made by admins (e.g., status updates, prioritization) were reflected in the public-
facing views.
xlviii
6.4 REGRESSION TESTING
After code changes or feature additions, regression testing
was conducted to ensure existing functionalities remained
unaffected. Automated and manual tests were run to validate
stable performance.

CHAPTER 7
CONCLUSION AND FUTURE ENHANCEMENTS

CONCLUSION
The AI-Driven Petition Management System serves as a
significant advancement in the realm of digital governance,
offering a comprehensive and intelligent platform for handling
public grievances. By incorporating Natural Language
Processing (NLP) algorithms, the system can intelligently
analyze large volumes of petition data to identify recurring
themes, prioritize urgent matters, and eliminate duplicate or
redundant entries. This automated approach not only
accelerates the grievance redressal process but also ensures
that critical issues receive timely attention based on sentiment
analysis and user engagement.
The system’s structured categorization of petitions by
department and issue type, along with secure user
authentication, ensures that all inputs are valid, traceable, and
efficiently directed to the appropriate authority. Public users
are granted role-based access to promote controlled visibility
while maintaining openness and transparency in the decision-
making process.
xlix
Moreover, the platform encourages citizen participation
by making the petitioning process more accessible, engaging,
and responsive. By ranking petitions and displaying their
progress, the system reinforces accountability and public trust,
enabling a more democratic and inclusive environment for
voicing concerns.
In conclusion, this AI-powered solution not only
enhances the operational efficiency of petition handling but
also strengthens the fundamental values of transparency,
accountability, and participatory governance. It lays the
foundation for a smarter, more responsive administrative
framework that meets the evolving expectations of digital-age
citizens.

FUTURE ENHANCEMENT
While the Petition Management System in its current
form offers a robust and intelligent platform for handling
public grievances, there are several potential areas for
enhancement to further improve functionality, scalability, and
user engagement. These enhancements are aimed at making
the system more adaptive to evolving user needs, integrating
with advanced technologies, and expanding its scope within
the public administration framework.
1. Mobile Application Support
To improve accessibility and encourage higher user
participation, a dedicated mobile application can be developed
for both Android and iOS platforms. This will allow users to
l
submit petitions, track status, and receive notifications in real-
time from their smartphones
2. Multi-Language Interface
India is a linguistically diverse country. To increase
reach and usability, the system can be enhanced to support
multiple regional languages. This will allow users from
various states to interact with the system in their native
language, thus breaking the language barrier and encouraging
broader civic participation.
3. Integration with Government Portals
To streamline administrative workflows, the system can
be integrated with existing e-governance platforms such as
Digital India, RTI, or MyGov. This will enable seamless
information sharing and cross-functional processing of citizen
concerns, reducing delays and duplication of work.
4. Geo-Tagging of Issues
By integrating maps and geo-location services, users
can tag the exact location of the issue they are reporting. This
can help departments understand regional complaint density
and plan area-specific responses more effectively.

CHAPTER 8
APPENDICES

APPENDIX A(SOURCE CODE)

from sqlalchemy.exc import IntegrityError


li
from tokenize import Comment
from distro import like
from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, UserMixin, login_user, login_required,
logout_user, current_user
import os
from werkzeug.utils import secure_filename
import spacy
from datetime import datetime
from flask import Flask, request, jsonify, session

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] = 'secretkey'
app.config['UPLOAD_FOLDER'] = 'static/uploads'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

nlp = spacy.load("en_core_web_sm")

# User Model
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
lii
name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
mobile = db.Column(db.String(15), nullable=False)
dob = db.Column(db.String(20), nullable=False) # You can change to db.Date if
needed
profile_pic = db.Column(db.String(100)) # stores filename

class Petition(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
file_name = db.Column(db.String(255), nullable=False)
is_public = db.Column(db.Boolean, default=False)
category = db.Column(db.String(100), nullable=False)
department = db.Column(db.String(100))
upload_time = db.Column(db.DateTime, default=datetime.utcnow)
verified = db.Column(db.Boolean, default=False)
likes = db.relationship("Like", backref="petition", lazy="dynamic")
repeat_count = db.Column(db.Integer, default=1) # Removed content_hash

def increment_repeat_count(self):
self.repeat_count += 1
db.session.commit()
# Verification Model
class Verification(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
liii
aadhar_no = db.Column(db.String(12), unique=True, nullable=False)
dob = db.Column(db.String(10), nullable=False)
location = db.Column(db.String(100), nullable=False)

class Like(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, nullable=False)
petition_id = db.Column(db.Integer, db.ForeignKey("petition.id"),
nullable=False)

class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, nullable=False)
petition_id = db.Column(db.Integer, db.ForeignKey("petition.id"),
nullable=False)
text = db.Column(db.Text, nullable=False)

@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))

@app.route('/index')
def home():
return render_template('index.html')
# User Registration
@app.route('/register', methods=['GET', 'POST'])
def register():
liv
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
mobile = request.form['mobile']
dob = request.form['dob']
password =
bcrypt.generate_password_hash(request.form['password']).decode('utf-8')

profile_pic_file = request.files['profile_pic']
profile_pic_filename = None
if profile_pic_file:
profile_pic_filename = secure_filename(profile_pic_file.filename)
profile_pic_path = os.path.join(app.config['UPLOAD_FOLDER'],
profile_pic_filename)
profile_pic_file.save(profile_pic_path)

user = User(
name=name,
email=email,
mobile=mobile,
dob=dob,
password=password,
profile_pic=profile_pic_filename
)
db.session.add(user)
db.session.commit()
flash("Registration Successful. Please Login.", "success")
return redirect(url_for('login'))
lv
return render_template('register.html')

# User Login
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
user = User.query.filter_by(email=email).first()
if user and bcrypt.check_password_hash(user.password, password):
login_user(user)
return redirect(url_for('home'))
else:
flash("Invalid Credentials", "danger")
return render_template('login.html')

ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = "admin123"

@app.route("/adminlogin", methods=["GET", "POST"])


def admin_login():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")

if username == ADMIN_USERNAME and password ==


lvi
ADMIN_PASSWORD:
session["admin_logged_in"] = True # Store session data
flash("Login successful!", "success")
return redirect(url_for("show_petitions"))

flash("Invalid username or password!", "danger")

return render_template("admin_login.html")

@app.route('/comment_petition/<int:petition_id>', methods=['POST'])
@login_required
def comment_petition(petition_id):
petition = Petition.query.get_or_404(petition_id)
comment_text = request.form.get("comment")

if not comment_text.strip():
flash("Comment cannot be empty!", "danger")
return redirect(url_for('view_petitions'))

comment = Comment(text=comment_text, user_id=current_user.id,


petition_id=petition_id)
db.session.add(comment)
db.session.commit()
flash("Comment added successfully!", "success")
return redirect(url_for('view_petitions'))

@app.route('/verify', methods=['GET', 'POST'])


@login_required
lvii
def verify():
if request.method == 'POST':
name = request.form['name']
aadhar_no = request.form['aadhar_no']
dob = request.form['dob']
location = request.form['location']

# Check verification
verification = Verification.query.filter_by(name=name, aadhar_no=aadhar_no,
dob=dob, location=location).first()
if verification:
# ✅ Retrieve petition data from session
petition_data = session.get("petition_data")

if petition_data:
new_petition = Petition(
file_name=petition_data.get("file_name"),
is_public=petition_data.get("is_public"),
category=petition_data.get("category"),
upload_time=datetime.utcnow(), # Add this if missing in the model
user_id=current_user.id, # Add this if Petition model has user_id
verified=True
)
db.session.add(new_petition)
db.session.commit()
session.pop("petition_data", None)

flash("Petition Verified & Submitted Successfully!", "success")


lviii
return redirect(url_for('home'))
else:
return redirect(url_for('home'))

else:
flash("Verification Failed! Check Your Details.", "danger")

return render_template('verify.html')

@app.route('/petitions')
def view_petitions():
petitions = Petition.query.filter_by(is_public=True).all() # Ignore 'verified' for
testing

if not petitions:
flash("No public petitions available!", "info")

return render_template('petitions.html', petitions=petitions)

def detect_department(content):
department_keywords = {
"Corporation": ["corporation", "municipality", "sanitation", "garbage", "road"],
"Water Supply": ["water", "pipeline", "leak", "drain", "supply"],
"Electricity": ["electricity", "power", "current", "transformer"],
"Health": ["hospital", "clinic", "health", "medical"],
"Education": ["school", "college", "education", "student"]
lix
}
content = content.lower()
for dept, keywords in department_keywords.items():
if any(word in content for word in keywords):
return dept
return "Other"
# Function to categorize petition content
def categorize_petition(content):
keywords = {
"urgent": ["immediate", "emergency", "critical", "severe", "urgent"],
"fast": ["quick", "rapid", "fast", "soon"],
}

category = "Normal"
doc = nlp(content.lower())

for token in doc:


if token.text in keywords["urgent"]:
category = "Urgent"
break
elif token.text in keywords["fast"]:
category = "Fast"

department = detect_department(content)
return category, department

lx
import fitz
@app.route("/upload_petition", methods=["GET", "POST"])
@login_required
def upload_petition():
if request.method == "POST":
file = request.files.get("file")
is_public = request.form.get("is_public") == "on"

if not file:
flash("No file selected!", "danger")
return redirect(url_for("upload_petition"))

file_ext = file.filename.rsplit(".", 1)[-1].lower()


file_path = os.path.join(app.config["UPLOAD_FOLDER"], file.filename)

content = ""
try:
if file_ext == "txt":
content = file.read().decode("utf-8")
elif file_ext == "pdf":
file.save(file_path)
doc = fitz.open(file_path)
content = "\n".join([page.get_text() for page in doc])
else:
flash("Unsupported file format! Upload TXT or PDF.", "danger")
return redirect(url_for("upload_petition"))
except Exception as e:
flash(f"Error reading file: {e}", "danger")
lxi
return redirect(url_for("upload_petition"))

if not content.strip():
flash("Uploaded file is empty or unreadable!", "danger")
return redirect(url_for("upload_petition"))

existing_petition = Petition.query.filter_by(
user_id=current_user.id,
file_name=file.filename
).first()

if existing_petition:
existing_petition.increment_repeat_count()
db.session.commit()
flash(f"Duplicate petition uploaded! Repeat count:
{existing_petition.repeat_count}", "warning")
return redirect(url_for("upload_petition"))

if file_ext == "txt":
file.save(file_path)

category, department = categorize_petition(content)

verified_status = True if is_public else False

try:
new_petition = Petition(
user_id=current_user.id,
lxii
file_name=file.filename,
is_public=is_public,
category=category,
department=department,
verified=verified_status
)
db.session.add(new_petition)
db.session.commit()
except IntegrityError:
db.session.rollback()
flash("Petition already exists or conflict in saving!", "danger")
return redirect(url_for("upload_petition"))

if verified_status:
flash("Petition uploaded and publicly visible!", "success")
else:
flash("Petition uploaded successfully! Pending verification.", "info")

return redirect(url_for("verify"))

return render_template("upload_petition.html")

from flask_mail import Mail, Message


app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = "daminmain@gmail.com"
lxiii
app.config["MAIL_PASSWORD"] = "kpqtxqskedcykwjz"
mail = Mail(app)

def send_email(to, subject, body):


import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = 'daminmain@gmail.com'
msg['To'] = to
msg.set_content(body)

with smtplib.SMTP('smtp.gmail.com', 587) as smtp:


smtp.starttls()
smtp.login('daminmain@gmail.com', 'kpqtxqskedcykwjz')
smtp.send_message(msg)

@app.route('/mark_complete/<int:petition_id>', methods=['POST'])
@login_required
def mark_complete(petition_id):
petition = Petition.query.get_or_404(petition_id)

user = db.session.get(User, petition.user_id)


if user:
try:
send_email(user.email, "Petition Completed",
lxiv
f"Hello {user.name},\n\nYour petition '{petition.file_name}' has been
marked as complete and removed from the system.")
except Exception as e:
print(f"Failed to send email: {e}")

file_path = os.path.join(app.config['UPLOAD_FOLDER'], petition.file_name)


if os.path.exists(file_path):
os.remove(file_path)

db.session.delete(petition)
db.session.commit()

flash("Petition marked as complete and removed.", "success")


return redirect(url_for('show_petitions'))

@app.route("/like_petition", methods=["POST"])
def like_petition():
petition_id = request.args.get("petition_id")
user_id = current_user.id # Make sure the user is logged in

if not petition_id:
return "Petition ID is required", 400

# Check if the user already liked this petition


existing_like = Like.query.filter_by(user_id=user_id,
petition_id=petition_id).first()
if existing_like:
lxv
return "Already liked", 400

# Add new like


like = Like(user_id=user_id, petition_id=petition_id)
db.session.add(like)
db.session.commit()

return redirect(url_for("view_petitions"))

@app.route("/add_comment/<int:petition_id>", methods=["POST"])
def add_comment(petition_id):
if "user_id" not in session:
flash("You need to log in to comment.", "warning")
return redirect(url_for("login"))

comment_text = request.form.get("comment_text")
if not comment_text:
flash("Comment cannot be empty.", "danger")
return redirect(url_for("view_petitions"))

new_comment = Comment(petition_id=petition_id, user_id=session["user_id"],


text=comment_text, user_name=session["user_name"])
db.session.add(new_comment)
db.session.commit()

@app.route("/view_petitions")
lxvi
def show_petitions():
departments = db.session.query(Petition.department).distinct().all()
departments = [dept[0] for dept in departments if dept[0]] # flatten

selected_dept = request.args.get("department")

if selected_dept:
petitions = Petition.query.filter_by(department=selected_dept).all()
else:
petitions = Petition.query.all()

return render_template(
"view_petitions.html",
departments=departments,
petitions=petitions,
selected_dept=selected_dept
)

from flask import Flask, request, render_template, jsonify


import g4f

@app.route('/ch')
def ch():
return render_template('chat.html')

@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json.get('message')
lxvii
try:
# Use g4f.ChatCompletion to get a response
response = g4f.ChatCompletion.create(
model=g4f.models.default, # or g4f.models.gpt_35_turbo
messages=[{"role": "user", "content": user_message}]
)
return jsonify({'reply': response})
except Exception as e:
return jsonify({'reply': f"Error: {str(e)}"})

# Logout
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))

if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)

lxviii
APPENDIX B(SCREENSHOTS):
Categorizations of petition

Public demonstration of a petition to reach all users

lxix
REFERENCES

[1] X. Li, Y. Liu, J. Ni, and Y. He, "Securing E-Petition: A Privacy-Preserving


Fine-Grained Electronic Petition System for Health and Political Petitions," ICC
2022 - IEEE International Conference on Communications, Seoul, Korea,
Republic of, 2022, pp. 3862–3867.

[2] M. Henderson and F. Hogarth, "Online Petitions to Queensland Parliament" in


Encyclopedia of Digital Government, IGI Global, pp. 1282–1286.

[3] Kalbande, P. Prabhu, A. Gharat, and T. Rajabally, "A Fraud Detection System

lxx
Using Machine Learning," 2021 12th International Conference on Computing
Communication and Networking Technologies (ICCCNT), Kharagpur, India, 2021,
pp. 1–7.

[4] Y. Zhang, J. Tong, Z. Wang, and F. Gao, "Customer Transaction Fraud


Detection Using XGBoost Model," 2020 International Conference on Computer
Engineering and Application (ICCEA), pp. 554–558.

[5] Wang, Y. Wang, Z. Ye, L. Yan, W. Cai, and S. Pan, "Credit Card Fraud
Detection Based on Whale Algorithm Optimized BP Neural Network," 2018 13th
International Conference on Computer Science Education (ICCSE), pp. 1–4.

[6] Y. Jain, T. Tiwari, N. Dubey, S. Jain, and Sarika, "A comparative analysis of
various credit card fraud detection techniques," International Journal of Recent
Technology and Engineering, vol. 7, pp. 402–407.

[7] B. Branco, P. Abreu, A. S. Gomes, M. S. C. Almeida, J. T. Ascensão, and P.


Bizarro, "Interleaved Sequence RNNs for Fraud Detection," Proceedings of the 26th
ACM SIGKDD International Conference on Knowledge Discovery Data Mining,
pp. 3101–3109.

[8] C. Ritzer et al., "Characterisation of the PETITION ICU System," 2023 IEEE
Nuclear Science Symposium, Medical Imaging Conference and International
Symposium on Room-Temperature Semiconductor Detectors (NSS MIC RTSD),
Vancouver, BC, Canada, 2023, pp. 1–1.

lxxi
[9] A. Gayen, V. Mehta, M. Sen, U. Chowduray, and A. Jana, "Destiny of Legal
Petition: Accept or Reject? A Machine Learning Approach to Predict the Legal
Petition's Initial Decision," 2024 IEEE Region 10 Symposium (TENSYMP), New
Delhi, India, 2024, pp. 1–6.

[10] M. Singh, "Indian judicial system overview and an approach for automatic
roster preparation and case scheduling for faster case solving (need of: e-courts),"
2018 International Conference on Advances in Computing Communication Control
and Networking (ICACCCN), pp. 128–131.

[11] N. Chawla and B. Kumar, "E-commerce and consumer protection in India: the
emerging trend," Journal of Business Ethics, vol. 180, no. 2, pp. 581–604.

[12] Sohony, R. Pratap, and U. Nambiar, "Ensemble learning for credit card fraud
detection," Proceedings of the ACM India Joint International Conference on Data
Science and Management of Data (CoDS-COMAD '18), pp. 289–294.

[13] Putra, "A modern judicial system in Indonesia: legal breakthrough of e-court
and e-legal proceeding," Jurnal Hukum dan Peradilan, vol. 9, no. 2, pp. 275–297.
CHAPTER 10
CERTIFICATES

lxxii
lxxiii
lxxiv
lxxv

You might also like