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

COMPUTER SCIENCE PROJECT

The document outlines a project titled 'Patient Diagnosis System using Python and MySQL,' aimed at automating disease diagnosis based on symptoms to enhance healthcare accessibility and efficiency. It details the project's objectives, the importance of Python and MySQL in its implementation, and compares the existing manual systems with the proposed automated solution. Additionally, it includes system requirements, similar software solutions, and a snippet of the source code used in the project.

Uploaded by

9cakshatkunwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

COMPUTER SCIENCE PROJECT

The document outlines a project titled 'Patient Diagnosis System using Python and MySQL,' aimed at automating disease diagnosis based on symptoms to enhance healthcare accessibility and efficiency. It details the project's objectives, the importance of Python and MySQL in its implementation, and compares the existing manual systems with the proposed automated solution. Additionally, it includes system requirements, similar software solutions, and a snippet of the source code used in the project.

Uploaded by

9cakshatkunwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

COMPUTER SCIENCE PROJECT

PROJECT TITLE: PATIENT DIAGNOSIS SYSTEM USING PYTHON AND


MYSQL

By : AKSHAT AND FARHAN


❖ ACKNOWLEDGMENT
❖ I would like to express my sincere gratitude to
my Computer Science teacher, ABHAY SIR, for
their valuable guidance and support
throughout this project.

I also extend my thanks to my school for


providing the necessary resources and learning
environment to work on this project.

Lastly, I appreciate the assistance from online


resources and forums that helped in
understanding Python, MySQL, and database
management.
❖ INTRODUCTION

The project titled "Patient Diagnosis System


