0% found this document useful (0 votes)
2K views44 pages

Healthcare - Chatbot Report

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)
2K views44 pages

Healthcare - Chatbot Report

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/ 44

HEALTHCARE - CHATBOT

A MINI PROJECT-II REPORT


(Phase-I)

Submitted by
CHANDRU (2013014)

KAVIN PRASANTH (2013049)

JEYPRASATH (2013043)

in partial fulfillment for the award of the degree

of

BACHELOR OF ENGINEERING
IN
COMPUTER SCIENCE
K.S.R COLLEGE OF ENGINEERING, TIRUCHENGODE-637215
(Autonomous)

ANNA UNIVERSITY: CHENNAI 600 025

JUNE 2021

Page 1 of 44
BONAFIDE CERTIFICATE

Certified that this project report “HEALTHCARE - CHATBOT” is the bonafide

work of “ CHANDRU (2013014), KAVIN PRASANTH (2013049), JEY

PRASATH (2013043)” who carried out the project work under my supervision.

SIGNATURE SIGNATURE

Dr.A.Rajiv Kannan M.E.,Phd., Mr.O.K Gowrishankar


HEAD OF THE DEPARTMENT SUPERVISOR
Professor Associate Professor
Department of Computer science and Department of Computer Science and
Engineering Engineering
K.S.R College of Engineering K.S.R College of Engineering
Tiruchengode - 637215 Tiruchengode – 637215

Submitted for Mini Project-II viva voce examination held


on .....................................

INTERNAL EXAMINER EXTERNAL EXAMINER

Page 2 of 44
ACKNOWLEDGEMENT

First and foremost, we thank to power of almighty for showing us inner peace and
for all blessings. Special gratitude to our parents, for showing their support and
love always.

We express our sincere thanks to Chairman Lion Dr . K . S . RANGASAMY,


MJF, and Principal Dr. P . Senthil Kumar for providing adequate facilities to
complete the project.

We are immensely grateful to Head of Computer Science and engineering, Dr. A .


Rajiv Kannan for the continues encouragement to complete the project.

We express our heartfelt thanks to our project supervisor Mr. O. K .


Gowrishankar for his valuable guidance and fruitful discussions throughout the
course of the project work.

We feel proud in sharing this success with all our staff members and friends who
helped directly or indirectly in completing this project successfully.

Page 3 of 44
ABSTRACT
ChatBot can be described as software that can chat with people using
artificial intelligence. These software are used to perform tasks such as
quickly responding to users, informing them, helping to purchase products
and providing better service to customers. In this paper, we present the
general working principle and the basic concepts of artificial intelligence
based chatbots and related concepts as well as their applications in various
sectors such as telecommunication, banking, health, customer call centre and
e-commerce.The proposed idea is to make a medical chatbot using Artificial
Intelligence which will diagnose the disease and supply basic details about
the disease before consulting a doctor. To reduce the healthcare costs and
improve accessibility to medical knowledge the medical chatbot is made.
Certain chatbots acts as a medical reference books, which helps the patient
know more about their disease and helps to enhance their health. The user
can achieve the real advantage of a chatbot only if it can diagnose all quite
disease and supply necessary information. A text-to-text diagnosis bot
engages patients in conversation about their medical issues and provides a
personalized diagnosis supported their symptoms. Hence, people will have a
thought about their health and have the correct protection.

Page 4 of 44
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.

ABSTRACT 4

LIST OF FIGURES 7

LIST OF SYMBOLS & ABBREVIATIONS 8

1. INTRODUCTION 9

1.1 ABOUT PROJECT 9

1.2 PROJECT DESCRIPTION 13

1.3 SCOPE FOR FUTURE DEVELOPMENT 13

2. LITERATURE SURVEY 15

2.1 A REVIEW ON CHAT INTERFACE 15

2.2 A REVIEW ON WORD SEGMENTATION 16

3. HARDWARE AND SOFTWARE 17

REQUIREMENTS

3.1 PYTHON 18

3.2 VS CODE 18

