a b/HealthCare_ChatBot/Health_Care_App.py
1
#Imports tkinter Library
2
from tkinter import *
3
import tkinter.messagebox
4
from tkinter.simpledialog import askstring
5
6
#Imports Library
7
import re
8
import webbrowser
9
from bot import getresponse,get_pridected_value , get_diesese_practions
10
11
# defined color for tkinter
12
BG_GRAY = "#FFFFFF"
13
BG_COLOR = "#DFE3EE"
14
TEXT_COLOR = "#000000"
15
FONT = "Helvetica 14"
16
FONT_BOLD = "Helvetica 13 bold"
17
18
#Main Tk class
19
class ChatApplication:
20
    
21
    def __init__(self):
22
        self.window = Tk()
23
        self.outputs = []
24
        self.days = 0
25
        self._get_name()
26
        
27
    def run(self):
28
        self.window.mainloop()
29
    
30
    #--------------------------------------------- start Window asking questions ----------------------------------------------
31
    # Print answer to the tk window 
32
    def giveanswer(self,dises,ans):
33
        self.text_widget.tag_config('blue', foreground="#FDD20E")
34
        self.msg_entry.delete(0, END)
35
        sender = self.name_entry.get().split(" ")[0]
36
        msg1 = f"{sender} : "
37
        msg2 = f"{dises} -> {ans} \n"
38
        self.text_widget.configure(state=NORMAL)
39
        self.text_widget.insert(END, msg1.capitalize(), 'blue')
40
        self.text_widget.insert(END, msg2.capitalize())
41
        self.text_widget.configure(state=DISABLED)
42
43
    # asking function for how many days 
44
    def _suffering_days(self):
45
        no_of_days = askstring(f"Please only respond in a number of days.", f"Since how many days do you suffer? ")
46
        if no_of_days is None:
47
            self.msg_warning(f"Wrong Input ","Please respond only in number format. Do not cancel because it's important.")
48
            self._suffering_days()
49
        elif no_of_days.isnumeric() is True and int(no_of_days) > 0:
50
            self.giveanswer("Since how many days do you suffer? ",no_of_days)
51
            self.days += int(no_of_days)
52
        else:
53
            self.msg_warning(f"Wrong Input ","Please respond only in number format. Do not cancel because it's important.")
54
            self._suffering_days()
55
56
57
    # ask question to the user 
58
    def ask_box(self,desid):
59
        prompt = askstring(f"Please respond only with (Yes/No)", f"Are you suffering from a ' {desid} ' ? ")
60
        if prompt == None:
61
            self.msg_warning(f"{desid} Wrong Input ","Please respond only in (yes/no) format.Do not cancel because it's important.")
62
            self.ask_box(desid)
63
        elif prompt.lower() == "no" or prompt.lower() == "yes":
64
            self.giveanswer(desid,prompt)
65
            if prompt.lower() == "yes" :
66
                self.outputs.append(desid)
67
        else:
68
            self.msg_warning(f"{desid} Wrong Input ","Please give the answer only in (yes/no)")
69
            self.ask_box(desid)
70
    # -------------------------------------------End of ask question -----------------------------------------------
71
72
73
    # ====================================================  START OF TKINTER FIRST WINDOW =====================================================
74
    #First tkinter window open and asking the name of user
75
    def _get_name(self):
76
        self.window.title("Welcome to Health Care Chatbot")
77
        self.window.resizable(width=False, height=False)
78
        self.window.configure(width=500, height=500, bg=BG_COLOR)
79
80
        # tiny divider
81
        line = Label(self.window, width=450, bg=BG_GRAY)
82
        line.place(relwidth=1, y=0, relheight=0.002)
83
84
        # entry label
85
        self.name = Label(self.window, bg="#8B9DC3", fg=TEXT_COLOR,
86
                           text="Please Enter Your name", font=FONT_BOLD, pady=10)
87
        self.name.place(relwidth=1,y=57.3)
88
89
        # message entry box level
90
        name_label = Label(self.window, bg=BG_COLOR, height=80)
91
        name_label.place(relheight=0.09, relwidth=1,y=105.9)
92
        #msg entery box
93
        self.name_entry = Entry(name_label, bg=BG_GRAY, fg="BLACK", font=FONT_BOLD)