using Python and MySQL" is an innovative
solution designed to assist healthcare
providers and individuals in diagnosing
diseases based on symptoms. This advanced
system leverages the power of Python for
robust processing and MySQL for efficient
database management, creating a seamless
experience for users.
One of the primary goals of this project is to
automate the initial stages of diagnosis,
reducing the burden on healthcare
professionals and providing users with
quick access to potential diagnoses. By
generating detailed reports, the system not
only aids in the diagnostic process but also
enhances the accessibility of healthcare
data. This empowers users to make informed
decisions about their health and seek
appropriate medical attention promptly.
Furthermore, the "Patient Diagnosis System"
is designed to be scalable and adaptable,
allowing for continuous improvements and
updates. This ensures that the system
remains relevant and effective in addressing
the ever-evolving needs of the healthcare
industry.
In summary, this project aims to
revolutionize the diagnostic process by
combining the strengths of Python and
MySQL, ultimately contributing to more
efficient and accessible healthcare for all.
❖ Objective of the Project
The primary objectives of this project
are:
• To develop an automated system for
• diagnosing diseases based on
symptoms.
• To store and manage patient records
efficiently using MySQL.
• To minimize human errors in manual
diagnosis.
• To provide a user-friendly interface
for doctors and patients.
• To lay a foundation for future
enhancements like AI-based
diagnosis.
❖ PYTHON: OVERVIEW
AND IMPORTANCE
Python is a high-level, interpreted
programming language known for its
simplicity and readability. It supports
multiple programming paradigms,
including procedural, object-oriented,
and functional programming.
❖ History of Python
Python was developed by Guido van
Rossum and first released in 1991. Initially
conceived as a successor to the ABC
language, Python was designed with a
strong emphasis on code readability and
simplicity. Over the years, it has evolved
through the contributions of a vibrant and
growing community, becoming one of the
most widely used programming languages
in the world. Python's success can be
attributed to its extensive standard library,
cross-platform capabilities, and a
commitment to open-source principles, which
have fostered continuous improvement and
adaptation to emerging technologies.
Python's growth has been fueled by its
strong and active community, which has
contributed to its extensive standard library
and the development of numerous third-
party modules. The language's adaptability
has made it a favorite among developers in
various fields, from web development and
data science to machine learning and
scientific computing.
Today, Python stands as one of the most
popular and influential programming
languages in the world, continuously
evolving to meet the demands of modern
technology and innovation.
Uses of Python
Python's versatility is demonstrated through
its extensive range of applications across
various domains:
• Web Development: Python's powerful
frameworks like Django and Flask
facilitate rapid development of robust and
scalable web applications. These
frameworks offer a rich set of tools and
libraries that simplify common web
development tasks.
• Data Science and Machine Learning: Python
is a preferred language for data scientists
and machine learning practitioners due to
libraries like Pandas, NumPy, Scikit-learn,
TensorFlow, and PyTorch. These libraries
provide comprehensive tools for data
manipulation, analysis, visualization, and
the implementation of machine learning
algorithms.
• Scripting and Automation: Python excels at
scripting and automation, enabling the
automation of repetitive tasks, system
administration, and the creation of scripts
that enhance productivity and efficiency.
• Game Development: Python's Pygame
library allows developers to create simple
2D games. Its ease of use and readability
make it an excellent choice for beginners
and hobbyists interested in game
development.
• Cybersecurity: Python is widely used in
cybersecurity for tasks such as penetration
testing, network scanning, and the
development of security tools. Its
flexibility and extensive library support
make it a valuable asset in the security
professional's toolkit.
• Internet of Things (IoT): Python's
lightweight nature and ease of integration
with hardware make it ideal for IoT
projects. Libraries like MicroPython and
CircuitPython enable developers to program
microcontrollers and other IoT devices
efficiently.
• Scientific Computing: Python is extensively
used in scientific research and academia for
tasks like simulation, modeling, and
complex numerical computations. Libraries
such as SciPy, Matplotlib, and SymPy
provide the necessary tools for scientific
applications.
In conclusion, Python's simplicity, extensive
library support, and adaptability have cemented
its importance in the programming world.
❖ MySQL: Overview and
Importance
MySQL is a powerful, open-source
relational database management system
(RDBMS) that has become an integral part
of the data management landscape.
Developed to handle large volumes of data
efficiently, it utilizes Structured Query
Language (SQL) for accessing, managing,
and manipulating databases. MySQL is
renowned for its speed, reliability,
scalability, and ease of use, which has led
to its widespread adoption among
developers and organizations worldwide.
One of the key strengths of MySQL is its
open-source nature, allowing for flexibility
and customization to meet specific needs. It
offers robust transactional support,
ensuring data integrity and providing
features like multi-version concurrency
control (MVCC). MySQL is compatible with
all major operating systems, including
Windows, Linux, and macOS, and integrates
seamlessly with various programming
languages such as Python, PHP, Java, and
C++.
❖ History of MySQL
MySQL was initially released in 1995 by
Swedish developers Michael "Monty" Widenius,
David Axmark, and Allan Larsson. The name
"MySQL" combines "My," the name of Monty's
daughter, with "SQL," the abbreviation for
Structured Query Language. The goal was to
develop a fast, reliable, and easy-to-use
RDBMS that would be superior to existing
solutions.

In 2008, Sun Microsystems acquired MySQL


AB, the company behind MySQL, for $1 billion,
recognizing its potential and popularity. Later,
in 2010, Oracle Corporation acquired Sun
Microsystems, bringing MySQL under Oracle's
umbrella. Despite concerns about its future,
MySQL has continued to thrive, with Oracle
supporting its development alongside the
community-driven fork, MariaDB, initiated by
Monty Widenius to ensure a free and open-
source alternative.

Over the years, MySQL has evolved


significantly, introducing features like stored
procedures, triggers, views, and robust
replication capabilities. Its continuous
development has kept it relevant in the face of
emerging technologies and growing data
demands.

Uses of MySQL

MySQL's versatility makes it suitable for a wide


range of applications across various industries:
• Web Applications and Content
Management Systems (CMS):

o MySQL powers some of the most


popular websites and CMS platforms,
including WordPress, Joomla, and
Drupal.

o It efficiently handles user data, content


storage, and dynamic page generation.

o Supports high-traffic websites by


enabling quick read/write operations
and scalable backend infrastructure.