3.3 PIP 18

3.4 DATASETS 19

4. PROJECT DESCRIPTION 20

Page 5 of 44
4.1 SCOPE OF THE PROJECT 20

4.2 SYSTEM ARCHITECTURE 21

4.3 APPLICATION FEATURES 23

4.3.1 INTERACTION 23

4.3.2 TASK EXECUTION 23

4.3.3 TERMINATION 23

5 RESULTS 24

5.1 USER INTERFACE 24

6. CONCLUSION AND FUTURE 29

ENHANCEMENTS

6.1 FUTURE ENHANCEMENTS 29

6.2 CONCLUSION 30

APPENDICES 31

APPENDIX 1 SAMPLE SCRIPT 31

REFERENCES 44

Page 6 of 44
LIST OF FIGURES

FIGURE NO. TITLE PAGE NO.

1.1 Block Diagram of Chat bot 15

4.1 Flowchart 20

4.2 Data Flow Diagram 21

5.1 User Interaction 25

5.2 Series of Questioning 26

5.3 Symptom Analysis 27

5.4 Disease Diagnose 28

5.5 Symptom Precaution 29

Page 7 of 44
LIST OF ABBREVIATIONS

ABBREVIATIONS:

AI - Artificial Intelligence

API - Application Programming Interface

CSV - Comma Separated Value

GUI - Graphical User Interface

NumPy - Numerical Python

NLP - Natural Language Processing

OS - Operating System

PIP - Performance Improvement Plan

Pyttsx3 - python text-to-speech x 3

SciPy - Scientific Python

Page 8 of 44
CHAPTER 1
INTRODUCTION
1.1 ABOUT THE PROJECT:

The title of our project is “HEALTH CARE – CHATBOT”. The proposed


idea is to make a medical chatbot using Artificial Intelligence which will diagnose
the disease and supply basic details about the disease before consulting a doctor.
To reduce the healthcare costs and improve accessibility to medical knowledge the
medical chatbot is made. Certain chatbots acts as a medical reference books, which
helps the patient know more about their disease and helps to enhance their health.
The user can achieve the real advantage of a chatbot only if it can diagnose all
quite disease and supply necessary information. A text-to-text diagnosis bot
engages patients in conversation about their medical issues and provides a
personalized diagnosis supported their symptoms. Hence, people will have a
thought about their health and have the correct protection.

The modules which are used in the project.

 Numpy
 Pandas
 Scikit-learn
 Pyttsx3
 CSV
 ChatterBot
 TKinter

Numpy:

NumPy is a Python library used for working with arrays. It also has
functions for working in domain of linear algebra, fourier transform and matrices.
In Python we have lists that serve the purpose of arrays, but they are slow to

Page 9 of 44
process. NumPy aims to provide an array object that is up to 50x faster than
tradition Python lists.

NumPy stands for Numerical Python.

Installation:

Pip install numpy

Command:

Import numpy as np

Pandas:

Pandas is a software library written for the Python programming language


for data manipulation and analysis. In particular, it offers for data structures and
operations. Pandas is mainly used for data analysis. Pandas allows importing data
from various file formats such as csv, JSON, SQL, Ms Excel.

Installation:

Pip install pandas

Command:

Import pandas as pd

Scikit-learn:

Simple and efficient tools for predictive data analysis. Accessible to


everybody, and reusable in various contexts. Built on NumPy, SciPy, and
matplotlib. Open source and commercially usable.

 Classification
 Regression
 Clustering
 Dimensionality reduction
 Model selection
 Preprocessing
Page 10 of 44
Installation:

Pip install scikit-learn

Command:

Import scikit-learn

Pyttsx3:

pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative


libraries, it works offline, and is compatible with both Python 2 and 3. Supports
multiple TTS engines, including Sapi5, nsss and espeak.

Installation

Pip install pyttsx3

Command:

Import pyttsx3

CSV:

A CSV (Comma Separated Values) format is one of the most simple and
common ways to store tabular data. To represent a CSV file, it must be saved with
the .csv file extension.