94
        self.name_entry.place(relheight=0.85,relwidth=0.74, x=65)
95
        self.name_entry.focus()
96
        self.name_entry.bind("<Return>", self.get_name_after_click)
97
98
        #save name button label
99
        name_box_label = Label(self.window, bg=BG_COLOR, height=80)
100
        name_box_label.place(relheight=0.09, relwidth=1,y=150.9)
101
        #button
102
        name_send_button = Button(name_box_label, text="Submit", fg=TEXT_COLOR, font=FONT_BOLD, width=20, bg="#8B9DC3",
103
                             command=lambda: self.get_name_after_click(None))
104
        name_send_button.place(relheight=1,relwidth=0.24, x=190)
105
106
        #------------------------------- menu button ------------------------------------
107
        menu = Menu(self.window,bg=BG_COLOR,borderwidth=0,fg=TEXT_COLOR,font="bold")
108
        self.window.config(menu=menu, bd=5)
109
110
        # File menu 
111
        File = Menu(menu, tearoff=0,font="bold",activebackground="#FFFFFF")
112
        menu.add_cascade(label="File", menu=File,font="bold")
113
        File.add_command(label="Clear Chat",command=self.clear_chat,font="bold")
114
        File.add_command(label="Exit",command=None,font="bold")
115
116
        # About menu 
117
        about = Menu(menu, tearoff=0,font="bold",activebackground="#FFFFFF")
118
        menu.add_cascade(label="About", menu=about,font="bold")
119
        about.add_command(label="Develpoers", command=lambda: self.msg_showinfo(f"Bot Develpoers ",f"Project Mentor - Mr.Prashant Kumar Yadav \n\nGroup number - 01 \n\nGroup Members \n\n1. Durgesh Maurya (105501) \n2. Dimpla (185506) \n3. Dev Sharan Yadav (185532) \n"),font="bold")
120
        about.add_command(label="About Project", command=lambda: self.msg_showinfo(f"Bot V1.0.0 ",f" \tAbout Project \n\nThe primary goal of this project is to forecast the disease so that patients can get the desired output according to their primary symptoms.\n\n GitHub Link \n\nhttps://github.com/Durgesh63/HealthCare_ChatBot.git"),font="bold")
121
122
        # Quit menu 
123
        menu.add_command(label ='Quit!',font="bold", command=lambda: self.msg_msg_askcancle(f"Ok Quit "," Are You sure? "))
124
125
    # ====================================================  END OF TKINTER FIRST WINDOW =====================================================
126
127
    # Name Validations
128
    def get_name_after_click(self,name):
129
        if len(self.name_entry.get()) >= 2:
130
            self._setup_main_window()
131
            self.coming_msg()
132
        else:
133
            self.msg_warning("Message Regarding Name Error","Please enter at least two words of a name.")
134
            
135
136
    #================================================ START MAIN WINDOW =========================================================
137
    def _setup_main_window(self):
138
        self.window.title("Welcome to Health Care Chatbot")
139
        self.window.resizable(width=False, height=False)
140
        self.window.configure(width=1200, height=640, bg=BG_COLOR)
141
142
        # tiny divider
143
        line = Label(self.window, width=450, bg=BG_GRAY)
144
        line.place(relwidth=1, y=0, relheight=0.012)
145
        
146
        #------------------- left side label -------------------------
147
        leftside_label = Label(self.window, bg=BG_COLOR, height=80,border=1)
148
        leftside_label.place(relheight=1, relwidth=0.2519,y=3 )
149
150
        # sidebox name lable
151
        self.name = Label(leftside_label, bg=BG_COLOR, fg=TEXT_COLOR,
152
                           text=self.name_entry.get().capitalize(), font=FONT_BOLD, pady=10)
153
        self.name.place(relheight=0.07, relwidth=1,y=1)
154
155
        # sidebox Help box
156
        self.help = Label(leftside_label, bg="#8B9DC3", fg=TEXT_COLOR,
157
                           text="Help Search (Similar diseases)", font=FONT_BOLD, pady=10)
158
        self.help.place(relheight=0.07, relwidth=1,y=48)
159
160
        # search box label
161
        search_label = Label(leftside_label, bg="#8B9DC3", height=80)
162
        search_label.place(relheight=0.07, relwidth=1,y=94)
