Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +160 -212
- gru_model.pth +3 -0
app.py
CHANGED
@@ -1,124 +1,89 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
3 |
import os
|
4 |
import torch
|
|
|
5 |
import random
|
6 |
-
import
|
7 |
import pandas as pd
|
8 |
from sklearn.model_selection import train_test_split
|
9 |
import time
|
10 |
-
#from model import RNN_model
|
11 |
from timeit import default_timer as timer
|
12 |
from typing import Tuple, Dict
|
13 |
-
|
14 |
-
|
15 |
-
import
|
16 |
-
|
17 |
-
import
|
18 |
-
import
|
19 |
-
import
|
20 |
-
|
21 |
-
from typing import Dict, Sequence
|
22 |
-
from sentence_transformers import SentenceTransformer
|
23 |
-
import torch
|
24 |
-
from modeling_phi import PhiForCausalLM
|
25 |
-
from tokenization_codegen import CodeGenTokenizer
|
26 |
-
from transformers import PhiForCausalLM, AutoTokenizer, AutoModelForCausalLM
|
27 |
-
################################################################################
|
28 |
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
parser.add_argument('--output_path', type=str, default="/home/henry/Desktop/HKU-DASC7606-A2/Outputs/ARC-Challenge-test", help="") ## -bge-m3
|
36 |
-
parser.add_argument('--start_index', type=int, default=0, help="")
|
37 |
-
parser.add_argument('--end_index', type=int, default=9999, help="")
|
38 |
-
parser.add_argument('--N', type=int, default=8, help="")
|
39 |
-
parser.add_argument('--max_len', type=int, default=1024, help="")
|
40 |
-
parser.add_argument('--prompt_type', type=str, default="v2.0", help="")
|
41 |
-
parser.add_argument('--top_k', type=str2bool, default=True, help="")
|
42 |
-
#############################################################################################################################
|
43 |
-
args = parser.parse_args()
|
44 |
-
if torch.cuda.is_available():
|
45 |
-
device = "cuda"
|
46 |
-
print(f'################################################################# device: {device}#################################################################')
|
47 |
-
else:
|
48 |
-
device = "cpu"
|
49 |
-
def get_model(base_model: str = "bigcode/starcoder",):
|
50 |
-
tokenizer = CodeGenTokenizer.from_pretrained(base_model)
|
51 |
-
tokenizer.pad_token_id = tokenizer.eos_token_id
|
52 |
-
tokenizer.pad_token = tokenizer.eos_token
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
device_map="auto",)
|
57 |
-
model.config.pad_token_id = tokenizer.pad_token_id
|
58 |
-
model.eval()
|
59 |
-
return tokenizer, model
|
60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
class GRU_model(nn.Module):
|
63 |
def __init__(self):
|
64 |
super().__init__()
|
65 |
|
66 |
-
self.rnn= nn.GRU(input_size=
|
67 |
-
self.output= nn.Linear(in_features=240, out_features=24)
|
68 |
|
69 |
def forward(self, x):
|
70 |
y, hidden= self.rnn(x)
|
71 |
-
|
72 |
-
|
73 |
-
x= self.output(y)
|
74 |
-
|
75 |
return(x)
|
76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
# Import data
|
78 |
-
df= pd.read_csv('
|
79 |
-
df.drop('Unnamed: 0', axis= 1, inplace= True)
|
80 |
|
81 |
# Preprocess data
|
|
|
82 |
df.drop_duplicates(inplace= True)
|
83 |
-
train_data, test_data= train_test_split(df, test_size=0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
# Setup class names
|
85 |
-
class_names= {0: 'Acne',
|
86 |
-
|
87 |
-
|
88 |
-
3: 'Cervical spondylosis',
|
89 |
-
4: 'Chicken pox',
|
90 |
-
5: 'Common Cold',
|
91 |
-
6: 'Dengue',
|
92 |
-
7: 'Dimorphic Hemorrhoids',
|
93 |
-
8: 'Fungal infection',
|
94 |
-
9: 'Hypertension',
|
95 |
-
10: 'Impetigo',
|
96 |
-
11: 'Jaundice',
|
97 |
-
12: 'Malaria',
|
98 |
-
13: 'Migraine',
|
99 |
-
14: 'Pneumonia',
|
100 |
-
15: 'Psoriasis',
|
101 |
-
16: 'Typhoid',
|
102 |
-
17: 'Varicose Veins',
|
103 |
-
18: 'allergy',
|
104 |
-
19: 'diabetes',
|
105 |
-
20: 'drug reaction',
|
106 |
-
21: 'gastroesophageal reflux disease',
|
107 |
-
22: 'peptic ulcer disease',
|
108 |
-
23: 'urinary tract infection'
|
109 |
-
}
|
110 |
-
|
111 |
-
vectorizer= nltk_u.vectorizer()
|
112 |
-
vectorizer.fit(train_data.text)
|
113 |
-
|
114 |
-
# Model and transforms preparation
|
115 |
-
model= GRU_model()
|
116 |
-
# Load state dict
|
117 |
-
model.load_state_dict(torch.load(
|
118 |
-
f= 'pretrained_symtom_to_disease_model.pth',
|
119 |
-
map_location= torch.device('cpu')
|
120 |
-
)
|
121 |
-
)
|
122 |
# Disease Advice
|
123 |
disease_advice = {
|
124 |
'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.",
|
@@ -147,123 +112,84 @@ disease_advice = {
|
|
147 |
'urinary tract infection': "Stay hydrated, take prescribed antibiotics, and maintain good hygiene. Consult a doctor for appropriate treatment."
|
148 |
}
|
149 |
|
150 |
-
'''
|
151 |
-
# Import data
|
152 |
-
df= pd.read_csv('Symptom2Disease.csv')
|
153 |
-
df.drop('Unnamed: 0', axis= 1, inplace= True)
|
154 |
-
|
155 |
-
# Preprocess data
|
156 |
-
df.drop_duplicates(inplace= True)
|
157 |
-
train_data, test_data= train_test_split(df, test_size=0.15, random_state=42 )
|
158 |
-
'''
|
159 |
-
|
160 |
howto= """Welcome to the <b>Medical Chatbot</b>, powered by Gradio.
|
161 |
Currently, the chatbot can WELCOME YOU, PREDICT DISEASE based on your symptoms and SUGGEST POSSIBLE SOLUTIONS AND RECOMENDATIONS, and BID YOU FAREWELL.
|
162 |
<b>How to Start:</b> Simply type your messages in the textbox to chat with the Chatbot and press enter!<br><br>
|
163 |
-
The bot will respond based on the best possible answers to your messages.
|
|
|
164 |
|
165 |
-
"""
|
166 |
# Create the gradio demo
|
167 |
with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
bot_message = model(message_embeddings)
|
182 |
-
chat_history.append((message, bot_message))
|
183 |
-
time.sleep(2)
|
184 |
-
return "", chat_history
|
185 |
-
'''
|
186 |
-
def respond(message, chat_history, base_model = "self_GRU", device=device): # "meta-llama/Meta-Llama-3-70B"
|
187 |
-
if base_model != "microsoft/phi-2":
|
188 |
# Random greetings in list format
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
"
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
"
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
"Stay well and stay proactive about your health! If you have more queries, feel free to ask.",
|
244 |
-
"Farewell! Remember, I'm here whenever you need reliable medical information.",
|
245 |
-
"Bye for now! Stay vigilant about your health and don't hesitate to return if necessary.",
|
246 |
-
"Take care and keep your well-being a priority! Reach out if you have more health questions.",
|
247 |
-
"Wishing you good health ahead! Don't hesitate to chat if you need medical insights.",
|
248 |
-
"Goodbye! Stay well and remember, I'm here to assist you with medical queries.",
|
249 |
-
]
|
250 |
-
|
251 |
-
# Create couple of if-else statements to capture/mimick peoples's Interaction
|
252 |
-
if message.lower() in greetings:
|
253 |
-
bot_message= random.choice(responses)
|
254 |
-
elif message.lower() in goodbyes:
|
255 |
-
bot_message= random.choice(goodbye_replies)
|
256 |
else:
|
257 |
-
|
258 |
-
transform_text= torch.tensor(transform_text.toarray()).to(torch.float32)
|
259 |
-
model.eval()
|
260 |
-
with torch.inference_mode():
|
261 |
-
y_logits=model(transform_text)
|
262 |
-
pred_prob= torch.argmax(torch.softmax(y_logits, dim=1), dim=1)
|
263 |
-
|
264 |
-
test_pred= class_names[pred_prob.item()]
|
265 |
-
bot_message = f' Based on your symptoms, I believe you are having {test_pred} and I would advice you {disease_advice[test_pred]}'
|
266 |
-
else:
|
267 |
# define the model and tokenizer.
|
268 |
# model = PhiForCausalLM.from_pretrained(base_model)
|
269 |
model = AutoModelForCausalLM.from_pretrained(base_model)
|
@@ -273,13 +199,14 @@ def respond(message, chat_history, base_model = "self_GRU", device=device): # "m
|
|
273 |
#prompt = f"Patient: coercive spondylitis, pain in the lumbosacral area when turning over during sleep at night, no pain in any other part of the body.
|
274 |
#/n Doctor: It shouldn't be a problem, but it's better to upload the images. /n Patient: {message} /n Doctor:"
|
275 |
output_termination = "\nOutput:"
|
276 |
-
prompt = f"Instruct: {message}{output_termination}"
|
|
|
277 |
# apply the tokenizer.
|
278 |
tokens = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)
|
279 |
#tokens = tokens.to(device)
|
280 |
#eos_token_id = tokenizer.eos_token_id
|
281 |
# use the model to generate new tokens.
|
282 |
-
generated_output = model.generate(**tokens, use_cache=True, max_new_tokens=
|
283 |
|
284 |
# Find the position of "Output:" and extract the text after it
|
285 |
generated_text = tokenizer.batch_decode(generated_output)[0]
|
@@ -287,12 +214,33 @@ def respond(message, chat_history, base_model = "self_GRU", device=device): # "m
|
|
287 |
split_text = generated_text.split("Output:", 1)
|
288 |
bot_message = split_text[1].strip() if len(split_text) > 1 else ""
|
289 |
bot_message = bot_message.replace("<|endoftext|>", "").strip()
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
|
|
|
|
|
|
|
|
294 |
|
295 |
-
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
296 |
|
|
|
297 |
# Launch the demo
|
298 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
import locale
|
4 |
+
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
|
5 |
+
import accelerate
|
6 |
+
from sentence_transformers import SentenceTransformer
|
7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
8 |
import os
|
9 |
import torch
|
10 |
+
from torch import nn
|
11 |
import random
|
12 |
+
import gradio as gr
|
13 |
import pandas as pd
|
14 |
from sklearn.model_selection import train_test_split
|
15 |
import time
|
|
|
16 |
from timeit import default_timer as timer
|
17 |
from typing import Tuple, Dict
|
18 |
+
'''
|
19 |
+
import nltk
|
20 |
+
import nltk_u
|
21 |
+
from nltk.corpus import stopwords
|
22 |
+
from nltk.stem import SnowballStemmer
|
23 |
+
from nltk.tokenize import word_tokenize
|
24 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
25 |
+
'''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
#########################################################################################################################
|
28 |
+
'''
|
29 |
+
nltk.download('punkt')
|
30 |
+
nltk.download('stopwords')
|
31 |
+
stemmer= SnowballStemmer(language= 'english')
|
32 |
|
33 |
+
# Tokenize text, e.g "I am sick" = ['i', 'am', 'sick']
|
34 |
+
def tokenize(text):
|
35 |
+
return [stemmer.stem(token) for token in word_tokenize(text)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
+
# Create stopwords to reduce noise
|
38 |
+
english_stopwords= stopwords.words('english')
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
# Create a vectosizer to learn all words in order to convert them into numbers
|
41 |
+
def vectorizer():
|
42 |
+
vectorizer= TfidfVectorizer(tokenizer=tokenize, stop_words=english_stopwords)
|
43 |
+
return vectorizer
|
44 |
+
'''
|
45 |
+
#########################################################################################################################
|
46 |
|
47 |
class GRU_model(nn.Module):
|
48 |
def __init__(self):
|
49 |
super().__init__()
|
50 |
|
51 |
+
self.rnn= nn.GRU(input_size=384, hidden_size=240,num_layers=2, bias= True).to('cuda') ## nonlinearity= 'relu',
|
52 |
+
self.output= nn.Linear(in_features=240, out_features=24).to('cuda')
|
53 |
|
54 |
def forward(self, x):
|
55 |
y, hidden= self.rnn(x)
|
56 |
+
y = y.to('cuda')
|
57 |
+
x= self.output(y).to('cuda')
|
|
|
|
|
58 |
return(x)
|
59 |
+
embedder = SentenceTransformer("bge-small-en-v1.5", device="cuda")
|
60 |
+
#########################################################################################################################
|
61 |
+
if torch.cuda.is_available():
|
62 |
+
device = "cuda"
|
63 |
+
print(f'################################################################# device: {device}#################################################################')
|
64 |
+
else:
|
65 |
+
device = "cpu"
|
66 |
+
'''
|
67 |
# Import data
|
68 |
+
df= pd.read_csv('Symptom2Disease_1.csv')
|
|
|
69 |
|
70 |
# Preprocess data
|
71 |
+
df.drop('Unnamed: 0', axis= 1, inplace= True)
|
72 |
df.drop_duplicates(inplace= True)
|
73 |
+
train_data, test_data= train_test_split(df, test_size=0.2, random_state=1)
|
74 |
+
'''
|
75 |
+
#########################################################################################################################
|
76 |
+
#vectorizer = TfidfVectorizer(tokenizer=tokenize, stop_words=english_stopwords).fit(train_data.text)
|
77 |
+
#vectorizer= nltk_u.vectorizer()
|
78 |
+
#vectorizer.fit(train_data.text)
|
79 |
+
#from sklearn.feature_extraction.text import TfidfVectorizer
|
80 |
+
#from spacy.lang.de.stop_words import STOP_WORDS
|
81 |
+
#vectorizer = TfidfVectorizer(tokenizer=tokenize, stop_words=list(STOP_WORDS)).fit(train_data.text)
|
82 |
+
#########################################################################################################################
|
83 |
# Setup class names
|
84 |
+
class_names= {0: 'Acne', 1: 'Arthritis', 2: 'Bronchial Asthma', 3: 'Cervical spondylosis', 4: 'Chicken pox', 5: 'Common Cold', 6: 'Dengue', 7: 'Dimorphic Hemorrhoids', 8: 'Fungal infection', 9: 'Hypertension',
|
85 |
+
10: 'Impetigo', 11: 'Jaundice', 12: 'Malaria', 13: 'Migraine', 14: 'Pneumonia', 15: 'Psoriasis', 16: 'Typhoid', 17: 'Varicose Veins', 18: 'allergy', 19: 'diabetes', 20: 'drug reaction',
|
86 |
+
21: 'gastroesophageal reflux disease', 22: 'peptic ulcer disease', 23: 'urinary tract infection'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
# Disease Advice
|
88 |
disease_advice = {
|
89 |
'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.",
|
|
|
112 |
'urinary tract infection': "Stay hydrated, take prescribed antibiotics, and maintain good hygiene. Consult a doctor for appropriate treatment."
|
113 |
}
|
114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
howto= """Welcome to the <b>Medical Chatbot</b>, powered by Gradio.
|
116 |
Currently, the chatbot can WELCOME YOU, PREDICT DISEASE based on your symptoms and SUGGEST POSSIBLE SOLUTIONS AND RECOMENDATIONS, and BID YOU FAREWELL.
|
117 |
<b>How to Start:</b> Simply type your messages in the textbox to chat with the Chatbot and press enter!<br><br>
|
118 |
+
The bot will respond based on the best possible answers to your messages."""
|
119 |
+
|
120 |
|
|
|
121 |
# Create the gradio demo
|
122 |
with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
|
123 |
+
gr.HTML('<h1 align="center">Medical Chatbot: ARIN 7102 project')
|
124 |
+
with gr.Accordion("Follow these Steps to use the Gradio WebUI", open=True):
|
125 |
+
gr.HTML(howto)
|
126 |
+
chatbot = gr.Chatbot()
|
127 |
+
msg = gr.Textbox()
|
128 |
+
clear = gr.ClearButton([msg, chatbot])
|
129 |
+
def respond(message, chat_history, base_model = "gru_model", embedder = SentenceTransformer("bge-small-en-v1.5", device="cuda"), device='cuda'): # "meta-llama/Meta-Llama-3-70B"
|
130 |
+
#base_model =/home/henry/Desktop/ARIN7102/phi-2 # gru_model
|
131 |
+
if base_model == "gru_model":
|
132 |
+
# Model and transforms preparation
|
133 |
+
model= GRU_model()
|
134 |
+
# Load state dict
|
135 |
+
model.load_state_dict(torch.load(f= 'gru_model.pth', map_location= device))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
# Random greetings in list format
|
137 |
+
greetings = ["hello!",'hello', 'hii !', 'hi', "hi there!", "hi there!", "heyy", 'good morning', 'good afternoon', 'good evening', "hey", "how are you", "how are you?", "how is it going", "how is it going?", "what's up?",
|
138 |
+
"how are you?", "hey, how are you?", "what is popping", "good to see you!", "howdy!", "hi, nice to meet you.", "hiya!", "hi", "hi, what's new?", "hey, how's your day?", "hi, how have you been?", "greetings"]
|
139 |
+
# Random Greetings responses
|
140 |
+
greetings_responses = ["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.",
|
141 |
+
"Hello! I'm here to help you with medical predictions based on your symptoms. Please describe your symptoms in as much detail as possible.",
|
142 |
+
"Greetings! I am a specialized medical chatbot trained to predict potential diseases based on the symptoms you provide. Kindly list your symptoms explicitly.",
|
143 |
+
"Welcome to the medical chatbot. To assist you accurately, please share your symptoms in explicit detail.",
|
144 |
+
"Hi there! I'm a medical chatbot specialized in analyzing symptoms to suggest possible diseases. Please provide your symptoms explicitly.",
|
145 |
+
"Hey! I'm your medical chatbot. Describe your symptoms with as much detail as you can, and I'll generate potential disease predictions.",
|
146 |
+
"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.",
|
147 |
+
"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.",
|
148 |
+
"Greetings! I'm here to help with medical predictions. Describe your symptoms explicitly, and I'll offer insights into potential diseases.",
|
149 |
+
"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.",
|
150 |
+
"Hi, I specialize in medical predictions based on symptoms. Kindly provide detailed symptoms for accurate disease predictions.",
|
151 |
+
"Hello! I'm a medical chatbot with expertise in predicting diseases from symptoms. Please describe your symptoms explicitly to receive accurate insights."]
|
152 |
+
# Random goodbyes
|
153 |
+
goodbyes = ["farewell!",'bye', 'goodbye','good-bye', 'good bye', 'bye', 'thank you', 'later', "take care!",
|
154 |
+
"see you later!", 'see you', 'see ya', 'see-you', 'thanks', 'thank', 'bye bye', 'byebye'
|
155 |
+
"catch you on the flip side!", "adios!",
|
156 |
+
"goodbye for now!", "till we meet again!",
|
157 |
+
"so long!", "hasta la vista!",
|
158 |
+
"bye-bye!", "keep in touch!",
|
159 |
+
"toodles!", "ciao!",
|
160 |
+
"later, gator!", "stay safe and goodbye!",
|
161 |
+
"peace out!", "until next time!", "off I go!"]
|
162 |
+
# Random Goodbyes responses
|
163 |
+
goodbyes_replies = ["Take care of yourself! If you have more questions, don't hesitate to reach out.", "Stay well! Remember, I'm here if you need further medical advice.",
|
164 |
+
"Goodbye for now! Don't hesitate to return if you need more information in the future.", "Wishing you good health ahead! Feel free to come back if you have more concerns.",
|
165 |
+
"Farewell! If you have more symptoms or questions, don't hesitate to consult again.", "Take care and stay informed about your health. Feel free to chat anytime.",
|
166 |
+
"Bye for now! Remember, your well-being is a priority. Don't hesitate to ask if needed.", "Have a great day ahead! If you need medical guidance later on, I'll be here.",
|
167 |
+
"Stay well and take it easy! Reach out if you need more medical insights.", "Until next time! Prioritize your health and reach out if you need assistance.",
|
168 |
+
"Goodbye! Your health matters. Feel free to return if you have more health-related queries.", "Stay healthy and stay curious about your health! If you need more info, just ask.",
|
169 |
+
"Wishing you wellness on your journey! If you have more questions, I'm here to help.", "Stay well and stay proactive about your health! If you have more queries, feel free to ask.",
|
170 |
+
"Take care and remember, your health is important. Don't hesitate to reach out if needed.", "Goodbye for now! Stay informed and feel free to consult if you require medical advice.",
|
171 |
+
"Farewell! Remember, I'm here whenever you need reliable medical information.", "Bye for now! Stay vigilant about your health and don't hesitate to return if necessary.",
|
172 |
+
"Take care and keep your well-being a priority! Reach out if you have more health questions.", "Wishing you good health ahead! Don't hesitate to chat if you need medical insights.",
|
173 |
+
"Goodbye! Stay well and remember, I'm here to assist you with medical queries."]
|
174 |
+
|
175 |
+
if message.lower() in greetings:
|
176 |
+
bot_message= random.choice(greetings_responses)
|
177 |
+
elif message.lower() in goodbyes:
|
178 |
+
bot_message= random.choice(goodbyes_replies)
|
179 |
+
else:
|
180 |
+
#transform_text= vectorizer.transform([message])
|
181 |
+
sentence_embeddings = embedder.encode(message)
|
182 |
+
sentence_embeddings = torch.from_numpy(sentence_embeddings).float().to(device).unsqueeze(dim=0)
|
183 |
+
sentence_embeddings.shape
|
184 |
+
#transform_text= torch.tensor(transform_text.toarray()).to(torch.float32)
|
185 |
+
model.eval()
|
186 |
+
with torch.inference_mode():
|
187 |
+
y_logits=model(sentence_embeddings.to(device))
|
188 |
+
pred_prob= torch.argmax(torch.softmax(y_logits, dim=1), dim=1)
|
189 |
+
test_pred= class_names[pred_prob.item()]
|
190 |
+
bot_message = f' Based on your symptoms, I believe you are having {test_pred} and I would advice you {disease_advice[test_pred]}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
else:
|
192 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
# define the model and tokenizer.
|
194 |
# model = PhiForCausalLM.from_pretrained(base_model)
|
195 |
model = AutoModelForCausalLM.from_pretrained(base_model)
|
|
|
199 |
#prompt = f"Patient: coercive spondylitis, pain in the lumbosacral area when turning over during sleep at night, no pain in any other part of the body.
|
200 |
#/n Doctor: It shouldn't be a problem, but it's better to upload the images. /n Patient: {message} /n Doctor:"
|
201 |
output_termination = "\nOutput:"
|
202 |
+
prompt = f"Instruct: Hi, i am patient, {message} what is wrong with my body? What drugs should i take, and what is the side-effect of this drug? What should i do?{output_termination}"
|
203 |
+
print(prompt)
|
204 |
# apply the tokenizer.
|
205 |
tokens = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)
|
206 |
#tokens = tokens.to(device)
|
207 |
#eos_token_id = tokenizer.eos_token_id
|
208 |
# use the model to generate new tokens.
|
209 |
+
generated_output = model.generate(**tokens, use_cache=True, max_new_tokens=2000, eos_token_id=50256, pad_token_id=50256)
|
210 |
|
211 |
# Find the position of "Output:" and extract the text after it
|
212 |
generated_text = tokenizer.batch_decode(generated_output)[0]
|
|
|
214 |
split_text = generated_text.split("Output:", 1)
|
215 |
bot_message = split_text[1].strip() if len(split_text) > 1 else ""
|
216 |
bot_message = bot_message.replace("<|endoftext|>", "").strip()
|
217 |
+
#return bot_message
|
218 |
+
#chat_history.append((message, bot_message))
|
219 |
+
#time.sleep(2)
|
220 |
+
#return "", chat_history
|
221 |
+
chat_history.append((message, bot_message))
|
222 |
+
time.sleep(2)
|
223 |
+
#return bot_message
|
224 |
+
return "", chat_history
|
225 |
|
|
|
226 |
|
227 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
228 |
# Launch the demo
|
229 |
+
demo.launch(share=True)
|
230 |
+
|
231 |
+
#msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
232 |
+
# Launch the demo
|
233 |
+
#demo.launch()
|
234 |
+
|
235 |
+
|
236 |
+
#gr.ChatInterface(respond).launch()
|
237 |
+
|
238 |
+
|
239 |
+
#a = respond('hi', list())
|
240 |
+
#a = respond("Hi, good morning")
|
241 |
+
#a = respond("My skin has been peeling, especially on my knees, elbows, and scalp. This peeling is often accompanied by a burning or stinging sensation.")
|
242 |
+
#a = respond("I have blurry vision, and it seems to be getting worse. I'm continuously fatigued and worn out. I also occasionally have acute lightheadedness and vertigo, can you give me some advice?")
|
243 |
+
#print(a)
|
244 |
+
#gr.ChatInterface(respond).launch()
|
245 |
+
#demo = gr.ChatInterface(fn=random_response, examples=[{"text": "Hello", "files": []}], title="Echo Bot", multimodal=True)
|
246 |
+
#demo.launch()
|
gru_model.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f03190a27f0fb4c866cdfa6cf6f108b2798fe18ff348aca2e81a96fac56f2723
|
3 |
+
size 3216610
|