While we could use the built-in function to work with CSV files in Python,
there is a dedicated csv module that makes working with CSV files much easier.

Command:

Import csv

ChatterBot:

ChatterBot is a Python library that makes it easy to generate automated


responses to a user’s input. ChatterBot uses a selection of machine learning

Page 11 of 44
algorithms to produce different types of responses. This makes it easy for
developers to create chat bots and automate conversations with users.

Installation:

Pip install chatterbot==1.0.2

Command:

Import chatterbot

Chatterbot-corpus:

A machine readable multilingual dialog corpus. These modules are used to


quickly train chatterbot to respond to various inputs in different languages.
Although much of chatterbot is designed to be language independent.

TKinter:

Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a
powerful object-oriented interface to the TK GUI toolkit.

Installation:

Pip install tkinter

Command:

Import tkinter

Page 12 of 44
1.2 PROBLEM DESCRIPTION:
Healthcare chatbot is designed to chat or respond to the user regarding any
health issues. Chatbot can be programmed using different object-oriented language
like python java etc. This health care chatbot is programmed using python
language with various modules installed. There are many challenges faced to
create chatbot.

There are some problems defined:

 Users way of texting


 User language
 Limitations of NLP
 Randomness of being a human
 Need for more
 Limited attention span
 Recognising user intents is what is needed

1.3 SCOPE FOR FUTURE DEVELOPMENT:


There are 61% of the consumers prefer to communicate with chatbots
for effective, and quick interaction with brands. This indicates how popular
chatbots are. What’s more, their popularity is likely to increase.
Nowadays chatbots are becoming so trendy, it’s used in almost every
places and websites. There are some of real time examples of chatbot.
 Customer service
 Booking tickets

Page 13 of 44
 Demo and Show requested products
 Ordering and Tracking products
 Answer FAQs in real time
 Improve user experience with personalizes recommendations

BLOCK DIAGRAM:

User Message

Intent Entity
Classification Recognition

Intent Entities

Context Candidate Response


Responses
Generator

Candidate Response

Response Selector

Response
Page 14 of 44
Figure 1.1 Block diagram

CHAPTER 2

LITERATURE SURVEY

This unit is the front end of the system. It is responsible for collecting the
user queries from the user which are the input to the system. It is also responsible
for displaying the system generated results to the user. Therefore, it can be said
that the chat interface is the face of the system through which the entire
communication takes place. It is the mediator of conversation between the system
and the user. The query that user fires on the chat interface is passed on to the
chatting backend which acts as a message delivering system between the Chat
interface and the Machine Learning Layer. This interface can be accessed either as
a website or as a smart phone app. The type of interface depends on the
requirements of the user that are to be satisfied by the system. If the system is
accessed from a smartphone, the interface will be in the form of an app and if the
system is accessed from a website, then the interface will be in the form of a
website. For building apps on the smartphone, it will require to use android for
android phones or Swift for iOS. In this case, only the interfacing platform will be
programmed on android and the complete backend processing of the system will
take place on a server on which the system will be deployed. For making a website,
either Java or Python web frameworks can be used. Java provides Spring and
Struts as the most advanced and latest web frameworks. Similarly, Python allows
usage of Django and Flask frameworks for building of a website. The criteria for
selection of the programming language depends upon the functionalities that the
system intents to provide, the requirements of the users that will use the system,
the algorithms that are to be used by the system, etc. Selection of an appropriate
programming language makes it simpler for developers to develop a system which

Page 15 of 44
provides maximum functionality to the user with high accuracy and minimum
complexity.

Segmentation, also referred to as tokenization is the process of splitting text


into smaller and meaningful units. These units could be paragraphs, sentences,
clauses, phrases, words or letters. The smallest unit are the letters. Word
segmentation is the splitting of sentences into individual words separated by blank
spaces. The tokenized units of the sentences are called as tokens. The tokenizers
split the sentences into words and punctuations marks as independent units. The
most commonly used tokenizer is of space type, i.e. it splits the sentences into
words at the blank spaces. It is also required that the tokenizer should consider
abbreviations, acronyms, dates, numbers in decimal formats, etc., which cannot
split at punctuations and blank spaces, as they will lose their meaning if done so.

