Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,8 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import nltk
|
| 4 |
import numpy as np
|
|
|
|
|
|
|
| 5 |
import json
|
| 6 |
import pickle
|
| 7 |
from nltk.tokenize import word_tokenize
|
|
@@ -10,16 +12,10 @@ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipe
|
|
| 10 |
import googlemaps
|
| 11 |
import folium
|
| 12 |
import torch
|
| 13 |
-
import pandas as pd
|
| 14 |
-
from sklearn.tree import DecisionTreeClassifier
|
| 15 |
-
from sklearn.ensemble import RandomForestClassifier
|
| 16 |
-
from sklearn.naive_bayes import GaussianNB
|
| 17 |
-
from sklearn.metrics import accuracy_score
|
| 18 |
-
from sklearn.preprocessing import LabelEncoder
|
| 19 |
|
| 20 |
# Suppress TensorFlow warnings
|
| 21 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 22 |
-
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 23 |
|
| 24 |
# Download necessary NLTK resources
|
| 25 |
nltk.download("punkt")
|
|
@@ -32,18 +28,14 @@ with open("intents.json") as file:
|
|
| 32 |
with open("data.pickle", "rb") as f:
|
| 33 |
words, labels, training, output = pickle.load(f)
|
| 34 |
|
| 35 |
-
# Build the chatbot model
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
# Build and train the chatbot model
|
| 45 |
-
chatbot_model = build_chatbot_model(len(training[0]), len(output[0]))
|
| 46 |
-
chatbot_model.fit(training, output, epochs=100) # Ensure training data is prepared accordingly
|
| 47 |
|
| 48 |
# Hugging Face sentiment and emotion models
|
| 49 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
|
@@ -54,148 +46,23 @@ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/e
|
|
| 54 |
# Google Maps API Client
|
| 55 |
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
| 56 |
|
| 57 |
-
# Disease
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
'Peptic ulcer disease': 5,
|
| 73 |
-
'AIDS': 6,
|
| 74 |
-
'Diabetes': 7,
|
| 75 |
-
'Gastroenteritis': 8,
|
| 76 |
-
'Bronchial Asthma': 9,
|
| 77 |
-
'Hypertension': 10,
|
| 78 |
-
'Migraine': 11,
|
| 79 |
-
'Cervical spondylosis': 12,
|
| 80 |
-
'Paralysis (brain hemorrhage)': 13,
|
| 81 |
-
'Jaundice': 14,
|
| 82 |
-
'Malaria': 15,
|
| 83 |
-
'Chicken pox': 16,
|
| 84 |
-
'Dengue': 17,
|
| 85 |
-
'Typhoid': 18,
|
| 86 |
-
'Hepatitis A': 19,
|
| 87 |
-
'Hepatitis B': 20,
|
| 88 |
-
'Hepatitis C': 21,
|
| 89 |
-
'Hepatitis D': 22,
|
| 90 |
-
'Hepatitis E': 23,
|
| 91 |
-
'Alcoholic hepatitis': 24,
|
| 92 |
-
'Tuberculosis': 25,
|
| 93 |
-
'Common Cold': 26,
|
| 94 |
-
'Pneumonia': 27,
|
| 95 |
-
'Dimorphic hemorrhoids (piles)': 28,
|
| 96 |
-
'Heart attack': 29,
|
| 97 |
-
'Varicose veins': 30,
|
| 98 |
-
'Hypothyroidism': 31,
|
| 99 |
-
'Hyperthyroidism': 32,
|
| 100 |
-
'Hypoglycemia': 33,
|
| 101 |
-
'Osteoarthritis': 34,
|
| 102 |
-
'Arthritis': 35,
|
| 103 |
-
'(vertigo) Paroxysmal Positional Vertigo': 36,
|
| 104 |
-
'Acne': 37,
|
| 105 |
-
'Urinary tract infection': 38,
|
| 106 |
-
'Psoriasis': 39,
|
| 107 |
-
'Impetigo': 40
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
# Replace prognosis values with numerical categories
|
| 111 |
-
df.replace({'prognosis': disease_dict}, inplace=True)
|
| 112 |
-
|
| 113 |
-
# Check unique values in prognosis for debugging
|
| 114 |
-
print("Unique values in prognosis after mapping:", df['prognosis'].unique())
|
| 115 |
-
|
| 116 |
-
# Ensure prognosis is purely numerical after mapping
|
| 117 |
-
if df['prognosis'].dtype == 'object':
|
| 118 |
-
raise ValueError(f"The prognosis contains unmapped values: {df['prognosis'].unique()}")
|
| 119 |
-
|
| 120 |
-
df['prognosis'] = df['prognosis'].astype(int)
|
| 121 |
-
df = df.infer_objects()
|
| 122 |
-
|
| 123 |
-
# Similar process for the testing data
|
| 124 |
-
tr.replace({'prognosis': disease_dict}, inplace=True)
|
| 125 |
-
print("Unique values in prognosis for testing data after mapping:", tr['prognosis'].unique())
|
| 126 |
-
|
| 127 |
-
if tr['prognosis'].dtype == 'object':
|
| 128 |
-
raise ValueError(f"Testing data prognosis contains unmapped values: {tr['prognosis'].unique()}")
|
| 129 |
-
|
| 130 |
-
tr['prognosis'] = tr['prognosis'].astype(int)
|
| 131 |
-
tr = tr.infer_objects()
|
| 132 |
-
|
| 133 |
-
return df, tr, disease_dict
|
| 134 |
-
|
| 135 |
-
df, tr, disease_dict = load_data()
|
| 136 |
-
l1 = list(df.columns[:-1]) # All columns except prognosis
|
| 137 |
-
X = df[l1]
|
| 138 |
-
y = df['prognosis']
|
| 139 |
-
X_test = tr[l1]
|
| 140 |
-
y_test = tr['prognosis']
|
| 141 |
-
|
| 142 |
-
# Encode the target variable with LabelEncoder if still in string format
|
| 143 |
-
le = LabelEncoder()
|
| 144 |
-
y_encoded = le.fit_transform(y)
|
| 145 |
-
|
| 146 |
-
def train_models(X, y_encoded, X_test, y_test):
|
| 147 |
-
models = {
|
| 148 |
-
"Decision Tree": DecisionTreeClassifier(),
|
| 149 |
-
"Random Forest": RandomForestClassifier(),
|
| 150 |
-
"Naive Bayes": GaussianNB()
|
| 151 |
-
}
|
| 152 |
-
trained_models = {}
|
| 153 |
-
for model_name, model_obj in models.items():
|
| 154 |
-
try:
|
| 155 |
-
model_obj.fit(X, y_encoded) # Fit the model
|
| 156 |
-
acc = accuracy_score(y_test, model_obj.predict(X_test))
|
| 157 |
-
trained_models[model_name] = (model_obj, acc)
|
| 158 |
-
except Exception as e:
|
| 159 |
-
print(f"Failed to train {model_name}: {e}")
|
| 160 |
-
return trained_models
|
| 161 |
-
|
| 162 |
-
trained_models = train_models(X, y_encoded, X_test, y_test)
|
| 163 |
-
|
| 164 |
-
def predict_disease(model, symptoms):
|
| 165 |
-
input_test = np.zeros(len(l1))
|
| 166 |
-
for symptom in symptoms:
|
| 167 |
-
if symptom in l1:
|
| 168 |
-
input_test[l1.index(symptom)] = 1
|
| 169 |
-
prediction = model.predict([input_test])[0]
|
| 170 |
-
confidence = model.predict_proba([input_test])[0][prediction] if hasattr(model, 'predict_proba') else None
|
| 171 |
-
return {
|
| 172 |
-
"disease": list(disease_dict.keys())[list(disease_dict.values()).index(prediction)],
|
| 173 |
-
"confidence": confidence
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
def disease_prediction_interface(symptoms):
|
| 177 |
-
symptoms_selected = [s for s in symptoms if s != "None"]
|
| 178 |
-
|
| 179 |
-
if len(symptoms_selected) < 3:
|
| 180 |
-
return ["Please select at least 3 symptoms for accurate prediction."]
|
| 181 |
-
|
| 182 |
-
results = []
|
| 183 |
-
for model_name, (model, acc) in trained_models.items():
|
| 184 |
-
prediction_info = predict_disease(model, symptoms_selected)
|
| 185 |
-
predicted_disease = prediction_info["disease"]
|
| 186 |
-
confidence_score = prediction_info["confidence"]
|
| 187 |
-
|
| 188 |
-
result = f"{model_name} Prediction: Predicted Disease: **{predicted_disease}**"
|
| 189 |
-
if confidence_score is not None:
|
| 190 |
-
result += f" (Confidence: {confidence_score:.2f})"
|
| 191 |
-
result += f" (Accuracy: {acc * 100:.2f}%)"
|
| 192 |
-
|
| 193 |
-
results.append(result)
|
| 194 |
-
|
| 195 |
-
return results
|
| 196 |
-
|
| 197 |
-
# Helper Functions (for chatbot)
|
| 198 |
def bag_of_words(s, words):
|
|
|
|
| 199 |
bag = [0] * len(words)
|
| 200 |
s_words = word_tokenize(s)
|
| 201 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
|
@@ -206,17 +73,23 @@ def bag_of_words(s, words):
|
|
| 206 |
return np.array(bag)
|
| 207 |
|
| 208 |
def generate_chatbot_response(message, history):
|
|
|
|
| 209 |
history = history or []
|
| 210 |
try:
|
| 211 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 212 |
tag = labels[np.argmax(result)]
|
| 213 |
-
response =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
except Exception as e:
|
| 215 |
response = f"Error: {e}"
|
| 216 |
history.append((message, response))
|
| 217 |
return history, response
|
| 218 |
|
| 219 |
def analyze_sentiment(user_input):
|
|
|
|
| 220 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 221 |
with torch.no_grad():
|
| 222 |
outputs = model_sentiment(**inputs)
|
|
@@ -225,6 +98,7 @@ def analyze_sentiment(user_input):
|
|
| 225 |
return f"Sentiment: {sentiment_map[sentiment_class]}"
|
| 226 |
|
| 227 |
def detect_emotion(user_input):
|
|
|
|
| 228 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 229 |
result = pipe(user_input)
|
| 230 |
emotion = result[0]["label"].lower().strip()
|
|
@@ -238,6 +112,17 @@ def detect_emotion(user_input):
|
|
| 238 |
}
|
| 239 |
return emotion_map.get(emotion, "Unknown 🤔"), emotion
|
| 240 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
def generate_suggestions(emotion):
|
| 242 |
"""Return relevant suggestions based on detected emotions."""
|
| 243 |
emotion_key = emotion.lower()
|
|
@@ -271,10 +156,12 @@ def generate_suggestions(emotion):
|
|
| 271 |
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
| 272 |
],
|
| 273 |
}
|
| 274 |
-
|
|
|
|
| 275 |
formatted_suggestions = [
|
| 276 |
[title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
|
| 277 |
]
|
|
|
|
| 278 |
return formatted_suggestions
|
| 279 |
|
| 280 |
def get_health_professionals_and_map(location, query):
|
|
@@ -290,100 +177,133 @@ def get_health_professionals_and_map(location, query):
|
|
| 290 |
professionals = []
|
| 291 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
| 292 |
for place in places_result:
|
|
|
|
| 293 |
professionals.append([place['name'], place.get('vicinity', 'No address provided')])
|
| 294 |
folium.Marker(
|
| 295 |
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
| 296 |
popup=f"{place['name']}"
|
| 297 |
).add_to(map_)
|
| 298 |
return professionals, map_._repr_html_()
|
| 299 |
-
|
|
|
|
| 300 |
except Exception as e:
|
| 301 |
-
|
| 302 |
-
return [], ""
|
| 303 |
|
| 304 |
# Main Application Logic
|
| 305 |
-
def app_function(user_input, location, query,
|
| 306 |
chatbot_history, _ = generate_chatbot_response(user_input, history)
|
| 307 |
sentiment_result = analyze_sentiment(user_input)
|
| 308 |
emotion_result, cleaned_emotion = detect_emotion(user_input)
|
| 309 |
suggestions = generate_suggestions(cleaned_emotion)
|
| 310 |
professionals, map_html = get_health_professionals_and_map(location, query)
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
return "Please enter the patient's name."
|
| 327 |
|
| 328 |
-
|
|
|
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
results = []
|
| 334 |
-
for model_name, (model, acc) in trained_models.items():
|
| 335 |
-
prediction = predict_disease(model, symptoms_selected)
|
| 336 |
-
result = f"{model_name} Prediction: Predicted Disease: **{prediction}**"
|
| 337 |
-
result += f" (Accuracy: {acc * 100:.2f}%)"
|
| 338 |
-
results.append(result)
|
| 339 |
|
| 340 |
-
|
| 341 |
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
location = gr.Textbox(label="Your Current Location Here", placeholder="Enter location...")
|
| 350 |
-
query = gr.Textbox(label="Search Health Professionals Nearby", placeholder="What are you looking for...")
|
| 351 |
-
|
| 352 |
-
with gr.Row():
|
| 353 |
-
symptom1 = gr.Dropdown(choices=["None"] + l1, label="Symptom 1")
|
| 354 |
-
symptom2 = gr.Dropdown(choices=["None"] + l1, label="Symptom 2")
|
| 355 |
-
symptom3 = gr.Dropdown(choices=["None"] + l1, label="Symptom 3")
|
| 356 |
-
symptom4 = gr.Dropdown(choices=["None"] + l1, label="Symptom 4")
|
| 357 |
-
symptom5 = gr.Dropdown(choices=["None"] + l1, label="Symptom 5")
|
| 358 |
-
|
| 359 |
-
submit_chatbot = gr.Button(value="Submit", variant="primary")
|
| 360 |
-
chatbot = gr.Chatbot(label="Chat History")
|
| 361 |
-
sentiment = gr.Textbox(label="Detected Sentiment")
|
| 362 |
-
emotion = gr.Textbox(label="Detected Emotion")
|
| 363 |
-
|
| 364 |
-
suggestions = gr.DataFrame(headers=["Title", "Link"])
|
| 365 |
-
professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"])
|
| 366 |
-
map_html = gr.HTML(label="Interactive Map")
|
| 367 |
-
disease_predictions = gr.Textbox(label="Disease Predictions")
|
| 368 |
-
|
| 369 |
-
submit_chatbot.click(
|
| 370 |
-
app_function,
|
| 371 |
-
inputs=[user_input, location, query, [symptom1, symptom2, symptom3, symptom4, symptom5], chatbot],
|
| 372 |
-
outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html, disease_predictions],
|
| 373 |
-
)
|
| 374 |
-
|
| 375 |
-
with gr.Tab("Disease Prediction"):
|
| 376 |
-
name_box = gr.Textbox(label="Name of Patient", placeholder="Enter patient's name")
|
| 377 |
-
symptom_choices = [gr.Dropdown(choices=["None"] + l1, label=f"Symptom {i+1}") for i in range(5)]
|
| 378 |
-
submit_disease = gr.Button(value="Submit", variant="primary")
|
| 379 |
-
|
| 380 |
-
disease_output = gr.Textbox(label="Predicted Disease", placeholder="Prediction will appear here")
|
| 381 |
-
|
| 382 |
-
submit_disease.click(
|
| 383 |
-
disease_app_function,
|
| 384 |
-
inputs=[name_box] + symptom_choices,
|
| 385 |
-
outputs=disease_output
|
| 386 |
-
)
|
| 387 |
-
|
| 388 |
-
# Launch the Gradio application
|
| 389 |
-
app.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import nltk
|
| 4 |
import numpy as np
|
| 5 |
+
import tflearn
|
| 6 |
+
import random
|
| 7 |
import json
|
| 8 |
import pickle
|
| 9 |
from nltk.tokenize import word_tokenize
|
|
|
|
| 12 |
import googlemaps
|
| 13 |
import folium
|
| 14 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# Suppress TensorFlow warnings
|
| 17 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 18 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 19 |
|
| 20 |
# Download necessary NLTK resources
|
| 21 |
nltk.download("punkt")
|
|
|
|
| 28 |
with open("data.pickle", "rb") as f:
|
| 29 |
words, labels, training, output = pickle.load(f)
|
| 30 |
|
| 31 |
+
# Build the chatbot model
|
| 32 |
+
net = tflearn.input_data(shape=[None, len(training[0])])
|
| 33 |
+
net = tflearn.fully_connected(net, 8)
|
| 34 |
+
net = tflearn.fully_connected(net, 8)
|
| 35 |
+
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
| 36 |
+
net = tflearn.regression(net)
|
| 37 |
+
chatbot_model = tflearn.DNN(net)
|
| 38 |
+
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
# Hugging Face sentiment and emotion models
|
| 41 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
|
|
|
| 46 |
# Google Maps API Client
|
| 47 |
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
| 48 |
|
| 49 |
+
# Disease dictionary to map disease names to numerical values
|
| 50 |
+
disease_dict = {
|
| 51 |
+
'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
|
| 52 |
+
'Peptic ulcer disease': 5, 'AIDS': 6, 'Diabetes ': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
|
| 53 |
+
'Hypertension ': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
|
| 54 |
+
'Jaundice': 14, 'Malaria': 15, 'Chicken pox': 16, 'Dengue': 17, 'Typhoid': 18, 'hepatitis A': 19,
|
| 55 |
+
'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23, 'Alcoholic hepatitis': 24,
|
| 56 |
+
'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27, 'Dimorphic hemorrhoids(piles)': 28,
|
| 57 |
+
'Heart attack': 29, 'Varicose veins': 30, 'Hypothyroidism': 31, 'Hyperthyroidism': 32,
|
| 58 |
+
'Hypoglycemia': 33, 'Osteoarthritis': 34, 'Arthritis': 35,
|
| 59 |
+
'(vertigo) Paroxysmal Positional Vertigo': 36, 'Acne': 37, 'Urinary tract infection': 38,
|
| 60 |
+
'Psoriasis': 39, 'Impetigo': 40
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
# Helper Functions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
def bag_of_words(s, words):
|
| 65 |
+
"""Convert user input to bag-of-words vector."""
|
| 66 |
bag = [0] * len(words)
|
| 67 |
s_words = word_tokenize(s)
|
| 68 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
|
|
|
| 73 |
return np.array(bag)
|
| 74 |
|
| 75 |
def generate_chatbot_response(message, history):
|
| 76 |
+
"""Generate chatbot response and maintain conversation history."""
|
| 77 |
history = history or []
|
| 78 |
try:
|
| 79 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 80 |
tag = labels[np.argmax(result)]
|
| 81 |
+
response = "I'm sorry, I didn't understand that. 🤔"
|
| 82 |
+
for intent in intents_data["intents"]:
|
| 83 |
+
if intent["tag"] == tag:
|
| 84 |
+
response = random.choice(intent["responses"])
|
| 85 |
+
break
|
| 86 |
except Exception as e:
|
| 87 |
response = f"Error: {e}"
|
| 88 |
history.append((message, response))
|
| 89 |
return history, response
|
| 90 |
|
| 91 |
def analyze_sentiment(user_input):
|
| 92 |
+
"""Analyze sentiment and map to emojis."""
|
| 93 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 94 |
with torch.no_grad():
|
| 95 |
outputs = model_sentiment(**inputs)
|
|
|
|
| 98 |
return f"Sentiment: {sentiment_map[sentiment_class]}"
|
| 99 |
|
| 100 |
def detect_emotion(user_input):
|
| 101 |
+
"""Detect emotions based on input."""
|
| 102 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 103 |
result = pipe(user_input)
|
| 104 |
emotion = result[0]["label"].lower().strip()
|
|
|
|
| 112 |
}
|
| 113 |
return emotion_map.get(emotion, "Unknown 🤔"), emotion
|
| 114 |
|
| 115 |
+
def disease_prediction(user_input):
|
| 116 |
+
"""Predict disease based on input symptoms."""
|
| 117 |
+
# Here, we simulate disease prediction logic
|
| 118 |
+
symptoms = user_input.lower().split()
|
| 119 |
+
disease_probabilities = [random.random() for _ in disease_dict] # Placeholder for prediction model
|
| 120 |
+
|
| 121 |
+
# Select the highest probability (for demonstration)
|
| 122 |
+
disease_index = np.argmax(disease_probabilities)
|
| 123 |
+
disease_name = list(disease_dict.keys())[disease_index]
|
| 124 |
+
return disease_name
|
| 125 |
+
|
| 126 |
def generate_suggestions(emotion):
|
| 127 |
"""Return relevant suggestions based on detected emotions."""
|
| 128 |
emotion_key = emotion.lower()
|
|
|
|
| 156 |
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
| 157 |
],
|
| 158 |
}
|
| 159 |
+
|
| 160 |
+
# Format the output to include HTML anchor tags
|
| 161 |
formatted_suggestions = [
|
| 162 |
[title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
|
| 163 |
]
|
| 164 |
+
|
| 165 |
return formatted_suggestions
|
| 166 |
|
| 167 |
def get_health_professionals_and_map(location, query):
|
|
|
|
| 177 |
professionals = []
|
| 178 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
| 179 |
for place in places_result:
|
| 180 |
+
# Use a list of values to append each professional
|
| 181 |
professionals.append([place['name'], place.get('vicinity', 'No address provided')])
|
| 182 |
folium.Marker(
|
| 183 |
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
| 184 |
popup=f"{place['name']}"
|
| 185 |
).add_to(map_)
|
| 186 |
return professionals, map_._repr_html_()
|
| 187 |
+
|
| 188 |
+
return [], "" # Return empty list if no professionals found
|
| 189 |
except Exception as e:
|
| 190 |
+
return [], "" # Return empty list on exception
|
|
|
|
| 191 |
|
| 192 |
# Main Application Logic
|
| 193 |
+
def app_function(user_input, location, query, history):
|
| 194 |
chatbot_history, _ = generate_chatbot_response(user_input, history)
|
| 195 |
sentiment_result = analyze_sentiment(user_input)
|
| 196 |
emotion_result, cleaned_emotion = detect_emotion(user_input)
|
| 197 |
suggestions = generate_suggestions(cleaned_emotion)
|
| 198 |
professionals, map_html = get_health_professionals_and_map(location, query)
|
| 199 |
+
disease_result = disease_prediction(user_input) # Get disease prediction
|
| 200 |
+
return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html, disease_result
|
| 201 |
+
|
| 202 |
+
# CSS Styling
|
| 203 |
+
custom_css = """
|
| 204 |
+
body {
|
| 205 |
+
font-family: 'Roboto', sans-serif;
|
| 206 |
+
background-color: #3c6487; /* Set the background color */
|
| 207 |
+
color: white;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
h1 {
|
| 211 |
+
background: #ffffff;
|
| 212 |
+
color: #000000;
|
| 213 |
+
border-radius: 8px;
|
| 214 |
+
padding: 10px;
|
| 215 |
+
font-weight: bold;
|
| 216 |
+
text-align: center;
|
| 217 |
+
font-size: 2.5rem;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
textarea, input {
|
| 221 |
+
background: transparent;
|
| 222 |
+
color: black;
|
| 223 |
+
border: 2px solid orange;
|
| 224 |
+
padding: 8px;
|
| 225 |
+
font-size: 1rem;
|
| 226 |
+
caret-color: black;
|
| 227 |
+
outline: none;
|
| 228 |
+
border-radius: 8px;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
textarea:focus, input:focus {
|
| 232 |
+
background: transparent;
|
| 233 |
+
color: black;
|
| 234 |
+
border: 2px solid orange;
|
| 235 |
+
outline: none;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
textarea:hover, input:hover {
|
| 239 |
+
background: transparent;
|
| 240 |
+
color: black;
|
| 241 |
+
border: 2px solid orange;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
.df-container {
|
| 245 |
+
background: white;
|
| 246 |
+
color: black;
|
| 247 |
+
border: 2px solid orange;
|
| 248 |
+
border-radius: 10px;
|
| 249 |
+
padding: 10px;
|
| 250 |
+
font-size: 14px;
|
| 251 |
+
max-height: 400px;
|
| 252 |
+
height: auto;
|
| 253 |
+
overflow-y: auto;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
#suggestions-title {
|
| 257 |
+
text-align: center !important; /* Ensure the centering is applied */
|
| 258 |
+
font-weight: bold !important; /* Ensure bold is applied */
|
| 259 |
+
color: white !important; /* Ensure color is applied */
|
| 260 |
+
font-size: 4.2rem !important; /* Ensure font size is applied */
|
| 261 |
+
margin-bottom: 20px !important; /* Ensure margin is applied */
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
/* Style for the submit button */
|
| 265 |
+
.gr-button {
|
| 266 |
+
background-color: #ae1c93; /* Set the background color to #ae1c93 */
|
| 267 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
|
| 268 |
+
transition: background-color 0.3s ease;
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
.gr-button:hover {
|
| 272 |
+
background-color: #8f167b;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
.gr-button:active {
|
| 276 |
+
background-color: #7f156b;
|
| 277 |
+
}
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
# Gradio Application
|
| 281 |
+
with gr.Blocks(css=custom_css) as app:
|
| 282 |
+
gr.HTML("<h1>🌟 Well-Being Companion</h1>")
|
| 283 |
+
with gr.Row():
|
| 284 |
+
user_input = gr.Textbox(label="Please Enter Your Message Here")
|
| 285 |
+
location = gr.Textbox(label="Please Enter Your Current Location Here")
|
| 286 |
+
query = gr.Textbox(label="Please Enter Which Health Professional You Want To Search Nearby")
|
| 287 |
+
|
| 288 |
+
submit = gr.Button(value="Submit", variant="primary")
|
| 289 |
|
| 290 |
+
chatbot = gr.Chatbot(label="Chat History")
|
| 291 |
+
sentiment = gr.Textbox(label="Detected Sentiment")
|
| 292 |
+
emotion = gr.Textbox(label="Detected Emotion")
|
|
|
|
| 293 |
|
| 294 |
+
# Adding Suggestions Title with Styled Markdown (Centered and Bold)
|
| 295 |
+
gr.Markdown("Suggestions", elem_id="suggestions-title")
|
| 296 |
|
| 297 |
+
suggestions = gr.DataFrame(headers=["Title", "Link"]) # Table for suggestions
|
| 298 |
+
professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"]) # Changed to DataFrame
|
| 299 |
+
map_html = gr.HTML(label="Interactive Map")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
+
disease = gr.Textbox(label="Predicted Disease") # Display disease prediction
|
| 302 |
|
| 303 |
+
submit.click(
|
| 304 |
+
app_function,
|
| 305 |
+
inputs=[user_input, location, query, chatbot],
|
| 306 |
+
outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html, disease],
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|