• Data Warehousing:

o Utilized for storing and managing large


datasets for analytics and business
intelligence.
o MySQL's partitioning, indexing, and
replication features facilitate efficient
data retrieval and reporting.

o Helps organizations make informed


decisions based on historical and real-
time data analysis.

• E-Commerce Applications:

o Forms the backbone of many e-commerce


platforms like Magento and
PrestaShop.

o Manages product catalogs, customer


information, order processing, and
inventory management.

o Ensures secure transactions through


support for ACID (Atomicity,
Consistency, Isolation, Durability)
compliance.
• Banking and Finance:

o Used for secure and reliable handling


of financial transactions and customer
data.

o Supports complex queries and


transaction processing essential for
banking operations.

o Offers robust security features to protect


sensitive financial information.

• Health Management Systems:

o Supports Electronic Health Records


(EHR) systems by storing patient data,
medical records, and appointment
scheduling.

o Enables secure sharing of information


among authorized healthcare providers.
o Assists in data analysis for patient care
improvement and medical research.

• Education Sector:

o Manages student information systems,


including enrollment, grading, and
course management.

o Facilitates e-learning platforms by


handling user data and course content
delivery.

o Supports library management systems


for cataloging and resource tracking.

• Social Media and Networking Platforms:

o Used by social networks to handle


large volumes of user-generated content
and interactions.
o Manages real-time data processing for
messaging, notifications, and activity
feeds.

o Scales horizontally to accommodate


growing user bases and data storage
requirements.

• Telecommunications:

o Assists in managing customer relations,


billing systems, and network data.

o Supports operational support systems


(OSS) and business support systems
(BSS).

o Handles large-scale data management


for call detail records and subscriber
information.
❖ System Requirements
❖ Hardware
Requirements:
1. Processor: Intel Core i3 or higher

o A multi-core processor is recommended


to handle multiple tasks smoothly and
improve performance.

2. RAM: 4GB or more

o Adequate RAM ensures efficient


processing of data and prevents
slowdowns during operation.

3. Storage: At least 500MB of free space

o Additional space may be required for


storing databases, reports, and log files
generated by the system.
4. Operating System: Windows, macOS, or
Linux

o Compatible with all major operating


systems to provide flexibility and ease
of deployment.

Software Requirements:

1. Python 3.x

o The latest version of Python 3 is


preferred to utilize updated features
and security improvements.

2. MySQL Database Server

o Essential for managing and storing


patient data reliably with robust
database capabilities.

3. MySQL Connector for Python


o Allows seamless communication
between the Python application and the
MySQL database.

4. Colorama (for colored terminal output)

o Enhances the user interface by enabling


colored text in the terminal for better
readability.

5. Any Text Editor or IDE (PyCharm, VS Code,


etc.)

o An Integrated Development
Environment facilitates easier coding,
debugging, and project management.
Existing vs. Proposed System Existing System:
Manual record-keeping with a high chance of
human errors. Difficult to retrieve patient data
efficiently. No automated symptom analysis or
disease prediction. Proposed System: Uses a
structured MySQL database for efficient data
storage and retrieval. Automates symptom-
based disease diagnosis. Generates reports for
patient history and recommended precautions.
extend it like above

Sure, here's an extended version of your


comparison between the existing system and the
proposed system:
❖ Existing vs. Proposed
System
❖ Existing System:
1. Manual Record-Keeping with a High
Chance of Human Errors

o In many healthcare facilities, patient


records are maintained manually using
paper files or basic digital documents.
This manual process is susceptible to
errors such as illegible handwriting,
misplaced files, and transcription
mistakes. These errors can lead to
incorrect diagnoses, inappropriate
treatments, and can compromise patient
safety due to the lack of accurate
information.

2. Difficult to Retrieve Patient Data Efficiently


o Accessing patient information in a
manual system can be time-consuming
and inefficient. Healthcare
professionals may spend significant
amounts of time searching through
physical files or unstructured digital
folders. This delay hinders timely
medical decisions and affects the
overall quality of care provided to
patients.

