Files changed (1) hide show
  1. app_phi2.py +196 -0
app_phi2.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import and class names setup
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+ import random
6
+ import nltk_u
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_u.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
+ # Disease Advice
62
+ disease_advice = {
63
+ '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.",
64
+ 'Arthritis': "Stay active with gentle exercises, manage weight, and consider pain-relief strategies like hot/cold therapy. Consult a rheumatologist for tailored guidance.",
65
+ '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.",
66
+ 'Cervical spondylosis': "Maintain good posture, do neck exercises, and use ergonomic support. Physical therapy and pain management techniques might be helpful.",
67
+ 'Chicken pox': "Rest, maintain hygiene, and avoid scratching. Consult a doctor for appropriate antiviral treatment.",
68
+ '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.",
69
+ 'Dengue': "Stay hydrated, rest, and manage fever with acetaminophen. Seek medical care promptly, as dengue can escalate quickly.",
70
+ 'Dimorphic Hemorrhoids': "Follow a high-fiber diet, maintain good hygiene, and consider stool softeners. Consult a doctor if symptoms persist.",
71
+ 'Fungal infection': "Keep the affected area clean and dry, use antifungal creams, and avoid sharing personal items. Consult a dermatologist if it persists.",
72
+ 'Hypertension': "Follow a balanced diet, exercise regularly, reduce salt intake, and take prescribed medications. Regular check-ups with a healthcare provider are important.",
73
+ 'Impetigo': "Keep the affected area clean, use prescribed antibiotics, and avoid close contact. Consult a doctor for proper treatment.",
74
+ 'Jaundice': "Get plenty of rest, maintain hydration, and follow a doctor's advice for diet and medications. Regular monitoring is important.",
75
+ 'Malaria': "Take prescribed antimalarial medications, rest, and manage fever. Seek medical attention for severe cases.",
76
+ 'Migraine': "Identify triggers, manage stress, and consider pain-relief medications. Consult a neurologist for personalized management.",
77
+ 'Pneumonia': "Follow prescribed antibiotics, rest, stay hydrated, and monitor symptoms. Seek immediate medical attention for severe cases.",
78
+ 'Psoriasis': "Moisturize, use prescribed creams, and avoid triggers. Consult a dermatologist for effective management.",
79
+ 'Typhoid': "Take prescribed antibiotics, rest, and stay hydrated. Dietary precautions are important. Consult a doctor for proper treatment.",
80
+ 'Varicose Veins': "Elevate legs, exercise regularly, and wear compression stockings. Consult a vascular specialist for evaluation and treatment options.",
81
+ 'allergy': "Identify triggers, manage exposure, and consider antihistamines. Consult an allergist for comprehensive management.",
82
+ 'diabetes': "Follow a balanced diet, exercise, monitor blood sugar levels, and take prescribed medications. Regular visits to an endocrinologist are essential.",
83
+ 'drug reaction': "Discontinue the suspected medication, seek medical attention if symptoms are severe, and inform healthcare providers about the reaction.",
84
+ 'gastroesophageal reflux disease': "Follow dietary changes, avoid large meals, and consider medications. Consult a doctor for personalized management.",
85
+ 'peptic ulcer disease': "Avoid spicy and acidic foods, take prescribed medications, and manage stress. Consult a gastroenterologist for guidance.",
86
+ 'urinary tract infection': "Stay hydrated, take prescribed antibiotics, and maintain good hygiene. Consult a doctor for appropriate treatment."
87
+ }
88
+
89
+ howto= """Welcome to the <b>Medical Chatbot</b>, powered by Gradio.
90
+ Currently, the chatbot can WELCOME YOU, PREDICT DISEASE based on your symptoms and SUGGEST POSSIBLE SOLUTIONS AND RECOMENDATIONS, and BID YOU FAREWELL.
91
+ <b>How to Start:</b> Simply type your messages in the textbox to chat with the Chatbot and press enter!<br><br>
92
+ The bot will respond based on the best possible answers to your messages.
93
+ """
94
+
95
+
96
+ # Create the gradio demo
97
+ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
98
+ gr.HTML('<h1 align="center">Medical Chatbot: ARIN 7102')
99
+ #gr.HTML('<h3 align="center">To know more about this project')
100
+ with gr.Accordion("Follow these Steps to use the Gradio WebUI", open=True):
101
+ gr.HTML(howto)
102
+ chatbot = gr.Chatbot()
103
+ msg = gr.Textbox()
104
+ clear = gr.ClearButton([msg, chatbot])
105
+
106
+ def respond(message, chat_history):
107
+ # Random greetings in list format
108
+ greetings = [
109
+ "hello!",'hello', 'hii !', 'hi', "hi there!", "hi there!", "heyy", 'good morning', 'good afternoon', 'good evening'
110
+ "hey", "how are you", "how are you?", "how is it going", "how is it going?",
111
+ "what's up?", "how are you?",
112
+ "hey, how are you?", "what is popping"
113
+ "good to see you!", "howdy!",
114
+ "hi, nice to meet you.", "hiya!",
115
+ "hi", "hi, what's new?",
116
+ "hey, how's your day?", "hi, how have you been?", "greetings",
117
+ ]
118
+ # Random Greetings responses
119
+ responses = [
120
+ "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.",
121
+ "Hello! I'm here to help you with medical predictions based on your symptoms. Please describe your symptoms in as much detail as possible.",
122
+ "Greetings! I am a specialized medical chatbot trained to predict potential diseases based on the symptoms you provide. Kindly list your symptoms explicitly.",
123
+ "Welcome to the medical chatbot. To assist you accurately, please share your symptoms in explicit detail.",
124
+ "Hi there! I'm a medical chatbot specialized in analyzing symptoms to suggest possible diseases. Please provide your symptoms explicitly.",
125
+ "Hey! I'm your medical chatbot. Describe your symptoms with as much detail as you can, and I'll generate potential disease predictions.",
126
+ "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.",
127
+ "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.",
128
+ "Greetings! I'm here to help with medical predictions. Describe your symptoms explicitly, and I'll offer insights into potential diseases.",
129
+ "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.",
130
+ "Hi, I specialize in medical predictions based on symptoms. Kindly provide detailed symptoms for accurate disease predictions.",
131
+ "Hello! I'm a medical chatbot with expertise in predicting diseases from symptoms. Please describe your symptoms explicitly to receive accurate insights.",
132
+ ]
133
+ # Random goodbyes
134
+ goodbyes = [
135
+ "farewell!",'bye', 'goodbye','good-bye', 'good bye', 'bye', 'thank you', 'later', "take care!",
136
+ "see you later!", 'see you', 'see ya', 'see-you', 'thanks', 'thank', 'bye bye', 'byebye'
137
+ "catch you on the flip side!", "adios!",
138
+ "goodbye for now!", "till we meet again!",
139
+ "so long!", "hasta la vista!",
140
+ "bye-bye!", "keep in touch!",
141
+ "toodles!", "ciao!",
142
+ "later, gator!", "stay safe and goodbye!",
143
+ "peace out!", "until next time!", "off I go!",
144
+ ]
145
+ # Random Goodbyes responses
146
+ goodbye_replies = [
147
+ "Take care of yourself! If you have more questions, don't hesitate to reach out.",
148
+ "Stay well! Remember, I'm here if you need further medical advice.",
149
+ "Goodbye for now! Don't hesitate to return if you need more information in the future.",
150
+ "Wishing you good health ahead! Feel free to come back if you have more concerns.",
151
+ "Farewell! If you have more symptoms or questions, don't hesitate to consult again.",
152
+ "Take care and stay informed about your health. Feel free to chat anytime.",
153
+ "Bye for now! Remember, your well-being is a priority. Don't hesitate to ask if needed.",
154
+ "Have a great day ahead! If you need medical guidance later on, I'll be here.",
155
+ "Stay well and take it easy! Reach out if you need more medical insights.",
156
+ "Until next time! Prioritize your health and reach out if you need assistance.",
157
+ "Goodbye! Your health matters. Feel free to return if you have more health-related queries.",
158
+ "Stay healthy and stay curious about your health! If you need more info, just ask.",
159
+ "Wishing you wellness on your journey! If you have more questions, I'm here to help.",
160
+ "Take care and remember, your health is important. Don't hesitate to reach out if needed.",
161
+ "Goodbye for now! Stay informed and feel free to consult if you require medical advice.",
162
+ "Stay well and stay proactive about your health! If you have more queries, feel free to ask.",
163
+ "Farewell! Remember, I'm here whenever you need reliable medical information.",
164
+ "Bye for now! Stay vigilant about your health and don't hesitate to return if necessary.",
165
+ "Take care and keep your well-being a priority! Reach out if you have more health questions.",
166
+ "Wishing you good health ahead! Don't hesitate to chat if you need medical insights.",
167
+ "Goodbye! Stay well and remember, I'm here to assist you with medical queries.",
168
+ ]
169
+
170
+ # Create couple of if-else statements to capture/mimick peoples's Interaction
171
+
172
+ if message.lower() in greetings:
173
+ bot_message= random.choice(responses)
174
+ elif message.lower() in goodbyes:
175
+ bot_message= random.choice(goodbye_replies)
176
+ else:
177
+ #bot_message= random.choice(goodbye_replies)
178
+
179
+ transform_text= vectorizer.transform([message])
180
+ transform_text= torch.tensor(transform_text.toarray()).to(torch.float32)
181
+ model.eval()
182
+ with torch.inference_mode():
183
+ y_logits=model(transform_text)
184
+ pred_prob= torch.argmax(torch.softmax(y_logits, dim=1), dim=1)
185
+
186
+ test_pred= class_names[pred_prob.item()]
187
+ bot_message = f' Based on your symptoms, I believe you are having {test_pred} and I would advice you {disease_advice[test_pred]}'
188
+ chat_history.append((message, bot_message))
189
+ time.sleep(2)
190
+ return "", chat_history
191
+
192
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
193
+
194
+
195
+ # Launch the demo
196
+ demo.launch()