Page 16 of 44
CHAPTER 3

HARDWARE AND SOFTWARE REQUIREMENTS

This chapter provides of brief information about the requirements of Hardware and
software.

HARDWARE REQUIREMENT:

OPERATING SYSTEM : WINDOWS 10

HARD DISK : 1 TB

RAM : 4 GB

SOFTWARE REQUIREMENT:

LANGUAGE : PYTHON

EDITOR : VISUAL STUDIO CODE

APPLICATION : CHROME

OS : WINDOWS 10

PACKAGE INSTALLER: PIP

Page 17 of 44
3.1 PYTHON:

Python is more popular language over C++ for AI and leads with 57% vote
among developers. That is because Python is easy to learn and implement. With its
many libraries, they can also be used for data analysis.

Python is a dynamic language and reduces complexity when it comes to


collaborating meaning you can implement functionality with less code. Unlike C+
+, where all significant compilers tend to do specific optimization and can be
platform specific, Python code can be run on pretty much any platform without
wasting time on specific configurations.

3.2 VS CODE:

Visual Studio Code is free source-code editor made by Microsoft for


Windows, Linux and macOS. Features include support for debugging, syntax
highlighting, intelligent code completion, snippets, code refactoring and embedded
Git.

Users can change the theme, keyboard shortcuts, preferences, and install
extensions that add additional functionality.

3.3 PIP:

Pip is the package installer for Python. You can use pip to install packages
from the python package index and other indexes. Pip is one of the best tools to
Page 18 of 44
install and manage Python packages. Pip has earned its fame by the number of
applications using this tool.

Used for its capabilities in handling binary packages over the easily installed
package manager, pip enables 3rd party package installations. Pip also supports
installing from requirements files which provide an easy way to specify a whole
environment to be installed.

3.4 DATASETS:

For this Healthcare chatbot we need atleast 2 – 3 datasets. In this project I


used Training set, Testing set, Symptom description, Symptom precaution,
Symptom severnity and doctor consultation. These are the datasets which are used
in this project.

These data are stored as a CSV (Comma-separated values). It is a text fie


that has a specific format which allows data to be saved in a table structured
format. With help of the python modules pandas, Numpy and CSV, we can
manipulate and analysis the data. The python In-built module CSV to work with
CSV files in python, that makes working with CSV files much easier.

Pandas is mainly used for data analysis. Pandas allows importing data from
various file formats such as CSV, JSON, SQL, Ms Excel. NumPy aims to provide
an array object that is up to 50x faster than tradition Python lists.

Page 19 of 44
CHAPTER 4
PROJECT DESCRIPTION
4.1 SCOPE OF THE PROJECT:

The project Health care Chat Bot. The proposed idea is to make a medical
chatbot using Artificial Intelligence which will diagnose the disease and supply
basic details about the disease before consulting a doctor. To reduce the healthcare
costs and improve accessibility to medical knowledge the medical chatbot is made.
Certain chatbots acts as a medical reference books, which helps the patient know
more about their disease and helps to enhance their health. The user can achieve
the real advantage of a chatbot only if it can diagnose all quite disease and supply
necessary information. A text-to-text diagnosis bot engages patients in
conversation about their medical issues and provides a personalized diagnosis
supported their symptoms. Hence, people will have a thought about their health
and have the correct protection.

Page 20 of 44
4.2 SYSTEM ARCHITECTURE:

FLOW CHART:

Personal
Start Information

Initiate Chat

Welcome Request to
message Consult Doctor

Display
Assessment Severity
Symptomatic
of infection score
questions

Thank you for


contacting Descriptive of
preventive
measure

Main menu/
End Chat Live
Frequently asked
chat
questions Page 21 of 44
Main menu/
End chat

Figure 4.1 Flow chart