3. No Automated Symptom Analysis or


Disease Prediction

o The absence of automated tools means


that symptom analysis relies entirely
on the healthcare provider's personal
experience and knowledge. This can
result in inconsistent diagnoses and
overlooks potential diseases, especially
in complex cases where symptoms are
ambiguous or overlap with multiple
conditions.

1. Proposed System:
1. Uses a Structured MySQL Database for
Efficient Data Storage and Retrieval

o The implementation of a structured


MySQL database allows for organized
and centralized storage of patient data.
This system ensures quick and efficient
retrieval of information, enabling
healthcare professionals to access
patient records with ease. The database
supports indexing and querying
capabilities, which significantly reduce
the time spent on data management and
enhance the overall efficiency of
healthcare services.
2. Automates Symptom-Based Disease
Diagnosis

o The system incorporates intelligent


algorithms that analyze inputted
symptoms to predict possible diseases.
This automation aids in identifying
potential health issues quickly,
providing a preliminary diagnosis that
can be further examined by medical
professionals. It enhances diagnostic
accuracy by leveraging a comprehensive
database of symptom-disease
correlations.

3. Generates Reports for Patient History and


Recommended Precautions

o Upon analyzing patient data and


diagnostic results, the system can
generate detailed reports that include
medical history, current diagnoses,
treatment plans, and precautionary
measures. These reports facilitate better
communication between healthcare
providers and patients, ensuring that all
parties have a clear understanding of
the patient's health status and
recommended actions. It also aids in
monitoring patient progress over time
and adjusting treatments as necessary.
Similar Software

Some existing software solutions that offer


similar healthcare automation include:

• MocDoc – A cloud-based hospital


management system.

• Suvarna Technosoft – An integrated


healthcare software.

• itDose – A medical information


management platform.
SOURCE CODE
import mysql.connector
from datetime import datetime
from colorama import Fore,
Style, init
import os

# Initialize colorama for


colored output
init()