163
164
        #Help message entry box 
165
        self.help_entry = Entry(search_label, bg=BG_GRAY, fg="BLACK", font=FONT_BOLD)
166
        self.help_entry.place(relheight=0.85,relwidth=0.74, y=2.4)
167
        self.help_entry.focus()
168
        self.help_entry.bind("<Return>", self._on_enter_help_search)
169
170
        # send button
171
        help_send_button = Button(search_label, text="Search", font=FONT_BOLD, width=20, bg=BG_GRAY,
172
                             command=lambda: self._on_enter_help_search(None))
173
        help_send_button.place(relheight=0.85,relwidth=0.24,y=2.4, x=224)
174
175
        #Searchbox
176
        self.search_box = Text(leftside_label, width=20, height=2, bg="#DFE3EE", fg=TEXT_COLOR,
177
                                font=FONT, padx=8, pady=8)
178
        self.search_box.place(relheight=.779, relwidth=1,y=140)
179
        self.search_box.configure(cursor="arrow", state=DISABLED)
180
        # scroll bar for search_box
181
        scrollsearch = Scrollbar(self.search_box)
182
        scrollsearch.place(relheight=1, relx=0.97)
183
        scrollsearch.configure(command=self.search_box.yview)
184
185
        #------------------------------ righ sider lebel -------------------------------
186
        rightside_label = Label(self.window, bg=BG_COLOR, height=80,border=1)
187
        rightside_label.place(relheight=1, relwidth=0.75,y=3 ,x=300)
188
189
        # text widget
190
        self.text_widget = Text(rightside_label, width=20, height=2, bg=BG_COLOR, fg=TEXT_COLOR,
191
                                font=FONT, padx=5, pady=5)
192
        self.text_widget.place(relheight=0.893, relwidth=1,y=0 ,x=0)
193
        self.text_widget.configure(cursor="arrow", state=DISABLED)
194
        
195
        # scroll bar
196
        scrollbar = Scrollbar(self.text_widget)
197
        scrollbar.place(relheight=1, relx=0.99)
198
        scrollbar.configure(command=self.text_widget.yview)
199
200
        
201
        #---------------------------------- bottom label ------------------------------------
202
        bottom_label = Label(rightside_label, bg="#8B9DC3", height=80)
203
        bottom_label.place(relwidth=1,relheight=.1,x=1, y=563.7 )
204
        
205
        # message entry box #2C3E50
206
        self.msg_entry = Entry(bottom_label, bg=BG_GRAY, fg="Black", font=FONT)
207
        self.msg_entry.place(relheight=0.85,relwidth=0.82,x=5, y=4)
208
        self.msg_entry.focus()
209
        self.msg_entry.bind("<Return>", self._on_enter_pressed)
210
        
211
        # # send button
212
        send_button = Button(bottom_label, text="Send", font=FONT_BOLD, width=20, bg=BG_GRAY,
213
                             command=lambda: self._on_enter_pressed(None))
214
        send_button.place(relheight=0.85, relwidth=0.15,x=745,y=4)
215
216
    #================================================ END START MAIN WINDOW =========================================================
217
    
218
    # get search help Diesies
219
    def _on_enter_help_search(self,event):