DATA FLOW DIAGRAM:

Input Response
Speech Text

Normalization Best Response


& Tokenization Selection

POS-tagging Rule Matching


Database

Parsing

Figure 4.2 Data flow diagram

Page 22 of 44
4.3 APPLICATION FEATURES:

4.3.1 INTERACTION:

ChatBot can be described as software that can chat with people using
artificial intelligence. These software are used to perform tasks such as quickly
responding to users, informing them, helping to purchase products and providing
better service to customers. In this paper, we present the general working principle
and the basic concepts of artificial intelligence based chatbots and related concepts
as well as their applications in various sectors such as telecommunication, banking,
health, customer call center and e-commerce. Additionally, the results of an
example chatbot for donation service developed for telecommunication service
provider are presented using the proposed architecture. We are using it for
educational purpose to solve the quires of users.

4.3.2 TASK EXECUTION:

To lead a better life healthcare is extremely much important. But it's very
difficult to get the consultation with the doctor just in case of any health issues.
The proposed idea is to make a medical chatbot using Artificial Intelligence which
will diagnose the disease and supply basic details about the disease before
consulting a doctor. To reduce the healthcare costs and improve accessibility to
medical knowledge the medical chatbot is made. Certain chatbots acts as a medical
reference books, which helps the patient know more about their disease and helps
to enhance their health. The user can achieve the real advantage of a chatbot only if
it can diagnose all quite disease and supply necessary information.

4.3.3 TERMINATION:
Page 23 of 44
A text-to-text diagnosis bot engages patients in conversation about their
medical issues and provides a personalized diagnosis supported their symptoms.
Hence, people will have a thought about their health and have the correct
protection. Once user answered the series of questions, with the necessary answers.
The threshold value is calculated with the questions they have answered. So if
threshold value goes above the marked value. ChatBot will pop a message to
consult a necessary doctor and also provides necessary information about the
disease.

CHAPTER-5
RESULTS
5.1 USER INTERFACE:

CHATBOT INTERACTION:

Figure 5.1 Chat bot and user interaction

Page 24 of 44
SERIES OF QUESTIONING:

Figure 5.2 Questioning of disease symptoms

Page 25 of 44
ANALYSIS:

Figure 5.3 symptom analysis

Page 26 of 44
DIAGNOSE DISEASE:

Figure 5.4 diagnose disease

Page 27 of 44
SYMPTOM PRECAUTION:

Figure 5.5 symptom precaution

Page 28 of 44
CHAPTER-6
CONCLUSION AND FUTURE ENHANCEMENTS
6.1 FUTURE ENHANCEMENT:

In the future, we would like to add some more features in the Healthcare
chat bot. So that it can be more interactive with people. We would like to add some
more modules in Healthcare chat bot to work more efficiently.

Chat bot will be designed to not just actively capture but captivate the
patients’ interest regarding their care calls into questions and further engaging
more with patients to improve outcomes. We will make chat bot so dynamic with
it’s responses that gives users a very humanized experience, so users feel as though
they’re talking to real person.

A chatbot for healthcare has the capacity to check existing coverage, help
file claims and track the status of claims. Healthcare AI tools can help doctors
through the pre-authorization process and billing inquiries.

Page 29 of 44
6.2 CONCLUSION:

ChatBot can be described as software that can chat with people using
artificial intelligence. These software are used to perform tasks such as quickly
responding to users, informing them, helping to purchase products and providing
better service to customers. In this paper, we present the general working principle
and the basic concepts of artificial intelligence based chatbots and related concepts
as well as their applications in various sectors such as telecommunication, banking,
health, customer call centre and e-commerce. Additionally, the results of an
example chatbot for donation service developed for telecommunication service
provider are presented using the proposed architecture. We are using it for
educational purpose to solve the quires of users.

Page 30 of 44
APPENDICES
APPENDIX – 1
SAMPLE SCRIPT
Program:

import pandas as pd

import pyttsx3

from sklearn import preprocessing

from sklearn.tree import DecisionTreeClassifier,_tree

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.model_selection import cross_val_score