# Connect to MySQL
try:
conn =
mysql.connector.connect(
host="localhost",
user="root",
password="9C@akshat"
)
cursor = conn.cursor()
print(Fore.GREEN + "
Connected to the database
successfully!" +
Style.RESET_ALL)
except mysql.connector.Error as
err:
print(Fore.RED + f"
Error: {err}" + Style.RESET_ALL)
exit()

# Use database
cursor.execute("CREATE DATABASE
IF NOT EXISTS diagnosis_db")
cursor.execute("USE
diagnosis_db")

# Create tables
cursor.execute("DROP TABLE IF
EXISTS symptoms") # Prevent
duplicate symptoms
cursor.execute("""
CREATE TABLE symptoms (
id INT PRIMARY KEY
AUTO_INCREMENT,
name VARCHAR(50),
category VARCHAR(50)
)
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS
patients (
name VARCHAR(50) NOT
NULL,
age INT,
gender CHAR(1),
phone CHAR(10) PRIMARY
KEY,
dob DATE
)
""")

# Insert Expanded Symptoms


Data
cursor.execute("""
INSERT IGNORE INTO symptoms
(id, name, category) VALUES
(1, 'Fever', 'Respiratory'),
(2, 'Cough', 'Respiratory'),
(3, 'Sore Throat',
'Respiratory'),
(4, 'Shortness of Breath',
'Respiratory'),
(5, 'Sneezing',
'Respiratory'),
(6, 'Runny Nose',
'Respiratory'),
(7, 'Headache',
'Neurological'),
(8, 'Fatigue',
'Neurological'),
(9, 'Dizziness',
'Neurological'),
(10, 'Memory Loss',
'Neurological'),
(11, 'Blurred Vision',
'Neurological'),
(12, 'Nausea', 'Digestive'),
(13, 'Body Ache',
'Digestive'),
(14, 'Stomach Pain',
'Digestive'),
(15, 'Vomiting',
'Digestive'),
(16, 'Loss of Appetite',
'Digestive')
""")

conn.commit()

# Register a patient
def register_patient():
print(Fore.BLUE + "===
Register Patient ===" +
Style.RESET_ALL)
name = input("Enter
patient's name: ")
age = input("Enter age: ")
gender = input("Enter gender
(M/F): ").upper()
phone = input("Enter phone
number (10 digits): ")
dob = input("Enter date of
birth (YYYY-MM-DD): ")

cursor.execute(
"INSERT INTO patients
(name, age, gender, phone, dob)
VALUES (%s, %s, %s, %s, %s)",
(name, age, gender,
phone, dob)
)
conn.commit()
print(Fore.GREEN + "
Patient registered
successfully!" +
Style.RESET_ALL)

# Ask additional health


questions
def ask_health_questions():
print(Fore.BLUE + "\n===
Health Questions ===" +
Style.RESET_ALL)
time_period = input("How
long have you had these
symptoms? (e.g., 2 days, 1
week): ")
hunger = input("Have you
felt a loss of appetite? (Y/N):
").upper()
body_temp =
float(input("Enter your body
temperature (°C): "))
hydration = input("Are you
drinking enough water? (Y/N):
").upper()
travel = input("Have you
traveled recently? (Y/N):
").upper()

return {
"time_period":
time_period,
"hunger": hunger,
"body_temp": body_temp,
"hydration": hydration,
"travel": travel
}

# Select symptoms
def select_symptoms():
print(Fore.BLUE + "\n===
Select Symptoms ===" +
Style.RESET_ALL)
cursor.execute("SELECT
DISTINCT category FROM
symptoms")
categories =
cursor.fetchall()
selected = []
for category in categories:
print(Fore.CYAN +
f"\n{category[0]} Symptoms:" +
Style.RESET_ALL)
cursor.execute("SELECT
id, name FROM symptoms WHERE
category = %s", (category[0],))
symptoms =
cursor.fetchall()
for symptom in symptoms:
print(f"{symptom[0]}
. {symptom[1]}")
selected.extend(input("E
nter symptom IDs (comma-
separated, or leave blank to
skip): ").split(','))
return [symptom.strip() for
symptom in selected if
symptom.strip().isdigit()]

# Diagnose patient based on


symptoms and health factors
def diagnose(symptoms,
patient_name, phone,
health_data):
print(Fore.BLUE + "\n===
Diagnosis ===" +
Style.RESET_ALL)

cursor.execute("SELECT *
FROM diseases")
diagnoses = []
for disease in
cursor.fetchall():
disease_symptoms =
set(disease[2].split(','))
match =
(len(set(symptoms) &
disease_symptoms) /
len(disease_symptoms)) * 100 if
disease_symptoms else 0

# **Modify match
probability based on health
data**
if "week" in
health_data["time_period"]:
match += 10 #
Increase probability for long-
term conditions
if
health_data["body_temp"] > 38.3:
match += 15 #
Increase chances for Flu, COVID-
19

if health_data["hunger"]
== "Y":
match += 10 #
Increase probability of
digestive issues

if health_data["travel"]
== "Y":
match += 10 #
Increase probability of
infections
diagnoses.append({'name'
: disease[1], 'prevention':
disease[3], 'doctor':
disease[4], 'match':
round(match, 2)})

return diagnoses

# Generate and save report,


then ask if user wants to open
it
def
generate_report(patient_name,
phone, diagnosis, health_data):
filename =
f"{patient_name}_Report.txt"
with open(filename, "w") as
file:
file.write(f"Patient
Name: {patient_name}\nPhone:
{phone}\n")
for key, value in
health_data.items():
file.write(f"{key.re
place('_', ' ').title()}:
{value}\n")
file.write("\nDiagnosis:
\n")
for d in diagnosis:
file.write(f" -
{d['name']} ({d['match']}%
match)\n Prevention:
{d['prevention']}\n Doctor:
{d['doctor']}\n\n")
print(Fore.GREEN + f"
Report saved as {filename}" +
Style.RESET_ALL)

# **ASK USER IF THEY WANT TO


OPEN THE REPORT**
open_report = input("\nDo
you want to open the report?
(Y/N): ").strip().upper()
if open_report == "Y":
print("\n Opening
report...")
os.system(f"notepad
{filename}") # Windows
# os.system(f"open
{filename}") # macOS
# Main menu
def main_menu():
while True:
print("\n1. Register
Patient\n2. Diagnose Patient\n3.
Exit")
choice = input("Enter
your choice: ")

if choice == '1':
register_patient()
elif choice == '2':
patient_name =
input("Enter patient's name: ")
phone = input("Enter
patient's phone number: ")
symptoms =
select_symptoms()
health_data =
ask_health_questions()
diagnosed_diseases =
diagnose(symptoms, patient_name,
phone, health_data)
if
diagnosed_diseases:
generate_report(
patient_name, phone,
diagnosed_diseases, health_data)
elif choice == '3':
break

# Run the program


if __name__ == "__main__":
main_menu()
conn.close()
❖ OUTPUT
FLOW CHART’S
SYSTEM OVERVIEW
❖ PATIENT REGISTRATION
DIAGNOSIS PROCESS
REPORT GENERATION
Potential Advancements
and Applications
As technology continues to
evolve, this diagnostic
system can be enhanced with
several advanced features
to improve its accuracy,
efficiency, and usability.
Some key areas for
improvement include:
1. Integration with AI and
Machine Learning
o Implementing AI-driven
predictive analysis to
improve diagnostic
accuracy based on
patient history.
oUsing machine learning
models to suggest
possible diseases based
on symptoms and health
data patterns.
2. Cloud-Based Data
Storage
Shifting the database
o

to cloud services to
allow seamless access
to patient records from
multiple locations.
oEnsuring data security
and compliance with
healthcare regulations.
3. IoT and Wearable Device
Support
Integrating real-time
o

health monitoring from


smartwatches or medical
devices.
oAutomatically
collecting vital signs
like heart rate, oxygen
levels, and temperature
for better diagnosis.
4. Mobile Application and
Web Interface
oDeveloping a mobile or
web-based version for
easy access by patients
and doctors.
o Enabling remote
diagnosis and
telemedicine support.
5. Improved User Interface
& Report Generation
Creating a more
o

interactive and user-


friendly GUI instead of
command-line inputs.
o Enhancing the reporting
system with graphical
analysis and historical
comparisons.
6. Multilingual and Voice-
Based Support
oAdding multilingual
support to make it
accessible to a wider
audience.
oImplementing voice-
based input for elderly
and visually impaired
users.
By incorporating these
enhancements, the system
can transform into a
comprehensive smart
healthcare assistant,
providing quick, accurate,
and remote diagnostic
solutions for users

worldwide .
Conclusion
The Patient Diagnosis System using Python and
MySQL successfully demonstrates how
technology can assist in medical diagnosis by
automating symptom analysis. The system helps
in reducing manual efforts, improving accuracy,
and maintaining a structured patient database.
This project serves as a foundational step toward
integrating AI and machine learning in future
healthcare applications.
The proposed advancements such as cloud
storage, wearable device integration, and voice-
based support could make the system even more
powerful and accessible. As healthcare technology
evolves, such systems will play a vital role in
making medical diagnosis more efficient and
patient-friendly.
Limitations
Despite its advantages, the project has certain
limitations:
• The accuracy of diagnosis depends on
predefined symptom-disease mapping.
• The system does not yet integrate real-time
AI-based learning.
• No graphical user interface (GUI) is currently
implemented, making it command-line
dependent.
• Requires internet connectivity for cloud-based
enhancements.
Bibliography / References
The following resources were referred to while
developing this project:
• Python Official Documentation:
https://docs.python.org/
• MySQL Official Documentation:
https://dev.mysql.com/doc/
• Online programming communities and forums
(Stack Overflow, GeeksforGeeks, W3Schools)
• Books and resources on Database
Management Systems (DBMS) and Python
programme

You might also like