220
        dis_list = ['itching', 'skin rash', 'nodal skin eruptions', 'continuous sneezing', 'shivering', 'chills', 'joint pain', 'stomach pain', 'acidity', 'ulcers on tongue', 'muscle wasting', 'vomiting', 'burning micturition', 'spotting urination', 'fatigue', 'weight gain', 'anxiety', 'cold hands and feets', 'mood swings', 'weight loss', 'restlessness', 'lethargy', 'patches in throat', 'irregular sugar level', 'cough', 'high fever', 'sunken eyes', 'breathlessness', 'sweating', 'dehydration', 'indigestion', 'headache', 'yellowish skin', 'dark urine', 'nausea', 'loss of appetite', 'pain behind the eyes', 'back pain', 'constipation', 'abdominal pain', 'diarrhoea', 'mild fever', 'yellow urine', 'yellowing of eyes', 'acute liver failure', 'fluid overload', 'swelling of stomach', 'swelled lymph nodes', 'malaise', 'blurred and distorted vision', 'phlegm', 'throat irritation', 'redness of eyes', 'sinus pressure', 'runny nose', 'congestion', 'chest pain', 'weakness in limbs', 'fast heart rate', 'pain during bowel movements', 'pain in anal region', 'bloody stool', 'irritation in anus', 'neck pain', 'dizziness', 'cramps', 'bruising', 'obesity', 'swollen legs', 'swollen blood vessels', 'puffy face and eyes', 'enlarged thyroid', 'brittle nails', 'swollen extremeties', 'excessive hunger', 'extra marital contacts', 'drying_and_tingling_lips', 'slurred_speech', 'knee_pain', 'hip_joint_pain', 'muscle_weakness', 'stiff_neck', 'swelling_joints', 'movement_stiffness', 'spinning_movements', 'loss_of_balance', 'unsteadiness', 'weakness_of_one_body_side', 'loss_of_smell', 'bladder_discomfort', 'foul_smell_of urine', 'continuous_feel_of_urine', 'passage_of_gases', 'internal_itching', 'toxic_look_(typhos)', 'depression', 'irritability', 'muscle_pain', 'altered_sensorium', 'red_spots_over_body', 'belly_pain', 'abnormal_menstruation', 'dischromic _patches', 'watering_from_eyes', 'increased_appetite', 'polyuria', 'family_history', 'mucoid_sputum', 'rusty_sputum', 'lack_of_concentration', 'visual_disturbances', 'receiving_blood_transfusion', 'receiving_unsterile_injections', 'coma', 'stomach_bleeding', 'distention_of_abdomen', 'history_of_alcohol_consumption', 'fluid_overload.1', 'blood_in_sputum', 'prominent_veins_on_calf', 'palpitations', 'painful_walking', 'pus_filled_pimples', 'blackheads', 'scurring', 'skin_peeling', 'silver_like_dusting', 'small_dents_in_nails', 'inflammatory_nails', 'blister', 'red_sore_around_nose', 'yellow_crust_ooze']
221
        inp = self.help_entry.get()
222
        pred_list=[]
223
        if len(inp) > 0:
224
            regexp = re.compile(inp)
225
            for item in dis_list:
226
                if regexp.search(item):
227
                    pred_list.append(item)
228
        self.help_entry.delete(0, END)
229
        if len(pred_list) > 0:
230
            msg1 = ""
231
            for i in range(len(pred_list)):
232
                msg1 += f"{i+1})  {pred_list[i]} \n"
233
        else:
234
            msg1 = "Ohh!! There were no similar diseases discovered."
235
        self.search_box.configure(state=NORMAL)
236
        self.search_box.delete("1.0",END)
237
        self.search_box.insert(END, msg1)
238
        self.search_box.configure(state=DISABLED)
239
240
    # bot First welcome Message 
241
    def coming_msg(self):
242
        good_name  = self.name_entry.get().split(" ")[0]
243
        msg = f"Hey! {good_name} , Are you not feeling well? Please tell me what symptoms here are some examples:\n --> fever\n --> cold\n --> cough\n --> headache\n --> stomach_pain\n --> abdominal_pain\n --> dehydration\n --> swelling\n --> acidity\n --> internal_itching\n --> sneezing\n --> vomiting\n --> anxiety , etc \n Note: Please use underscore (  _  ) in place of spacing in the name of disease.\n\n"
244
        # msg = f"Hey! {good_name} ,Are you not feeling well? Please tell me what symptoms here are some examples: \n fever , cold , cough , headache , stomach_pain , abdominal_pain , dehydration , swelling , acidity , \n itching , sneezing , vomiting , anxiety , etc.\nNote: Please use underscore( _ ) in place of spacing in the name of disease.\n\n"
245
        self._bot_insert(msg)
246
247
    #===================================== START RESPONSE MESSAGE =============================================
248
    # get the type msg from the entery of main msg box 
249
    def _on_enter_pressed(self, event):
250
        msg = self.msg_entry.get()
251
        self._insert_message(msg)
252
253
    #get and send response message     
254
    def _insert_message(self, msg):
255
        if not msg:
256
            return
257
258
        # delete the entery whtich is in entry box 
259
        self.msg_entry.delete(0, END)
260
261
        # sender msg or user msg 
262
        sender = self.name_entry.get().split(" ")[0]
263
        msg1 = f"{sender} : "
