Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,281 +1,285 @@
|
|
| 1 |
-
import os
|
| 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
|
| 10 |
-
from nltk.stem.lancaster import LancasterStemmer
|
| 11 |
-
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 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")
|
| 22 |
-
stemmer = LancasterStemmer()
|
| 23 |
-
|
| 24 |
-
# Load intents and chatbot training data
|
| 25 |
-
with open("intents.json") as file:
|
| 26 |
-
intents_data = json.load(file)
|
| 27 |
-
|
| 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")
|
| 42 |
-
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 43 |
-
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 44 |
-
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 45 |
-
|
| 46 |
-
# Google Maps API Client
|
| 47 |
-
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
| 48 |
-
|
| 49 |
-
# Helper Functions
|
| 50 |
-
def bag_of_words(s, words):
|
| 51 |
-
"""Convert user input to bag-of-words vector."""
|
| 52 |
-
bag = [0] * len(words)
|
| 53 |
-
s_words = word_tokenize(s)
|
| 54 |
-
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
| 55 |
-
for se in s_words:
|
| 56 |
-
for i, w in enumerate(words):
|
| 57 |
-
if w == se:
|
| 58 |
-
bag[i] = 1
|
| 59 |
-
return np.array(bag)
|
| 60 |
-
|
| 61 |
-
def generate_chatbot_response(message, history):
|
| 62 |
-
"""Generate chatbot response and maintain conversation history."""
|
| 63 |
-
history = history or []
|
| 64 |
-
try:
|
| 65 |
-
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 66 |
-
tag = labels[np.argmax(result)]
|
| 67 |
-
response = "I'm sorry, I didn't understand that. 🤔"
|
| 68 |
-
for intent in intents_data["intents"]:
|
| 69 |
-
if intent["tag"] == tag:
|
| 70 |
-
response = random.choice(intent["responses"])
|
| 71 |
-
break
|
| 72 |
-
except Exception as e:
|
| 73 |
-
response = f"Error: {e}"
|
| 74 |
-
history.append((message, response))
|
| 75 |
-
return history, response
|
| 76 |
-
|
| 77 |
-
def analyze_sentiment(user_input):
|
| 78 |
-
"""Analyze sentiment and map to emojis."""
|
| 79 |
-
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 80 |
-
with torch.no_grad():
|
| 81 |
-
outputs = model_sentiment(**inputs)
|
| 82 |
-
sentiment_class = torch.argmax(outputs.logits, dim=1).item()
|
| 83 |
-
sentiment_map = ["Negative 😔", "Neutral 😐", "Positive 😊"]
|
| 84 |
-
return f"Sentiment: {sentiment_map[sentiment_class]}"
|
| 85 |
-
|
| 86 |
-
def detect_emotion(user_input):
|
| 87 |
-
"""Detect emotions based on input."""
|
| 88 |
-
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 89 |
-
result = pipe(user_input)
|
| 90 |
-
emotion = result[0]["label"].lower().strip()
|
| 91 |
-
emotion_map = {
|
| 92 |
-
"joy": "Joy 😊",
|
| 93 |
-
"anger": "Anger 😠",
|
| 94 |
-
"sadness": "Sadness 😢",
|
| 95 |
-
"fear": "Fear 😨",
|
| 96 |
-
"surprise": "Surprise 😲",
|
| 97 |
-
"neutral": "Neutral 😐",
|
| 98 |
-
}
|
| 99 |
-
return emotion_map.get(emotion, "Unknown 🤔"), emotion
|
| 100 |
-
|
| 101 |
-
def generate_suggestions(emotion):
|
| 102 |
-
"""Return relevant suggestions based on detected emotions."""
|
| 103 |
-
emotion_key = emotion.lower()
|
| 104 |
-
suggestions = {
|
| 105 |
-
"joy": [
|
| 106 |
-
["Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
|
| 107 |
-
["Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 108 |
-
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 109 |
-
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
| 110 |
-
],
|
| 111 |
-
"anger": [
|
| 112 |
-
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 113 |
-
["Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"],
|
| 114 |
-
["Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 115 |
-
["Relaxation Video", "https://youtu.be/MIc299Flibs"],
|
| 116 |
-
],
|
| 117 |
-
"fear": [
|
| 118 |
-
["Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
|
| 119 |
-
["Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 120 |
-
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 121 |
-
["Relaxation Video", "https://youtu.be/yGKKz185M5o"],
|
| 122 |
-
],
|
| 123 |
-
"sadness": [
|
| 124 |
-
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 125 |
-
["Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 126 |
-
["Relaxation Video", "https://youtu.be/-e-4Kx5px_I"],
|
| 127 |
-
],
|
| 128 |
-
"surprise": [
|
| 129 |
-
["Managing Stress", "https://www.health.harvard.edu/health-a-to-z"],
|
| 130 |
-
["Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 131 |
-
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
| 132 |
-
],
|
| 133 |
-
}
|
| 134 |
-
|
| 135 |
-
# Format the output to include HTML anchor tags
|
| 136 |
-
formatted_suggestions = [
|
| 137 |
-
[title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
|
| 138 |
-
]
|
| 139 |
-
|
| 140 |
-
return formatted_suggestions
|
| 141 |
-
|
| 142 |
-
def get_health_professionals_and_map(location, query):
|
| 143 |
-
"""Search nearby healthcare professionals using Google Maps API."""
|
| 144 |
-
try:
|
| 145 |
-
if not location or not query:
|
| 146 |
-
return [], "" # Return empty list if inputs are missing
|
| 147 |
-
|
| 148 |
-
geo_location = gmaps.geocode(location)
|
| 149 |
-
if geo_location:
|
| 150 |
-
lat, lng = geo_location[0]["geometry"]["location"].values()
|
| 151 |
-
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
| 152 |
-
professionals = []
|
| 153 |
-
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
| 154 |
-
for place in places_result:
|
| 155 |
-
# Use a list of values to append each professional
|
| 156 |
-
professionals.append([place['name'], place.get('vicinity', 'No address provided')])
|
| 157 |
-
folium.Marker(
|
| 158 |
-
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
| 159 |
-
popup=f"{place['name']}"
|
| 160 |
-
).add_to(map_)
|
| 161 |
-
return professionals, map_._repr_html_()
|
| 162 |
-
|
| 163 |
-
return [], "" # Return empty list if no professionals found
|
| 164 |
-
except Exception as e:
|
| 165 |
-
return [], "" # Return empty list on exception
|
| 166 |
-
|
| 167 |
-
# Main Application Logic
|
| 168 |
-
def app_function(user_input, location, query, history):
|
| 169 |
-
chatbot_history, _ = generate_chatbot_response(user_input, history)
|
| 170 |
-
sentiment_result = analyze_sentiment(user_input)
|
| 171 |
-
emotion_result, cleaned_emotion = detect_emotion(user_input)
|
| 172 |
-
suggestions = generate_suggestions(cleaned_emotion)
|
| 173 |
-
professionals, map_html = get_health_professionals_and_map(location, query)
|
| 174 |
-
return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
|
| 175 |
-
|
| 176 |
-
# CSS Styling
|
| 177 |
-
custom_css = """
|
| 178 |
-
body {
|
| 179 |
-
font-family: 'Roboto', sans-serif;
|
| 180 |
-
background-color: #3c6487; /* Set the background color */
|
| 181 |
-
color: white;
|
| 182 |
-
}
|
| 183 |
-
|
| 184 |
-
h1 {
|
| 185 |
-
background: #ffffff;
|
| 186 |
-
color: #000000;
|
| 187 |
-
border-radius: 8px;
|
| 188 |
-
padding: 10px;
|
| 189 |
-
font-weight: bold;
|
| 190 |
-
text-align: center;
|
| 191 |
-
font-size: 2.5rem;
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
textarea, input {
|
| 195 |
-
background: transparent;
|
| 196 |
-
color: black;
|
| 197 |
-
border: 2px solid orange;
|
| 198 |
-
padding: 8px;
|
| 199 |
-
font-size: 1rem;
|
| 200 |
-
caret-color: black;
|
| 201 |
-
outline: none;
|
| 202 |
-
border-radius: 8px;
|
| 203 |
-
}
|
| 204 |
-
|
| 205 |
-
textarea:focus, input:focus {
|
| 206 |
-
background: transparent;
|
| 207 |
-
color: black;
|
| 208 |
-
border: 2px solid orange;
|
| 209 |
-
outline: none;
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
textarea:hover, input:hover {
|
| 213 |
-
background: transparent;
|
| 214 |
-
color: black;
|
| 215 |
-
border: 2px solid orange;
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
.df-container {
|
| 219 |
-
background: white;
|
| 220 |
-
color: black;
|
| 221 |
-
border: 2px solid orange;
|
| 222 |
-
border-radius: 10px;
|
| 223 |
-
padding: 10px;
|
| 224 |
-
font-size: 14px;
|
| 225 |
-
max-height: 400px;
|
| 226 |
-
height: auto;
|
| 227 |
-
overflow-y: auto;
|
| 228 |
-
}
|
| 229 |
-
|
| 230 |
-
#suggestions-title {
|
| 231 |
-
text-align: center !important; /* Ensure the centering is applied */
|
| 232 |
-
font-weight: bold !important; /* Ensure bold is applied */
|
| 233 |
-
color: white !important; /* Ensure color is applied */
|
| 234 |
-
font-size: 4.2rem !important; /* Ensure font size is applied */
|
| 235 |
-
margin-bottom: 20px !important; /* Ensure margin is applied */
|
| 236 |
-
}
|
| 237 |
-
|
| 238 |
-
/* Style for the submit button */
|
| 239 |
-
.gr-button {
|
| 240 |
-
background-color: #ae1c93; /* Set the background color to #ae1c93 */
|
| 241 |
-
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
|
| 242 |
-
transition: background-color 0.3s ease;
|
| 243 |
-
}
|
| 244 |
-
|
| 245 |
-
.gr-button:hover {
|
| 246 |
-
background-color: #8f167b;
|
| 247 |
-
}
|
| 248 |
-
|
| 249 |
-
.gr-button:active {
|
| 250 |
-
background-color: #7f156b;
|
| 251 |
-
}
|
| 252 |
-
"""
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
gr.
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
gr.
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
app.launch()
|
|
|
|
| 1 |
+
import os
|
| 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
|
| 10 |
+
from nltk.stem.lancaster import LancasterStemmer
|
| 11 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 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")
|
| 22 |
+
stemmer = LancasterStemmer()
|
| 23 |
+
|
| 24 |
+
# Load intents and chatbot training data
|
| 25 |
+
with open("intents.json") as file:
|
| 26 |
+
intents_data = json.load(file)
|
| 27 |
+
|
| 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")
|
| 42 |
+
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 43 |
+
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 44 |
+
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 45 |
+
|
| 46 |
+
# Google Maps API Client
|
| 47 |
+
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
| 48 |
+
|
| 49 |
+
# Helper Functions
|
| 50 |
+
def bag_of_words(s, words):
|
| 51 |
+
"""Convert user input to bag-of-words vector."""
|
| 52 |
+
bag = [0] * len(words)
|
| 53 |
+
s_words = word_tokenize(s)
|
| 54 |
+
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
| 55 |
+
for se in s_words:
|
| 56 |
+
for i, w in enumerate(words):
|
| 57 |
+
if w == se:
|
| 58 |
+
bag[i] = 1
|
| 59 |
+
return np.array(bag)
|
| 60 |
+
|
| 61 |
+
def generate_chatbot_response(message, history):
|
| 62 |
+
"""Generate chatbot response and maintain conversation history."""
|
| 63 |
+
history = history or []
|
| 64 |
+
try:
|
| 65 |
+
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 66 |
+
tag = labels[np.argmax(result)]
|
| 67 |
+
response = "I'm sorry, I didn't understand that. 🤔"
|
| 68 |
+
for intent in intents_data["intents"]:
|
| 69 |
+
if intent["tag"] == tag:
|
| 70 |
+
response = random.choice(intent["responses"])
|
| 71 |
+
break
|
| 72 |
+
except Exception as e:
|
| 73 |
+
response = f"Error: {e}"
|
| 74 |
+
history.append((message, response))
|
| 75 |
+
return history, response
|
| 76 |
+
|
| 77 |
+
def analyze_sentiment(user_input):
|
| 78 |
+
"""Analyze sentiment and map to emojis."""
|
| 79 |
+
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 80 |
+
with torch.no_grad():
|
| 81 |
+
outputs = model_sentiment(**inputs)
|
| 82 |
+
sentiment_class = torch.argmax(outputs.logits, dim=1).item()
|
| 83 |
+
sentiment_map = ["Negative 😔", "Neutral 😐", "Positive 😊"]
|
| 84 |
+
return f"Sentiment: {sentiment_map[sentiment_class]}"
|
| 85 |
+
|
| 86 |
+
def detect_emotion(user_input):
|
| 87 |
+
"""Detect emotions based on input."""
|
| 88 |
+
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 89 |
+
result = pipe(user_input)
|
| 90 |
+
emotion = result[0]["label"].lower().strip()
|
| 91 |
+
emotion_map = {
|
| 92 |
+
"joy": "Joy 😊",
|
| 93 |
+
"anger": "Anger 😠",
|
| 94 |
+
"sadness": "Sadness 😢",
|
| 95 |
+
"fear": "Fear 😨",
|
| 96 |
+
"surprise": "Surprise 😲",
|
| 97 |
+
"neutral": "Neutral 😐",
|
| 98 |
+
}
|
| 99 |
+
return emotion_map.get(emotion, "Unknown 🤔"), emotion
|
| 100 |
+
|
| 101 |
+
def generate_suggestions(emotion):
|
| 102 |
+
"""Return relevant suggestions based on detected emotions."""
|
| 103 |
+
emotion_key = emotion.lower()
|
| 104 |
+
suggestions = {
|
| 105 |
+
"joy": [
|
| 106 |
+
["Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
|
| 107 |
+
["Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 108 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 109 |
+
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
| 110 |
+
],
|
| 111 |
+
"anger": [
|
| 112 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 113 |
+
["Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"],
|
| 114 |
+
["Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 115 |
+
["Relaxation Video", "https://youtu.be/MIc299Flibs"],
|
| 116 |
+
],
|
| 117 |
+
"fear": [
|
| 118 |
+
["Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
|
| 119 |
+
["Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 120 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 121 |
+
["Relaxation Video", "https://youtu.be/yGKKz185M5o"],
|
| 122 |
+
],
|
| 123 |
+
"sadness": [
|
| 124 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
| 125 |
+
["Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 126 |
+
["Relaxation Video", "https://youtu.be/-e-4Kx5px_I"],
|
| 127 |
+
],
|
| 128 |
+
"surprise": [
|
| 129 |
+
["Managing Stress", "https://www.health.harvard.edu/health-a-to-z"],
|
| 130 |
+
["Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
| 131 |
+
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
| 132 |
+
],
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
# Format the output to include HTML anchor tags
|
| 136 |
+
formatted_suggestions = [
|
| 137 |
+
[title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
|
| 138 |
+
]
|
| 139 |
+
|
| 140 |
+
return formatted_suggestions
|
| 141 |
+
|
| 142 |
+
def get_health_professionals_and_map(location, query):
|
| 143 |
+
"""Search nearby healthcare professionals using Google Maps API."""
|
| 144 |
+
try:
|
| 145 |
+
if not location or not query:
|
| 146 |
+
return [], "" # Return empty list if inputs are missing
|
| 147 |
+
|
| 148 |
+
geo_location = gmaps.geocode(location)
|
| 149 |
+
if geo_location:
|
| 150 |
+
lat, lng = geo_location[0]["geometry"]["location"].values()
|
| 151 |
+
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
| 152 |
+
professionals = []
|
| 153 |
+
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
| 154 |
+
for place in places_result:
|
| 155 |
+
# Use a list of values to append each professional
|
| 156 |
+
professionals.append([place['name'], place.get('vicinity', 'No address provided')])
|
| 157 |
+
folium.Marker(
|
| 158 |
+
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
| 159 |
+
popup=f"{place['name']}"
|
| 160 |
+
).add_to(map_)
|
| 161 |
+
return professionals, map_._repr_html_()
|
| 162 |
+
|
| 163 |
+
return [], "" # Return empty list if no professionals found
|
| 164 |
+
except Exception as e:
|
| 165 |
+
return [], "" # Return empty list on exception
|
| 166 |
+
|
| 167 |
+
# Main Application Logic
|
| 168 |
+
def app_function(user_input, location, query, history):
|
| 169 |
+
chatbot_history, _ = generate_chatbot_response(user_input, history)
|
| 170 |
+
sentiment_result = analyze_sentiment(user_input)
|
| 171 |
+
emotion_result, cleaned_emotion = detect_emotion(user_input)
|
| 172 |
+
suggestions = generate_suggestions(cleaned_emotion)
|
| 173 |
+
professionals, map_html = get_health_professionals_and_map(location, query)
|
| 174 |
+
return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
|
| 175 |
+
|
| 176 |
+
# CSS Styling
|
| 177 |
+
custom_css = """
|
| 178 |
+
body {
|
| 179 |
+
font-family: 'Roboto', sans-serif;
|
| 180 |
+
background-color: #3c6487; /* Set the background color */
|
| 181 |
+
color: white;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
h1 {
|
| 185 |
+
background: #ffffff;
|
| 186 |
+
color: #000000;
|
| 187 |
+
border-radius: 8px;
|
| 188 |
+
padding: 10px;
|
| 189 |
+
font-weight: bold;
|
| 190 |
+
text-align: center;
|
| 191 |
+
font-size: 2.5rem;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
textarea, input {
|
| 195 |
+
background: transparent;
|
| 196 |
+
color: black;
|
| 197 |
+
border: 2px solid orange;
|
| 198 |
+
padding: 8px;
|
| 199 |
+
font-size: 1rem;
|
| 200 |
+
caret-color: black;
|
| 201 |
+
outline: none;
|
| 202 |
+
border-radius: 8px;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
textarea:focus, input:focus {
|
| 206 |
+
background: transparent;
|
| 207 |
+
color: black;
|
| 208 |
+
border: 2px solid orange;
|
| 209 |
+
outline: none;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
textarea:hover, input:hover {
|
| 213 |
+
background: transparent;
|
| 214 |
+
color: black;
|
| 215 |
+
border: 2px solid orange;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
.df-container {
|
| 219 |
+
background: white;
|
| 220 |
+
color: black;
|
| 221 |
+
border: 2px solid orange;
|
| 222 |
+
border-radius: 10px;
|
| 223 |
+
padding: 10px;
|
| 224 |
+
font-size: 14px;
|
| 225 |
+
max-height: 400px;
|
| 226 |
+
height: auto;
|
| 227 |
+
overflow-y: auto;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
#suggestions-title {
|
| 231 |
+
text-align: center !important; /* Ensure the centering is applied */
|
| 232 |
+
font-weight: bold !important; /* Ensure bold is applied */
|
| 233 |
+
color: white !important; /* Ensure color is applied */
|
| 234 |
+
font-size: 4.2rem !important; /* Ensure font size is applied */
|
| 235 |
+
margin-bottom: 20px !important; /* Ensure margin is applied */
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
/* Style for the submit button */
|
| 239 |
+
.gr-button {
|
| 240 |
+
background-color: #ae1c93; /* Set the background color to #ae1c93 */
|
| 241 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
|
| 242 |
+
transition: background-color 0.3s ease;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
.gr-button:hover {
|
| 246 |
+
background-color: #8f167b;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
.gr-button:active {
|
| 250 |
+
background-color: #7f156b;
|
| 251 |
+
}
|
| 252 |
+
"""
|
| 253 |
+
# Gradio Application
|
| 254 |
+
with gr.Blocks(css=custom_css) as app:
|
| 255 |
+
gr.HTML("<h1>🌟 Well-Being Companion</h1>")
|
| 256 |
+
with gr.Row():
|
| 257 |
+
user_input = gr.Textbox(label="Please Enter Your Message Here")
|
| 258 |
+
location = gr.Textbox(label="Please Enter Your Current Location Here")
|
| 259 |
+
query = gr.Textbox(label="Please Enter Which Health Professional You Want To Search Nearby")
|
| 260 |
+
|
| 261 |
+
# New Predict Disease Button
|
| 262 |
+
predict_disease = gr.Button(value="Predict Disease", variant="secondary")
|
| 263 |
+
predict_disease.click(lambda: None, _js="window.open('https://huggingface.co/spaces/Mishal23/wellBeing', '_blank')")
|
| 264 |
+
|
| 265 |
+
# Existing Submit Button
|
| 266 |
+
submit = gr.Button(value="Submit", variant="primary")
|
| 267 |
+
|
| 268 |
+
chatbot = gr.Chatbot(label="Chat History")
|
| 269 |
+
sentiment = gr.Textbox(label="Detected Sentiment")
|
| 270 |
+
emotion = gr.Textbox(label="Detected Emotion")
|
| 271 |
+
|
| 272 |
+
# Adding Suggestions Title with Styled Markdown (Centered and Bold)
|
| 273 |
+
gr.Markdown("Suggestions", elem_id="suggestions-title")
|
| 274 |
+
|
| 275 |
+
suggestions = gr.DataFrame(headers=["Title", "Link"]) # Table for suggestions
|
| 276 |
+
professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"]) # Changed to DataFrame
|
| 277 |
+
map_html = gr.HTML(label="Interactive Map")
|
| 278 |
+
|
| 279 |
+
submit.click(
|
| 280 |
+
app_function,
|
| 281 |
+
inputs=[user_input, location, query, chatbot],
|
| 282 |
+
outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html],
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
app.launch()
|