Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -3,13 +3,14 @@ import gradio as gr
|
|
| 3 |
import os
|
| 4 |
import torch
|
| 5 |
import random
|
| 6 |
-
|
| 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 |
import argparse
|
| 15 |
import numpy as np
|
|
@@ -24,8 +25,10 @@ from modeling_phi import PhiForCausalLM
|
|
| 24 |
from tokenization_codegen import CodeGenTokenizer
|
| 25 |
from transformers import PhiForCausalLM, AutoTokenizer, AutoModelForCausalLM
|
| 26 |
################################################################################
|
|
|
|
| 27 |
parser = argparse.ArgumentParser()
|
| 28 |
#############################################################################################################################
|
|
|
|
| 29 |
parser.add_argument('--device_id', type=str, default="0")
|
| 30 |
parser.add_argument('--model', type=str, default="microsoft/phi-2", help="") ## /phi-1.5
|
| 31 |
parser.add_argument('--embedder', type=str, default="BAAI/bge-small-en-v1.5") ## /bge-small-en-v1.5 # bge-m3
|
|
@@ -38,7 +41,6 @@ parser.add_argument('--prompt_type', type=str, default="v2.0", help="")
|
|
| 38 |
parser.add_argument('--top_k', type=str2bool, default=True, help="")
|
| 39 |
#############################################################################################################################
|
| 40 |
args = parser.parse_args()
|
| 41 |
-
|
| 42 |
if torch.cuda.is_available():
|
| 43 |
device = "cuda"
|
| 44 |
print(f'################################################################# device: {device}#################################################################')
|
|
@@ -55,7 +57,95 @@ def get_model(base_model: str = "bigcode/starcoder",):
|
|
| 55 |
model.config.pad_token_id = tokenizer.pad_token_id
|
| 56 |
model.eval()
|
| 57 |
return tokenizer, model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
################################################################################
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
'''
|
| 61 |
# Import data
|
|
@@ -70,18 +160,19 @@ train_data, test_data= train_test_split(df, test_size=0.15, random_state=42 )
|
|
| 70 |
howto= """Welcome to the <b>Medical Chatbot</b>, powered by Gradio.
|
| 71 |
Currently, the chatbot can WELCOME YOU, PREDICT DISEASE based on your symptoms and SUGGEST POSSIBLE SOLUTIONS AND RECOMENDATIONS, and BID YOU FAREWELL.
|
| 72 |
<b>How to Start:</b> Simply type your messages in the textbox to chat with the Chatbot and press enter!<br><br>
|
| 73 |
-
The bot will respond based on the best possible answers to your messages.
|
| 74 |
|
|
|
|
| 75 |
# Create the gradio demo
|
| 76 |
with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
def respond(message, chat_history):
|
| 86 |
# Create couple of if-else statements to capture/mimick peoples's Interaction
|
| 87 |
embedder = SentenceTransformer(args.embedder, device=device)
|
|
@@ -91,112 +182,117 @@ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
|
|
| 91 |
chat_history.append((message, bot_message))
|
| 92 |
time.sleep(2)
|
| 93 |
return "", chat_history
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
]
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
"Wishing you good health ahead! Don't hesitate to chat if you need medical insights.",
|
| 157 |
-
"Goodbye! Stay well and remember, I'm here to assist you with medical queries.",
|
| 158 |
-
]
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
tokens = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)
|
| 182 |
-
#tokens = tokens.to(device)
|
| 183 |
-
#eos_token_id = tokenizer.eos_token_id
|
| 184 |
-
# use the model to generate new tokens.
|
| 185 |
-
generated_output = model.generate(**tokens, use_cache=True, max_new_tokens=100, eos_token_id=50256, pad_token_id=50256)
|
| 186 |
-
|
| 187 |
-
# Find the position of "Output:" and extract the text after it
|
| 188 |
-
generated_text = tokenizer.batch_decode(generated_output)[0]
|
| 189 |
-
# Split the text at "Output:" and take the second part
|
| 190 |
-
split_text = generated_text.split("Output:", 1)
|
| 191 |
-
bot_message = split_text[1].strip() if len(split_text) > 1 else ""
|
| 192 |
-
bot_message = bot_message.replace("<|endoftext|>", "").strip()
|
| 193 |
-
chat_history.append((message, bot_message))
|
| 194 |
-
time.sleep(2)
|
| 195 |
-
return "", chat_history
|
| 196 |
#return bot_message
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
|
| 201 |
# Launch the demo
|
| 202 |
demo.launch()
|
|
|
|
| 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 |
#from model import RNN_model
|
| 11 |
from timeit import default_timer as timer
|
| 12 |
from typing import Tuple, Dict
|
| 13 |
+
from torch import nn
|
| 14 |
################################################################################
|
| 15 |
import argparse
|
| 16 |
import numpy as np
|
|
|
|
| 25 |
from tokenization_codegen import CodeGenTokenizer
|
| 26 |
from transformers import PhiForCausalLM, AutoTokenizer, AutoModelForCausalLM
|
| 27 |
################################################################################
|
| 28 |
+
|
| 29 |
parser = argparse.ArgumentParser()
|
| 30 |
#############################################################################################################################
|
| 31 |
+
|
| 32 |
parser.add_argument('--device_id', type=str, default="0")
|
| 33 |
parser.add_argument('--model', type=str, default="microsoft/phi-2", help="") ## /phi-1.5
|
| 34 |
parser.add_argument('--embedder', type=str, default="BAAI/bge-small-en-v1.5") ## /bge-small-en-v1.5 # bge-m3
|
|
|
|
| 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}#################################################################')
|
|
|
|
| 57 |
model.config.pad_token_id = tokenizer.pad_token_id
|
| 58 |
model.eval()
|
| 59 |
return tokenizer, model
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class RNN_model(nn.Module):
|
| 63 |
+
def __init__(self):
|
| 64 |
+
super().__init__()
|
| 65 |
+
|
| 66 |
+
self.rnn= nn.GRU(input_size=1080, hidden_size=240,num_layers=1, nonlinearity= 'relu', bias= True)
|
| 67 |
+
self.output= nn.Linear(in_features=240, out_features=24)
|
| 68 |
+
|
| 69 |
+
def forward(self, x):
|
| 70 |
+
y, hidden= self.rnn(x)
|
| 71 |
+
#print(y.shape)
|
| 72 |
+
#print(hidden.shape)
|
| 73 |
+
x= self.output(y)
|
| 74 |
+
|
| 75 |
+
return(x)
|
| 76 |
################################################################################
|
| 77 |
+
# Import data
|
| 78 |
+
df= pd.read_csv('Symptom2Disease.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.15, random_state=42 )
|
| 84 |
+
# Setup class names
|
| 85 |
+
class_names= {0: 'Acne',
|
| 86 |
+
1: 'Arthritis',
|
| 87 |
+
2: 'Bronchial Asthma',
|
| 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= RNN_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.",
|
| 125 |
+
'Arthritis': "Stay active with gentle exercises, manage weight, and consider pain-relief strategies like hot/cold therapy. Consult a rheumatologist for tailored guidance.",
|
| 126 |
+
'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.",
|
| 127 |
+
'Cervical spondylosis': "Maintain good posture, do neck exercises, and use ergonomic support. Physical therapy and pain management techniques might be helpful.",
|
| 128 |
+
'Chicken pox': "Rest, maintain hygiene, and avoid scratching. Consult a doctor for appropriate antiviral treatment.",
|
| 129 |
+
'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.",
|
| 130 |
+
'Dengue': "Stay hydrated, rest, and manage fever with acetaminophen. Seek medical care promptly, as dengue can escalate quickly.",
|
| 131 |
+
'Dimorphic Hemorrhoids': "Follow a high-fiber diet, maintain good hygiene, and consider stool softeners. Consult a doctor if symptoms persist.",
|
| 132 |
+
'Fungal infection': "Keep the affected area clean and dry, use antifungal creams, and avoid sharing personal items. Consult a dermatologist if it persists.",
|
| 133 |
+
'Hypertension': "Follow a balanced diet, exercise regularly, reduce salt intake, and take prescribed medications. Regular check-ups with a healthcare provider are important.",
|
| 134 |
+
'Impetigo': "Keep the affected area clean, use prescribed antibiotics, and avoid close contact. Consult a doctor for proper treatment.",
|
| 135 |
+
'Jaundice': "Get plenty of rest, maintain hydration, and follow a doctor's advice for diet and medications. Regular monitoring is important.",
|
| 136 |
+
'Malaria': "Take prescribed antimalarial medications, rest, and manage fever. Seek medical attention for severe cases.",
|
| 137 |
+
'Migraine': "Identify triggers, manage stress, and consider pain-relief medications. Consult a neurologist for personalized management.",
|
| 138 |
+
'Pneumonia': "Follow prescribed antibiotics, rest, stay hydrated, and monitor symptoms. Seek immediate medical attention for severe cases.",
|
| 139 |
+
'Psoriasis': "Moisturize, use prescribed creams, and avoid triggers. Consult a dermatologist for effective management.",
|
| 140 |
+
'Typhoid': "Take prescribed antibiotics, rest, and stay hydrated. Dietary precautions are important. Consult a doctor for proper treatment.",
|
| 141 |
+
'Varicose Veins': "Elevate legs, exercise regularly, and wear compression stockings. Consult a vascular specialist for evaluation and treatment options.",
|
| 142 |
+
'allergy': "Identify triggers, manage exposure, and consider antihistamines. Consult an allergist for comprehensive management.",
|
| 143 |
+
'diabetes': "Follow a balanced diet, exercise, monitor blood sugar levels, and take prescribed medications. Regular visits to an endocrinologist are essential.",
|
| 144 |
+
'drug reaction': "Discontinue the suspected medication, seek medical attention if symptoms are severe, and inform healthcare providers about the reaction.",
|
| 145 |
+
'gastroesophageal reflux disease': "Follow dietary changes, avoid large meals, and consider medications. Consult a doctor for personalized management.",
|
| 146 |
+
'peptic ulcer disease': "Avoid spicy and acidic foods, take prescribed medications, and manage stress. Consult a gastroenterologist for guidance.",
|
| 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
|
|
|
|
| 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 |
+
gr.HTML('<h1 align="center">Medical Chatbot: ARIN 7102')
|
| 169 |
+
#gr.HTML('<h3 align="center">To know more about this project')
|
| 170 |
+
with gr.Accordion("Follow these Steps to use the Gradio WebUI", open=True):
|
| 171 |
+
gr.HTML(howto)
|
| 172 |
+
chatbot = gr.Chatbot()
|
| 173 |
+
msg = gr.Textbox()
|
| 174 |
+
clear = gr.ClearButton([msg, chatbot])
|
| 175 |
+
'''
|
| 176 |
def respond(message, chat_history):
|
| 177 |
# Create couple of if-else statements to capture/mimick peoples's Interaction
|
| 178 |
embedder = SentenceTransformer(args.embedder, device=device)
|
|
|
|
| 182 |
chat_history.append((message, bot_message))
|
| 183 |
time.sleep(2)
|
| 184 |
return "", chat_history
|
| 185 |
+
'''
|
| 186 |
+
def respond(message, chat_history, base_model = "microsoft/phi-2", device=device): # "meta-llama/Meta-Llama-3-70B"
|
| 187 |
+
if base_model != "microsoft/phi-2":
|
| 188 |
+
# Random greetings in list format
|
| 189 |
+
greetings = [
|
| 190 |
+
"hello!",'hello', 'hii !', 'hi', "hi there!", "hi there!", "heyy", 'good morning', 'good afternoon', 'good evening'
|
| 191 |
+
"hey", "how are you", "how are you?", "how is it going", "how is it going?",
|
| 192 |
+
"what's up?", "how are you?",
|
| 193 |
+
"hey, how are you?", "what is popping"
|
| 194 |
+
"good to see you!", "howdy!",
|
| 195 |
+
"hi, nice to meet you.", "hiya!",
|
| 196 |
+
"hi", "hi, what's new?",
|
| 197 |
+
"hey, how's your day?", "hi, how have you been?", "greetings",
|
| 198 |
+
]
|
| 199 |
+
# Random Greetings responses
|
| 200 |
+
responses = [
|
| 201 |
+
"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.",
|
| 202 |
+
"Hello! I'm here to help you with medical predictions based on your symptoms. Please describe your symptoms in as much detail as possible.",
|
| 203 |
+
"Greetings! I am a specialized medical chatbot trained to predict potential diseases based on the symptoms you provide. Kindly list your symptoms explicitly.",
|
| 204 |
+
"Welcome to the medical chatbot. To assist you accurately, please share your symptoms in explicit detail.",
|
| 205 |
+
"Hi there! I'm a medical chatbot specialized in analyzing symptoms to suggest possible diseases. Please provide your symptoms explicitly.",
|
| 206 |
+
"Hey! I'm your medical chatbot. Describe your symptoms with as much detail as you can, and I'll generate potential disease predictions.",
|
| 207 |
+
"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.",
|
| 208 |
+
"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.",
|
| 209 |
+
"Greetings! I'm here to help with medical predictions. Describe your symptoms explicitly, and I'll offer insights into potential diseases.",
|
| 210 |
+
"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.",
|
| 211 |
+
"Hi, I specialize in medical predictions based on symptoms. Kindly provide detailed symptoms for accurate disease predictions.",
|
| 212 |
+
"Hello! I'm a medical chatbot with expertise in predicting diseases from symptoms. Please describe your symptoms explicitly to receive accurate insights.",
|
| 213 |
+
]
|
| 214 |
+
# Random goodbyes
|
| 215 |
+
goodbyes = [
|
| 216 |
+
"farewell!",'bye', 'goodbye','good-bye', 'good bye', 'bye', 'thank you', 'later', "take care!",
|
| 217 |
+
"see you later!", 'see you', 'see ya', 'see-you', 'thanks', 'thank', 'bye bye', 'byebye'
|
| 218 |
+
"catch you on the flip side!", "adios!",
|
| 219 |
+
"goodbye for now!", "till we meet again!",
|
| 220 |
+
"so long!", "hasta la vista!",
|
| 221 |
+
"bye-bye!", "keep in touch!",
|
| 222 |
+
"toodles!", "ciao!",
|
| 223 |
+
"later, gator!", "stay safe and goodbye!",
|
| 224 |
+
"peace out!", "until next time!", "off I go!",
|
| 225 |
+
]
|
| 226 |
+
# Random Goodbyes responses
|
| 227 |
+
goodbye_replies = [
|
| 228 |
+
"Take care of yourself! If you have more questions, don't hesitate to reach out.",
|
| 229 |
+
"Stay well! Remember, I'm here if you need further medical advice.",
|
| 230 |
+
"Goodbye for now! Don't hesitate to return if you need more information in the future.",
|
| 231 |
+
"Wishing you good health ahead! Feel free to come back if you have more concerns.",
|
| 232 |
+
"Farewell! If you have more symptoms or questions, don't hesitate to consult again.",
|
| 233 |
+
"Take care and stay informed about your health. Feel free to chat anytime.",
|
| 234 |
+
"Bye for now! Remember, your well-being is a priority. Don't hesitate to ask if needed.",
|
| 235 |
+
"Have a great day ahead! If you need medical guidance later on, I'll be here.",
|
| 236 |
+
"Stay well and take it easy! Reach out if you need more medical insights.",
|
| 237 |
+
"Until next time! Prioritize your health and reach out if you need assistance.",
|
| 238 |
+
"Goodbye! Your health matters. Feel free to return if you have more health-related queries.",
|
| 239 |
+
"Stay healthy and stay curious about your health! If you need more info, just ask.",
|
| 240 |
+
"Wishing you wellness on your journey! If you have more questions, I'm here to help.",
|
| 241 |
+
"Take care and remember, your health is important. Don't hesitate to reach out if needed.",
|
| 242 |
+
"Goodbye for now! Stay informed and feel free to consult if you require medical advice.",
|
| 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 |
+
transform_text= vectorizer.transform([message])
|
| 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)
|
| 270 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model)
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
+
# feel free to change the prompt to your liking.
|
| 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=500, eos_token_id=50256, pad_token_id=50256)
|
| 283 |
+
|
| 284 |
+
# Find the position of "Output:" and extract the text after it
|
| 285 |
+
generated_text = tokenizer.batch_decode(generated_output)[0]
|
| 286 |
+
# Split the text at "Output:" and take the second part
|
| 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 |
+
chat_history.append((message, bot_message))
|
| 291 |
+
time.sleep(2)
|
| 292 |
+
return "", chat_history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
#return bot_message
|
| 294 |
+
|
| 295 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
|
|
|
| 296 |
|
| 297 |
# Launch the demo
|
| 298 |
demo.launch()
|