Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,7 +13,7 @@ import googlemaps
|
|
13 |
import folium
|
14 |
import torch
|
15 |
|
16 |
-
# Suppress TensorFlow
|
17 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
18 |
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
19 |
|
@@ -21,14 +21,14 @@ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
|
21 |
nltk.download("punkt")
|
22 |
stemmer = LancasterStemmer()
|
23 |
|
24 |
-
# Load intents
|
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
|
32 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
33 |
net = tflearn.fully_connected(net, 8)
|
34 |
net = tflearn.fully_connected(net, 8)
|
@@ -37,7 +37,7 @@ net = tflearn.regression(net)
|
|
37 |
chatbot_model = tflearn.DNN(net)
|
38 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
39 |
|
40 |
-
# Hugging Face
|
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")
|
@@ -58,8 +58,8 @@ def bag_of_words(s, words):
|
|
58 |
bag[i] = 1
|
59 |
return np.array(bag)
|
60 |
|
61 |
-
def
|
62 |
-
"""Generate chatbot response and maintain
|
63 |
history = history or []
|
64 |
try:
|
65 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
@@ -75,7 +75,7 @@ def chatbot(message, history):
|
|
75 |
return history, response
|
76 |
|
77 |
def analyze_sentiment(user_input):
|
78 |
-
"""Analyze sentiment
|
79 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
80 |
with torch.no_grad():
|
81 |
outputs = model_sentiment(**inputs)
|
@@ -84,7 +84,7 @@ def analyze_sentiment(user_input):
|
|
84 |
return f"Sentiment: {sentiment_map[sentiment_class]}"
|
85 |
|
86 |
def detect_emotion(user_input):
|
87 |
-
"""Detect
|
88 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
89 |
result = pipe(user_input)
|
90 |
emotion = result[0]["label"].lower().strip()
|
@@ -96,46 +96,48 @@ def detect_emotion(user_input):
|
|
96 |
"surprise": "Surprise π²",
|
97 |
"neutral": "Neutral π",
|
98 |
}
|
99 |
-
return emotion_map.get(emotion, "Unknown π€"), emotion # Text
|
100 |
|
101 |
def generate_suggestions(emotion):
|
102 |
-
"""
|
|
|
103 |
suggestions = {
|
104 |
"joy": [
|
105 |
-
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation
|
106 |
["Emotional Toolkit", '<a href="https://www.nih.gov" target="_blank">Visit</a>'],
|
107 |
["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
108 |
],
|
109 |
"anger": [
|
110 |
-
["
|
111 |
-
["
|
112 |
],
|
113 |
"fear": [
|
114 |
-
["
|
|
|
115 |
],
|
116 |
"sadness": [
|
117 |
-
["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
|
118 |
],
|
119 |
"surprise": [
|
120 |
["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
121 |
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
122 |
],
|
123 |
"neutral": [
|
124 |
-
["General
|
125 |
-
]
|
126 |
}
|
127 |
-
return suggestions.get(
|
128 |
|
129 |
def get_health_professionals_and_map(location, query):
|
130 |
-
"""Search
|
131 |
try:
|
132 |
if not location or not query:
|
133 |
-
return ["Please provide both
|
|
|
134 |
geo_location = gmaps.geocode(location)
|
135 |
if geo_location:
|
136 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
137 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
138 |
-
|
139 |
professionals = []
|
140 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
141 |
for place in places_result:
|
@@ -144,87 +146,44 @@ def get_health_professionals_and_map(location, query):
|
|
144 |
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
145 |
popup=f"{place['name']}"
|
146 |
).add_to(map_)
|
147 |
-
|
148 |
return professionals, map_._repr_html_()
|
149 |
|
150 |
-
return ["No professionals found
|
151 |
except Exception as e:
|
152 |
-
return [f"
|
153 |
|
154 |
-
# Main Application
|
155 |
def app_function(user_input, location, query, history):
|
156 |
-
chatbot_history, _ =
|
157 |
-
|
158 |
-
|
159 |
-
suggestions = generate_suggestions(
|
160 |
-
professionals, map_html = get_health_professionals_and_map(location, query) #
|
161 |
-
return chatbot_history,
|
162 |
-
|
163 |
-
#
|
164 |
custom_css = """
|
165 |
-
body {
|
166 |
-
|
167 |
-
font-family: 'Roboto', sans-serif;
|
168 |
-
color: white;
|
169 |
-
}
|
170 |
-
h1 {
|
171 |
-
font-size: 4.5rem;
|
172 |
-
font-weight: bold;
|
173 |
-
text-align: center;
|
174 |
-
margin: 20px auto;
|
175 |
-
}
|
176 |
-
h2 {
|
177 |
-
font-size: 2rem;
|
178 |
-
text-align: center;
|
179 |
-
margin-bottom: 30px;
|
180 |
-
color: white;
|
181 |
-
font-weight: lighter;
|
182 |
-
}
|
183 |
-
button {
|
184 |
-
background: linear-gradient(45deg, #ff5722, #ff9800);
|
185 |
-
border: none;
|
186 |
-
color: white;
|
187 |
-
padding: 12px 20px;
|
188 |
-
font-size: 16px;
|
189 |
-
border-radius: 8px;
|
190 |
-
cursor: pointer;
|
191 |
-
}
|
192 |
-
textarea, input {
|
193 |
-
background: black;
|
194 |
-
color: white;
|
195 |
-
border: 1px solid #ff5722;
|
196 |
-
padding: 12px;
|
197 |
-
border-radius: 8px;
|
198 |
-
}
|
199 |
-
.gr-dataframe {
|
200 |
-
background-color: black !important;
|
201 |
-
color: white !important;
|
202 |
-
overflow: auto;
|
203 |
-
border: 1px solid orange;
|
204 |
-
}
|
205 |
"""
|
206 |
|
207 |
-
# Gradio UI Interface
|
208 |
with gr.Blocks(css=custom_css) as app:
|
209 |
-
gr.HTML("<h1>π Well-Being Companion</h1>")
|
210 |
-
gr.HTML("<h2>Empowering Your Mental Health Journey π</h2>")
|
211 |
-
|
212 |
with gr.Row():
|
213 |
-
|
214 |
-
location = gr.Textbox(label="Your Location"
|
215 |
-
query = gr.Textbox(label="Search Query"
|
216 |
-
|
217 |
chatbot = gr.Chatbot(label="Chat History")
|
218 |
sentiment = gr.Textbox(label="Detected Sentiment")
|
219 |
emotion = gr.Textbox(label="Detected Emotion")
|
220 |
-
suggestions = gr.DataFrame(headers=["
|
221 |
professionals = gr.Textbox(label="Nearby Professionals", lines=6)
|
222 |
map_html = gr.HTML(label="Interactive Map")
|
|
|
223 |
|
224 |
-
|
225 |
-
submit_button.click(
|
226 |
app_function,
|
227 |
-
inputs=[
|
228 |
outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html]
|
229 |
)
|
230 |
|
|
|
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 |
|
|
|
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)
|
|
|
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")
|
|
|
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)])
|
|
|
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)
|
|
|
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()
|
|
|
96 |
"surprise": "Surprise π²",
|
97 |
"neutral": "Neutral π",
|
98 |
}
|
99 |
+
return emotion_map.get(emotion, "Unknown π€"), emotion # Text with matching key
|
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", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
|
107 |
["Emotional Toolkit", '<a href="https://www.nih.gov" target="_blank">Visit</a>'],
|
108 |
["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
109 |
],
|
110 |
"anger": [
|
111 |
+
["Handle Anger", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
|
112 |
+
["Stress Tips", '<a href="https://www.helpguide.org/mental-health/anger-management.htm" target="_blank">Visit</a>'],
|
113 |
],
|
114 |
"fear": [
|
115 |
+
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
116 |
+
["Mindfulness", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
|
117 |
],
|
118 |
"sadness": [
|
119 |
+
["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
|
120 |
],
|
121 |
"surprise": [
|
122 |
["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
123 |
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
124 |
],
|
125 |
"neutral": [
|
126 |
+
["General Well-Being Tips", '<a href="https://www.psychologytoday.com" target="_blank">Visit</a>'],
|
127 |
+
],
|
128 |
}
|
129 |
+
return suggestions.get(emotion_key, [["No specific suggestions available.", ""]])
|
130 |
|
131 |
def get_health_professionals_and_map(location, query):
|
132 |
+
"""Search nearby healthcare professionals using Google Maps API."""
|
133 |
try:
|
134 |
if not location or not query:
|
135 |
+
return ["Please provide both location and query."], ""
|
136 |
+
|
137 |
geo_location = gmaps.geocode(location)
|
138 |
if geo_location:
|
139 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
140 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
|
|
141 |
professionals = []
|
142 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
143 |
for place in places_result:
|
|
|
146 |
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
147 |
popup=f"{place['name']}"
|
148 |
).add_to(map_)
|
|
|
149 |
return professionals, map_._repr_html_()
|
150 |
|
151 |
+
return ["No professionals found for the given location."], ""
|
152 |
except Exception as e:
|
153 |
+
return [f"An error occurred: {e}"], ""
|
154 |
|
155 |
+
# Main Application Logic
|
156 |
def app_function(user_input, location, query, history):
|
157 |
+
chatbot_history, _ = generate_chatbot_response(user_input, history) # Generate chatbot response
|
158 |
+
sentiment_result = analyze_sentiment(user_input) # Sentiment detection
|
159 |
+
emotion_result, cleaned_emotion = detect_emotion(user_input) # Emotion detection
|
160 |
+
suggestions = generate_suggestions(cleaned_emotion) # Fetch suggestions for emotion
|
161 |
+
professionals, map_html = get_health_professionals_and_map(location, query) # Nearby professionals with map
|
162 |
+
return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
|
163 |
+
|
164 |
+
# Gradio Interface
|
165 |
custom_css = """
|
166 |
+
body { background: linear-gradient(135deg,#0d0d0d,#ff5722); color: white; }
|
167 |
+
textarea, input { background: black; color: white; border: 2px solid orange; padding: 10px }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
"""
|
169 |
|
|
|
170 |
with gr.Blocks(css=custom_css) as app:
|
171 |
+
gr.HTML("<h1 style='text-align: center'>π Well-Being Companion</h1>")
|
|
|
|
|
172 |
with gr.Row():
|
173 |
+
user_input = gr.Textbox(label="Your Message")
|
174 |
+
location = gr.Textbox(label="Your Location")
|
175 |
+
query = gr.Textbox(label="Search Query")
|
|
|
176 |
chatbot = gr.Chatbot(label="Chat History")
|
177 |
sentiment = gr.Textbox(label="Detected Sentiment")
|
178 |
emotion = gr.Textbox(label="Detected Emotion")
|
179 |
+
suggestions = gr.DataFrame(headers=["Title", "Link"])
|
180 |
professionals = gr.Textbox(label="Nearby Professionals", lines=6)
|
181 |
map_html = gr.HTML(label="Interactive Map")
|
182 |
+
submit = gr.Button("Submit")
|
183 |
|
184 |
+
submit.click(
|
|
|
185 |
app_function,
|
186 |
+
inputs=[user_input, location, query, chatbot],
|
187 |
outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html]
|
188 |
)
|
189 |
|