Petition Doc 29
Petition Doc 29
Submitted by
HEMAVATHI G (8115U21CS047)
KEERTHANA K (8115U21CS059)
KHAVIYA K (8115U21CS062)
SIGNATURE SIGNATURE
Dr. T.M. NITHYA, M.E., Ph.D., Dr. L. AMUDHA, M.E., Ph.D.,
(Autonomous) (Autonomous)
Samayapuram, Samayapuram,
ii
DECLARATION
DONA VERGINIYA N
(8115U21CS036)
iii
DECLARATION
HEMAVATHI G
(8115U21CS047)
iv
DECLARATION
KEERTHANA K
(8115U21CS059)
Assistant Professor/CSE
v
DECLARATION
KHAVIYA K
(8115U21CS062)
vi
TABLE OF CONTENTS
REFERENCES 86
ABSTRACT
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
LIST OF ABBREVITIONS
ABBREVITIONS FULL FORM
AI ARTIFICIAL INTELLIGENCE
UI USER INTERFACE
ML MACHINE LEARNING
x
API APPLICATION PROGRAMMING
INTERFACE
DB DATABASE
CHAPTER 1
INTRODUCTION
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
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
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.
ivic Engagement
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
xx
CHAPTER 2
LITERATURE SURVEY
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.
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.
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 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
CHAPTER 3
SYSTEM ANALYSIS
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.
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.
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
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+
xxxiii
FLASK
spaCy
SQLALCHEMY
These are used for form validations and secure data input from users.
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
INDENTATION
Python relies on indentation for defining blocks of code rather than curly
braces. This ensures readability and enforces clean code structure.
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
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.
xxxviii
Figure 5.2.1 Usecase Diagram
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.
xli
5.4 SEQUENCE DIAGRAM
xliii
Figure 5.4.1 Sequence Diagram
xlv
Figure 5.5.1 Activity Diagram
xlvi
CHAPTER 6
SYSTEM TESTING
Testing Steps:
Unit Testing
Usability Testing
Integration Testing
Regression 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
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"
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'))
# 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)
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")
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())
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"))
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)
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")
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = 'daminmain@gmail.com'
msg['To'] = to
msg.set_content(body)
@app.route('/mark_complete/<int:petition_id>', methods=['POST'])
@login_required
def mark_complete(petition_id):
petition = Petition.query.get_or_404(petition_id)
db.session.delete(petition)
db.session.commit()
@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
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"))
@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
)
@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
lxix
REFERENCES
[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.
[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.
[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