from sklearn.svm import SVC

import csv

import warnings

warnings.filterwarnings("ignore", category=DeprecationWarning)

Page 31 of 44
training = pd.read_csv('C:\\Users\\ashish\\Desktop\\ChatBot API\\Training.csv')

testing= pd.read_csv('C:\\Users\\ashish\\Desktop\\ChatBot API\\Testing.csv')

cols= training.columns

cols= cols[:-1]

x = training[cols]

y = training['prognosis']

y1= y

reduced_data = training.groupby(training['prognosis']).max()

#mapping strings to numbers

le = preprocessing.LabelEncoder()

le.fit(y)

y = le.transform(y)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33,


random_state=42)

testx = testing[cols]

testy = testing['prognosis']

#testy = str(le.transform(testy))

Page 32 of 44
clf1 = DecisionTreeClassifier()

clf = clf1.fit(x_train,y_train)

# print(clf.score(x_train,y_train))

# print ("cross result========")

scores = cross_val_score(clf, x_test, y_test, cv=3)

# print (scores)

print (scores.mean())

model=SVC()

model.fit(x_train,y_train)

print("for svm: ")

print(model.score(x_test,y_test))

importances = clf.feature_importances_

indices = np.argsort(importances)[::-1]

features = cols

def readn(nstr):

engine = pyttsx3.init()

Page 33 of 44
engine.setProperty('voice', "english+f5")

engine.setProperty('rate', 130)

engine.say(nstr)

engine.runAndWait()

engine.stop()

severityDictionary=dict()

description_list = dict()

precautionDictionary=dict()

symptoms_dict = {}

for index, symptom in enumerate(x):

symptoms_dict[symptom] = index

def calc_condition(exp,days):

sum=0

for item in exp:

sum=sum+severityDictionary[item]

if((sum*days)/(len(exp)+1)>13):

print("You should take the consultation from doctor. ")

else:
Page 34 of 44
print("It might not be that bad but you should take precautions.")

def getDescription():

global description_list

with open('C:\\Users\\ashish\\Desktop\\ChatBot API\\


symptom_Description.csv') as csv_file:

csv_reader = csv.reader(csv_file, delimiter=',')

line_count = 0

for row in csv_reader:

_description={row[0]:row[1]}

description_list.update(_description)

def getSeverityDict():

global severityDictionary

with open('C:\\Users\\ashish\\Desktop\\ChatBot API\\Symptom_severity.csv') as


csv_file:

csv_reader = csv.reader(csv_file, delimiter=',')

line_count = 0

Page 35 of 44
try:

for row in csv_reader:

_diction={row[0]:int(row[1])}

severityDictionary.update(_diction)

except:

pass

def getprecautionDict():

global precautionDictionary

with open('C:\\Users\\ashish\\Desktop\\ChatBot API\\symptom_precaution.csv')


as csv_file:

csv_reader = csv.reader(csv_file, delimiter=',')

line_count = 0

for row in csv_reader:

_prec={row[0]:[row[1],row[2],row[3],row[4]]}

precautionDictionary.update(_prec)

def getInfo():

# name=input("Name:")

print("Your Name \n\t\t\t\t\t\t",end="->")

Page 36 of 44
name=input("")

print("hello ",name)

def check_pattern(dis_list,inp):

import re

pred_list=[]

ptr=0

patt = "^" + inp + "$"

regexp = re.compile(inp)

for item in dis_list:

# print(f"comparing {inp} to {item}")

if regexp.search(item):

pred_list.append(item)

# return 1,item

if(len(pred_list)>0):

return 1,pred_list

else:

return ptr,item

def sec_predict(symptoms_exp):

df = pd.read_csv('C:\\Users\\ashish\\Desktop\\ChatBot API\\Training.csv')

X = df.iloc[:, :-1]

y = df['prognosis']
Page 37 of 44
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=20)

rf_clf = DecisionTreeClassifier()

rf_clf.fit(X_train, y_train)

