henry2024 commited on
Commit
40ee52c
1 Parent(s): 009de29
Files changed (6) hide show
  1. Symptom2Disease.csv +0 -0
  2. a.py +7 -0
  3. app.py +201 -0
  4. model.py +17 -0
  5. nltk_u.py +24 -0
  6. pretrained_symtom_to_disease_model.pth +3 -0
Symptom2Disease.csv ADDED
The diff for this file is too large to render. See raw diff
 
a.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def greet(name):
4
+ return "Hello " + name + "!!"
5
+
6
+ iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
+ iface.launch()
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 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
+ <br><br>
92
+ Here's a quick guide to get you started:<br><br>
93
+ <b>How to Start:</b> Simply type your messages in the textbox to chat with the Chatbot and press enter!<br><br>
94
+ 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.
95
+
96
+ """
97
+
98
+
99
+ # Create the gradio demo
100
+ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
101
+ gr.HTML('<h1 align="center">Medical Chatbot: Your Virtual Health Guide 🌟🏥🤖"</h1>')
102
+ 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>')
103
+ with gr.Accordion("Follow these Steps to use the Gradio WebUI", open=True):
104
+ gr.HTML(howto)
105
+ chatbot = gr.Chatbot()
106
+ msg = gr.Textbox()
107
+ clear = gr.ClearButton([msg, chatbot])
108
+
109
+ def respond(message, chat_history):
110
+ # Random greetings in list format
111
+ greetings = [
112
+ "hello!",'hello', 'hii !', 'hi', "hi there!", "hi there!", "heyy", 'good morning', 'good afternoon', 'good evening'
113
+ "hey", "how are you", "how are you?", "how is it going", "how is it going?",
114
+ "what's up?", "how are you?",
115
+ "hey, how are you?", "what is popping"
116
+ "good to see you!", "howdy!",
117
+ "hi, nice to meet you.", "hiya!",
118
+ "hi", "hi, what's new?",
119
+ "hey, how's your day?", "hi, how have you been?", "greetings",
120
+ ]
121
+ # Random Greetings responses
122
+ responses = [
123
+ "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.",
124
+ "Hello! I'm here to help you with medical predictions based on your symptoms. Please describe your symptoms in as much detail as possible.",
125
+ "Greetings! I am a specialized medical chatbot trained to predict potential diseases based on the symptoms you provide. Kindly list your symptoms explicitly.",
126
+ "Welcome to the medical chatbot. To assist you accurately, please share your symptoms in explicit detail.",
127
+ "Hi there! I'm a medical chatbot specialized in analyzing symptoms to suggest possible diseases. Please provide your symptoms explicitly.",
128
+ "Hey! I'm your medical chatbot. Describe your symptoms with as much detail as you can, and I'll generate potential disease predictions.",
129
+ "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.",
130
+ "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.",
131
+ "Greetings! I'm here to help with medical predictions. Describe your symptoms explicitly, and I'll offer insights into potential diseases.",
132
+ "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.",
133
+ "Hi, I specialize in medical predictions based on symptoms. Kindly provide detailed symptoms for accurate disease predictions.",
134
+ "Hello! I'm a medical chatbot with expertise in predicting diseases from symptoms. Please describe your symptoms explicitly to receive accurate insights.",
135
+ ]
136
+ # Random goodbyes
137
+ goodbyes = [
138
+ "farewell!",'bye', 'goodbye','good-bye', 'good bye', 'bye', 'thank you', 'later', "take care!",
139
+ "see you later!", 'see you', 'see ya', 'see-you', 'thanks', 'thank', 'bye bye', 'byebye'
140
+ "catch you on the flip side!", "adios!",
141
+ "goodbye for now!", "till we meet again!",
142
+ "so long!", "hasta la vista!",
143
+ "bye-bye!", "keep in touch!",
144
+ "toodles!", "ciao!",
145
+ "later, gator!", "stay safe and goodbye!",
146
+ "peace out!", "until next time!", "off I go!",
147
+ ]
148
+ # Random Goodbyes responses
149
+ goodbye_replies = [
150
+ "Take care of yourself! If you have more questions, don't hesitate to reach out.",
151
+ "Stay well! Remember, I'm here if you need further medical advice.",
152
+ "Goodbye for now! Don't hesitate to return if you need more information in the future.",
153
+ "Wishing you good health ahead! Feel free to come back if you have more concerns.",
154
+ "Farewell! If you have more symptoms or questions, don't hesitate to consult again.",
155
+ "Take care and stay informed about your health. Feel free to chat anytime.",
156
+ "Bye for now! Remember, your well-being is a priority. Don't hesitate to ask if needed.",
157
+ "Have a great day ahead! If you need medical guidance later on, I'll be here.",
158
+ "Stay well and take it easy! Reach out if you need more medical insights.",
159
+ "Until next time! Prioritize your health and reach out if you need assistance.",
160
+ "Goodbye! Your health matters. Feel free to return if you have more health-related queries.",
161
+ "Stay healthy and stay curious about your health! If you need more info, just ask.",
162
+ "Wishing you wellness on your journey! If you have more questions, I'm here to help.",
163
+ "Take care and remember, your health is important. Don't hesitate to reach out if needed.",
164
+ "Goodbye for now! Stay informed and feel free to consult if you require medical advice.",
165
+ "Stay well and stay proactive about your health! If you have more queries, feel free to ask.",
166
+ "Farewell! Remember, I'm here whenever you need reliable medical information.",
167
+ "Bye for now! Stay vigilant about your health and don't hesitate to return if necessary.",
168
+ "Take care and keep your well-being a priority! Reach out if you have more health questions.",
169
+ "Wishing you good health ahead! Don't hesitate to chat if you need medical insights.",
170
+ "Goodbye! Stay well and remember, I'm here to assist you with medical queries.",
171
+ ]
172
+
173
+ # Create couple of if-else statements to capture/mimick peoples's Interaction
174
+
175
+ if message.lower() in greetings:
176
+ bot_message= random.choice(responses)
177
+ elif message.lower() in goodbyes:
178
+ bot_message= random.choice(goodbye_replies)
179
+ else:
180
+ bot_message= random.choice(goodbye_replies)
181
+ '''
182
+ else:
183
+ transform_text= vectorizer.transform([message])
184
+ transform_text= torch.tensor(transform_text.toarray()).to(torch.float32)
185
+ model.eval()
186
+ with torch.inference_mode():
187
+ y_logits=model(transform_text)
188
+ pred_prob= torch.argmax(torch.softmax(y_logits, dim=1), dim=1)
189
+
190
+ test_pred= class_names[pred_prob.item()]
191
+ bot_message = f' Based on your symptoms, I believe you are having {test_pred} and I would advice you {disease_advice[test_pred]}'
192
+ chat_history.append((message, bot_message))
193
+ time.sleep(2)
194
+ return "", chat_history
195
+ '''
196
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
197
+
198
+
199
+ # Launch the demo
200
+ demo.launch()
201
+
model.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+ class RNN_model(nn.Module):
5
+ def __init__(self):
6
+ super().__init__()
7
+
8
+ self.rnn= nn.RNN(input_size=1080, hidden_size=240,num_layers=1, nonlinearity= 'relu', bias= True)
9
+ self.output= nn.Linear(in_features=240, out_features=24)
10
+
11
+ def forward(self, x):
12
+ y, hidden= self.rnn(x)
13
+ #print(y.shape)
14
+ #print(hidden.shape)
15
+ x= self.output(y)
16
+
17
+ return(x)
nltk_u.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import Libraries
2
+ import nltk
3
+ from nltk.tokenize import word_tokenize
4
+ nltk.download('punkt')
5
+ from sklearn.feature_extraction.text import TfidfVectorizer
6
+ from nltk.stem import SnowballStemmer
7
+ stemmer= SnowballStemmer(language= 'english')
8
+ from nltk.corpus import stopwords
9
+ nltk.download('stopwords')
10
+
11
+ # Tokenize text i.e make all text be in a list format e.g "I am sick" = ['i', 'am', 'sick']
12
+ def tokenize(text):
13
+ return [stemmer.stem(token) for token in word_tokenize(text)]
14
+
15
+ # Create stopwords to reduce noise in data
16
+ english_stopwords= stopwords.words('english')
17
+
18
+ # Create a vectosizer to learn all words in order to convert them into numbers
19
+ def vectorizer():
20
+ vectorizer= TfidfVectorizer(tokenizer=tokenize,
21
+ stop_words=english_stopwords,
22
+ )
23
+ return vectorizer
24
+
pretrained_symtom_to_disease_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d182949722a706bed0e7c6319bb893eccc31f8d2b502d023750e0beafd5da8fe
3
+ size 1294703