264
        msg2 = f"{msg}\n"
265
266
        #user insert msg
267
        self._user_instet_msg(msg1,msg2)
268
269
        # if we type any one from quit_msg then window close 
270
        quit_msg = ["quit","exit","bye","bye bye"]        
271
        if len([i for i in quit_msg if i == msg.lower()]) == 1:
272
            self.msg_msg_askcancle(f"Ok Quit "," Are You sure? ")
273
        
274
        # get msg form response from bot 
275
        else:
276
            chat_hear = getresponse(msg)
277
            if len(chat_hear) == 1 :
278
                msg4 = f"{chat_hear[0]} \n\n"
279
                self._bot_insert(msg4)
280
            elif len(chat_hear) > 1 :
281
                msg4 = f"{chat_hear[0]} \n \t Please give input on the diseases. \n\n"
282
                self._bot_insert(msg4)
283
                self.days *= 0
284
                self._suffering_days()
285
                self.outputs.clear()
286
                for i in chat_hear[1]:
287
                    self.ask_box(i)
288
                msg4 = f"You may also have diseases like \n"
289
                # if more than one output then condition true 
290
                if len(self.outputs) > 0 :
291
                    for i in range(len(self.outputs)):
292
                        msg4 += f"\t {i+1} ) : {self.outputs[i]}\n"
293
                    msg4 += f"\n"
294
                else:
295
                    msg4 += f"\t 1 ) : {chat_hear[0]}\n\n"
296
                self._bot_insert(msg4)
297
298
                # no of days 
299
                if self.days > 10:
300
                    self._bot_insert("Stop taking the medicine and reach out to the nearest hospital. \n")
301
302
                # get answer 
303
                final_dieses = get_pridected_value(self.outputs)
304
                try:
305
                    diesese_is =  get_diesese_practions(final_dieses)
306
                except:
307
                    diesese_is = f"Sorry no diese get {final_dieses} \n"
308
                self._bot_insert(diesese_is)
309
310
                # open webbrowser when number of days is grater than 10
311
                if self.days > 10:
312
                    ask_to_web = tkinter.messagebox.askokcancel("Permission to open Google Maps", "Do you want to launch Google Maps in your regular browser?\n ")
313
                    if ask_to_web is True:
314
                        webbrowser.open_new_tab('https://www.google.com/maps/search/hospital+near+me/')
315
                        self._bot_insert(" Open Google Maps on your default web browser \n")
316
            else:
317
                pass
318
319
    # ============================================= END RESPONSE MESSAGE ============================================================
320
321
    # clear chat box
322
    def clear_chat(self):
323
        self.text_widget.config(state=NORMAL)
324
        self.text_widget.delete(1.0, END)
325
        self.text_widget.delete(1.0, END)
326
        self.text_widget.config(state=DISABLED)
327
        self.coming_msg()
328
    # Insert msg from user
329
    def _user_instet_msg(self,usr,msg):
330
        self.text_widget.tag_config('blue', foreground="#FDD20E")
331
        self.text_widget.configure(state=NORMAL)
332
        self.text_widget.insert(END, usr.capitalize(), 'blue')
333
        self.text_widget.insert(END, msg.capitalize())
334
        self.text_widget.configure(state=DISABLED)
335
    #insert msg from bot
336
    def _bot_insert(self,msg):
337
        self.text_widget.tag_config('red', foreground="#F93822")
338
        self.text_widget.configure(state=NORMAL)
339
        self.text_widget.insert(END, "Bot : ","#8B9DC3")
340
        self.text_widget.insert(END, msg)
341
        self.text_widget.configure(state=DISABLED)
342
        self.text_widget.see(END)
343
    # ----------------------------------- Msg showing window --------------------------------    
344
    def msg_showinfo(self,title,msg):
345
        tkinter.messagebox.showinfo(title,msg)
346
    def msg_warning(self,title,msg):
347
        tkinter.messagebox.showwarning(title,msg)
348
    def msg_msg_askcancle(self,title,msg):
349
        msg_data = tkinter.messagebox.askokcancel(title, msg)
350
        if msg_data == True:
351
            self.window.destroy()
352
    # ----------------------------------- end Msg showing window --------------------------------        
353
if __name__ == "__main__":
354
    app = ChatApplication()
355
    app.run()