symptoms_dict = {}

for index, symptom in enumerate(X):

symptoms_dict[symptom] = index

input_vector = np.zeros(len(symptoms_dict))

for item in symptoms_exp:

input_vector[[symptoms_dict[item]]] = 1

return rf_clf.predict([input_vector])

def print_disease(node):

#print(node)

node = node[0]

#print(len(node))

val = node.nonzero()

Page 38 of 44
# print(val)

disease = le.inverse_transform(val[0])

return disease

def tree_to_code(tree, feature_names):

tree_ = tree.tree_

# print(tree_)

feature_name = [

feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"

for i in tree_.feature

chk_dis=",".join(feature_names).split(",")

symptoms_present = []

# conf_inp=int()

while True:

print("Enter the symptom you are experiencing \n\t\t\t\t\t\t",end="->")

disease_input = input("")

conf,cnf_dis=check_pattern(chk_dis,disease_input)

if conf==1:

print("searches related to input: ")


Page 39 of 44
for num,it in enumerate(cnf_dis):

print(num,")",it)

if num!=0:

print(f"Select the one you meant (0 - {num}): ", end="")

conf_inp = int(input(""))

else:

conf_inp=0

disease_input=cnf_dis[conf_inp]

break

# print("Did you mean: ",cnf_dis,"?(yes/no) :",end="")

# conf_inp = input("")

# if(conf_inp=="yes"):

# break

else:

print("Enter valid symptom.")

while True:

try:

num_days=int(input("Okay. From how many days ? : "))

break

except:

print("Enter number of days.")


Page 40 of 44
def recurse(node, depth):

indent = " " * depth

if tree_.feature[node] != _tree.TREE_UNDEFINED:

name = feature_name[node]

threshold = tree_.threshold[node]

if name == disease_input:

val = 1

else:

val = 0

if val <= threshold:

recurse(tree_.children_left[node], depth + 1)

else:

symptoms_present.append(name)

recurse(tree_.children_right[node], depth + 1)

else:

present_disease = print_disease(tree_.value[node])

# print( "You may have " + present_disease )

red_cols = reduced_data.columns

symptoms_given =
red_cols[reduced_data.loc[present_disease].values[0].nonzero()]

# dis_list=list(symptoms_present)

# if len(dis_list)!=0:

Page 41 of 44
# print("symptoms present " + str(list(symptoms_present)))

# print("symptoms given " + str(list(symptoms_given)) )

print("Are you experiencing any ")

symptoms_exp=[]

for syms in list(symptoms_given):

inp=""

print(syms,"? : ",end='')

while True:

inp=input("")

if(inp=="yes" or inp=="no"):

break

else:

print("provide proper answers i.e. (yes/no) : ",end="")

if(inp=="yes"):

symptoms_exp.append(syms)

second_prediction=sec_predict(symptoms_exp)

# print(second_prediction)

calc_condition(symptoms_exp,num_days)

if(present_disease[0]==second_prediction[0]):

print("You may have ", present_disease[0])

print(description_list[present_disease[0]])
Page 42 of 44
# readn(f"You may have {present_disease[0]}")

# readn(f"{description_list[present_disease[0]]}")

else:

print("You may have ", present_disease[0], "or ", second_prediction[0])

print(description_list[present_disease[0]])

print(description_list[second_prediction[0]])

# print(description_list[present_disease[0]])

precution_list=precautionDictionary[present_disease[0]]

print("Take following measures : ")

for i,j in enumerate(precution_list):

print(i+1,")",j)

# confidence_level = (1.0*len(symptoms_present))/len(symptoms_given)

# print("confidence level is " + str(confidence_level))

recurse(0, 1)

getSeverityDict()

getDescription()

getprecautionDict()

getInfo()
Page 43 of 44
tree_to_code(clf,cols)

REFEERENCE

1. https://www.geeksforgeeks.com

2. https://www.pypi.org

3. docs.python.org

4. www.tutorialspoint.com

5. www.stackoverflow.com

Page 44 of 44

You might also like