henry2024 commited on
Commit
ceeec26
β€’
1 Parent(s): eb2ca9e

Upload App.py

Browse files
Files changed (1) hide show
  1. App.py +197 -0
App.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import and class names setup
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+ import random
6
+ import nltk_utils
7
+ import pandas as pd
8
+ from sklearn.model_selection import train_test_split
9
+ import time
10
+
11
+ from model import RNN_model
12
+ from timeit import default_timer as timer
13
+ from typing import Tuple, Dict
14
+
15
+ # Import data
16
+ df= pd.read_csv('Symptom2Disease.csv')
17
+ df.drop('Unnamed: 0', axis= 1, inplace= True)
18
+
19
+ # Preprocess data
20
+ df.drop_duplicates(inplace= True)
21
+ train_data, test_data= train_test_split(df, test_size=0.15, random_state=42 )
22
+
23
+ # Setup class names
24
+ class_names= {0: 'Acne',
25
+ 1: 'Arthritis',
26
+ 2: 'Bronchial Asthma',
27
+ 3: 'Cervical spondylosis',
28
+ 4: 'Chicken pox',
29
+ 5: 'Common Cold',
30
+ 6: 'Dengue',
31
+ 7: 'Dimorphic Hemorrhoids',
32
+ 8: 'Fungal infection',
33
+ 9: 'Hypertension',
34
+ 10: 'Impetigo',
35
+ 11: 'Jaundice',
36
+ 12: 'Malaria',
37
+ 13: 'Migraine',
38
+ 14: 'Pneumonia',
39
+ 15: 'Psoriasis',
40
+ 16: 'Typhoid',
41
+ 17: 'Varicose Veins',
42
+ 18: 'allergy',
43
+ 19: 'diabetes',
44
+ 20: 'drug reaction',
45
+ 21: 'gastroesophageal reflux disease',
46
+ 22: 'peptic ulcer disease',
47
+ 23: 'urinary tract infection'
48
+ }
49
+
50
+ vectorizer= nltk_utils.vectorizer()
51
+ vectorizer.fit(train_data.text)
52
+
53
+
54
+
55
+ # Model and transforms preparation
56
+ model= RNN_model()
57
+ # Load state dict
58
+ model.load_state_dict(torch.load(
59
+ f= 'pretrained_symtom_to_disease_model.pth',
60
+ map_location= torch.device('cpu')
61
+ )
62
+ )
63
+ # Disease Advice
64
+ disease_advice = {
65
+ 'Acne': "Maintain a proper skincare routine, avoid excessive touching of the affected areas, and consider using over-the-counter topical treatments. If severe, consult a dermatologist.",
66
+ 'Arthritis': "Stay active with gentle exercises, manage weight, and consider pain-relief strategies like hot/cold therapy. Consult a rheumatologist for tailored guidance.",
67
+ 'Bronchial Asthma': "Follow prescribed inhaler and medication regimen, avoid triggers like smoke and allergens, and have an asthma action plan. Regular check-ups with a pulmonologist are important.",
68
+ 'Cervical spondylosis': "Maintain good posture, do neck exercises, and use ergonomic support. Physical therapy and pain management techniques might be helpful.",
69
+ 'Chicken pox': "Rest, maintain hygiene, and avoid scratching. Consult a doctor for appropriate antiviral treatment.",
70
+ 'Common Cold': "Get plenty of rest, stay hydrated, and consider over-the-counter remedies for symptom relief. Seek medical attention if symptoms worsen or last long.",
71
+ 'Dengue': "Stay hydrated, rest, and manage fever with acetaminophen. Seek medical care promptly, as dengue can escalate quickly.",
72
+ 'Dimorphic Hemorrhoids': "Follow a high-fiber diet, maintain good hygiene, and consider stool softeners. Consult a doctor if symptoms persist.",
73
+ 'Fungal infection': "Keep the affected area clean and dry, use antifungal creams, and avoid sharing personal items. Consult a dermatologist if it persists.",
74
+ 'Hypertension': "Follow a balanced diet, exercise regularly, reduce salt intake, and take prescribed medications. Regular check-ups with a healthcare provider are important.",
75
+ 'Impetigo': "Keep the affected area clean, use prescribed antibiotics, and avoid close contact. Consult a doctor for proper treatment.",
76
+ 'Jaundice': "Get plenty of rest, maintain hydration, and follow a doctor's advice for diet and medications. Regular monitoring is important.",
77
+ 'Malaria': "Take prescribed antimalarial medications, rest, and manage fever. Seek medical attention for severe cases.",
78
+ 'Migraine': "Identify triggers, manage stress, and consider pain-relief medications. Consult a neurologist for personalized management.",
79
+ 'Pneumonia': "Follow prescribed antibiotics, rest, stay hydrated, and monitor symptoms. Seek immediate medical attention for severe cases.",
80
+ 'Psoriasis': "Moisturize, use prescribed creams, and avoid triggers. Consult a dermatologist for effective management.",
81
+ 'Typhoid': "Take prescribed antibiotics, rest, and stay hydrated. Dietary precautions are important. Consult a doctor for proper treatment.",
82
+ 'Varicose Veins': "Elevate legs, exercise regularly, and wear compression stockings. Consult a vascular specialist for evaluation and treatment options.",
83
+ 'allergy': "Identify triggers, manage exposure, and consider antihistamines. Consult an allergist for comprehensive management.",
84
+ 'diabetes': "Follow a balanced diet, exercise, monitor blood sugar levels, and take prescribed medications. Regular visits to an endocrinologist are essential.",
85
+ 'drug reaction': "Discontinue the suspected medication, seek medical attention if symptoms are severe, and inform healthcare providers about the reaction.",
86
+ 'gastroesophageal reflux disease': "Follow dietary changes, avoid large meals, and consider medications. Consult a doctor for personalized management.",
87
+ 'peptic ulcer disease': "Avoid spicy and acidic foods, take prescribed medications, and manage stress. Consult a gastroenterologist for guidance.",
88
+ 'urinary tract infection': "Stay hydrated, take prescribed antibiotics, and maintain good hygiene. Consult a doctor for appropriate treatment."
89
+ }
90
+
91
+ howto= """Welcome to the <b>Medical Chatbot</b>, powered by Gradio.
92
+ Currently, the chatbot can WELCOME YOU, PREDICT DISEASE based on your symptoms and SUGGEST POSSIBLE SOLUTIONS AND RECOMENDATIONS, and BID YOU FAREWELL.
93
+ <br><br>
94
+ Here's a quick guide to get you started:<br><br>
95
+ <b>How to Start:</b> Simply type your messages in the textbox to chat with the Chatbot and press enter!<br><br>
96
+ The bot will respond based on the best possible answers to your messages. For now, let's keep it SIMPLE as I'm working hard to enhance its capabilities in the future.
97
+
98
+ """
99
+
100
+
101
+ # Create the gradio demo
102
+ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
103
+ gr.HTML('<h1 align="center">Medical Chatbot: Your Virtual Health Guide 🌟πŸ₯πŸ€–"</h1>')
104
+ gr.HTML('<h3 align="center">To know more about this project click, <a href="https://github.com/Monsurat-Onabajo/Medical_chatbot" target="_blank">Here</a>')
105
+ with gr.Accordion("Follow these Steps to use the Gradio WebUI", open=True):
106
+ gr.HTML(howto)
107
+ chatbot = gr.Chatbot()
108
+ msg = gr.Textbox()
109
+ clear = gr.ClearButton([msg, chatbot])
110
+
111
+ def respond(message, chat_history):
112
+ # Random greetings in list format
113
+ greetings = [
114
+ "hello!",'hello', 'hii !', 'hi', "hi there!", "hi there!", "heyy", 'good morning', 'good afternoon', 'good evening'
115
+ "hey", "how are you", "how are you?", "how is it going", "how is it going?",
116
+ "what's up?", "how are you?",
117
+ "hey, how are you?", "what is popping"
118
+ "good to see you!", "howdy!",
119
+ "hi, nice to meet you.", "hiya!",
120
+ "hi", "hi, what's new?",
121
+ "hey, how's your day?", "hi, how have you been?", "greetings",
122
+ ]
123
+ # Random Greetings responses
124
+ responses = [
125
+ "Thank you for using our medical chatbot. Please provide the symptoms you're experiencing, and I'll do my best to predict the possible disease.",
126
+ "Hello! I'm here to help you with medical predictions based on your symptoms. Please describe your symptoms in as much detail as possible.",
127
+ "Greetings! I am a specialized medical chatbot trained to predict potential diseases based on the symptoms you provide. Kindly list your symptoms explicitly.",
128
+ "Welcome to the medical chatbot. To assist you accurately, please share your symptoms in explicit detail.",
129
+ "Hi there! I'm a medical chatbot specialized in analyzing symptoms to suggest possible diseases. Please provide your symptoms explicitly.",
130
+ "Hey! I'm your medical chatbot. Describe your symptoms with as much detail as you can, and I'll generate potential disease predictions.",
131
+ "How can I assist you today? I'm a medical chatbot trained to predict diseases based on symptoms. Please be explicit while describing your symptoms.",
132
+ "Hello! I'm a medical chatbot capable of predicting diseases based on the symptoms you provide. Your explicit symptom description will help me assist you better.",
133
+ "Greetings! I'm here to help with medical predictions. Describe your symptoms explicitly, and I'll offer insights into potential diseases.",
134
+ "Hi, I'm the medical chatbot. I've been trained to predict diseases from symptoms. The more explicit you are about your symptoms, the better I can assist you.",
135
+ "Hi, I specialize in medical predictions based on symptoms. Kindly provide detailed symptoms for accurate disease predictions.",
136
+ "Hello! I'm a medical chatbot with expertise in predicting diseases from symptoms. Please describe your symptoms explicitly to receive accurate insights.",
137
+ ]
138
+ # Random goodbyes
139
+ goodbyes = [
140
+ "farewell!",'bye', 'goodbye','good-bye', 'good bye', 'bye', 'thank you', 'later', "take care!",
141
+ "see you later!", 'see you', 'see ya', 'see-you', 'thanks', 'thank', 'bye bye', 'byebye'
142
+ "catch you on the flip side!", "adios!",
143
+ "goodbye for now!", "till we meet again!",
144
+ "so long!", "hasta la vista!",
145
+ "bye-bye!", "keep in touch!",
146
+ "toodles!", "ciao!",
147
+ "later, gator!", "stay safe and goodbye!",
148
+ "peace out!", "until next time!", "off I go!",
149
+ ]
150
+ # Random Goodbyes responses
151
+ goodbye_replies = [
152
+ "Take care of yourself! If you have more questions, don't hesitate to reach out.",
153
+ "Stay well! Remember, I'm here if you need further medical advice.",
154
+ "Goodbye for now! Don't hesitate to return if you need more information in the future.",
155
+ "Wishing you good health ahead! Feel free to come back if you have more concerns.",
156
+ "Farewell! If you have more symptoms or questions, don't hesitate to consult again.",
157
+ "Take care and stay informed about your health. Feel free to chat anytime.",
158
+ "Bye for now! Remember, your well-being is a priority. Don't hesitate to ask if needed.",
159
+ "Have a great day ahead! If you need medical guidance later on, I'll be here.",
160
+ "Stay well and take it easy! Reach out if you need more medical insights.",
161
+ "Until next time! Prioritize your health and reach out if you need assistance.",
162
+ "Goodbye! Your health matters. Feel free to return if you have more health-related queries.",
163
+ "Stay healthy and stay curious about your health! If you need more info, just ask.",
164
+ "Wishing you wellness on your journey! If you have more questions, I'm here to help.",
165
+ "Take care and remember, your health is important. Don't hesitate to reach out if needed.",
166
+ "Goodbye for now! Stay informed and feel free to consult if you require medical advice.",
167
+ "Stay well and stay proactive about your health! If you have more queries, feel free to ask.",
168
+ "Farewell! Remember, I'm here whenever you need reliable medical information.",
169
+ "Bye for now! Stay vigilant about your health and don't hesitate to return if necessary.",
170
+ "Take care and keep your well-being a priority! Reach out if you have more health questions.",
171
+ "Wishing you good health ahead! Don't hesitate to chat if you need medical insights.",
172
+ "Goodbye! Stay well and remember, I'm here to assist you with medical queries.",
173
+ ]
174
+
175
+ # Create couple of if-else statements to capture/mimick peoples's Interaction
176
+ if message.lower() in greetings:
177
+ bot_message= random.choice(responses)
178
+ elif message.lower() in goodbyes:
179
+ bot_message= random.choice(goodbye_replies)
180
+ else:
181
+ transform_text= vectorizer.transform([message])
182
+ transform_text= torch.tensor(transform_text.toarray()).to(torch.float32)
183
+ model.eval()
184
+ with torch.inference_mode():
185
+ y_logits=model(transform_text)
186
+ pred_prob= torch.argmax(torch.softmax(y_logits, dim=1), dim=1)
187
+
188
+ test_pred= class_names[pred_prob.item()]
189
+ bot_message = f' Based on your symptoms, I believe you are having {test_pred} and I would advice you {disease_advice[test_pred]}'
190
+ chat_history.append((message, bot_message))
191
+ time.sleep(2)
192
+ return "", chat_history
193
+
194
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
195
+ # Launch the demo
196
+ demo.launch()
197
+