Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,6 +8,7 @@ import gradio as gr
|
|
8 |
import requests
|
9 |
import torch
|
10 |
import pandas as pd
|
|
|
11 |
from bs4 import BeautifulSoup
|
12 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
13 |
from nltk.tokenize import word_tokenize
|
@@ -83,7 +84,8 @@ def chat(message, history):
|
|
83 |
response = f"An error occurred: {str(e)}"
|
84 |
|
85 |
history.append((message, response))
|
86 |
-
return history,
|
|
|
87 |
|
88 |
# Sentiment analysis setup
|
89 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
@@ -97,59 +99,51 @@ def load_emotion_model():
|
|
97 |
|
98 |
tokenizer_emotion, model_emotion = load_emotion_model()
|
99 |
|
100 |
-
# Emotion detection function with suggestions
|
101 |
def detect_emotion(user_input):
|
102 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
103 |
result = pipe(user_input)
|
104 |
emotion = result[0]['label']
|
105 |
|
106 |
-
|
|
|
|
|
|
|
107 |
if emotion == 'joy':
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
{"subject": "Emotional Wellness Toolkit", "heading": "Emotional Wellness Resources", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "https://youtu.be/m1vaUGtyo-A"}
|
113 |
]
|
114 |
-
|
115 |
elif emotion == 'anger':
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
{"subject": "Dealing with Anger", "heading": "Strategies to Calm Anger", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/MIc299Flibs"}
|
121 |
]
|
122 |
-
|
123 |
elif emotion == 'fear':
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
{"subject": "Emotional Wellness Toolkit", "heading": "Calming Your Mind", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "https://youtu.be/yGKKz185M5o"}
|
129 |
]
|
130 |
-
|
131 |
elif emotion == 'sadness':
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
{"subject": "Dealing with Anxiety", "heading": "Coping Strategies for Stress", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/-e-4Kx5px_I"}
|
136 |
]
|
137 |
-
|
138 |
elif emotion == 'surprise':
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
{"subject": "Coping Strategies", "heading": "Dealing with Unexpected Events", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/m1vaUGtyo-A"}
|
143 |
]
|
144 |
-
|
145 |
-
else:
|
146 |
-
emotion_msg = "Could not detect emotion."
|
147 |
-
resources = []
|
148 |
-
|
149 |
-
# Create a DataFrame for resources to display in table format
|
150 |
-
resource_df = pd.DataFrame(resources)
|
151 |
|
152 |
-
return
|
153 |
|
154 |
# Google Geocoding API setup to convert city name to latitude/longitude
|
155 |
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json"
|
@@ -168,86 +162,90 @@ def get_lat_lon(location, api_key):
|
|
168 |
return location['lat'], location['lng']
|
169 |
return None, None
|
170 |
|
171 |
-
#
|
172 |
-
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
173 |
-
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
|
174 |
-
api_key = os.getenv("GOOGLE_API_KEY") # Use environment variable for security
|
175 |
-
|
176 |
-
# Function to get places data using Google Places API
|
177 |
-
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
178 |
-
params = {
|
179 |
-
'query': query,
|
180 |
-
'location': location,
|
181 |
-
'radius': radius,
|
182 |
-
'key': api_key
|
183 |
-
}
|
184 |
-
if next_page_token:
|
185 |
-
params['pagetoken'] = next_page_token
|
186 |
-
|
187 |
-
response = requests.get(url, params=params)
|
188 |
-
return response.json()
|
189 |
-
|
190 |
-
# Function to fetch wellness professionals
|
191 |
def get_wellness_professionals(location, api_key):
|
|
|
|
|
|
|
|
|
192 |
lat, lon = get_lat_lon(location, api_key)
|
193 |
|
194 |
-
if lat
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
|
216 |
-
# Gradio interface
|
217 |
-
def
|
218 |
-
history = history
|
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 |
-
|
244 |
-
# Gradio
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
)
|
252 |
|
253 |
-
|
|
|
|
|
|
8 |
import requests
|
9 |
import torch
|
10 |
import pandas as pd
|
11 |
+
import folium
|
12 |
from bs4 import BeautifulSoup
|
13 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
14 |
from nltk.tokenize import word_tokenize
|
|
|
84 |
response = f"An error occurred: {str(e)}"
|
85 |
|
86 |
history.append((message, response))
|
87 |
+
return history, history
|
88 |
+
|
89 |
|
90 |
# Sentiment analysis setup
|
91 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
|
|
99 |
|
100 |
tokenizer_emotion, model_emotion = load_emotion_model()
|
101 |
|
102 |
+
# Emotion detection function with suggestions
|
103 |
def detect_emotion(user_input):
|
104 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
105 |
result = pipe(user_input)
|
106 |
emotion = result[0]['label']
|
107 |
|
108 |
+
suggestions = []
|
109 |
+
video_link = ""
|
110 |
+
|
111 |
+
# Provide suggestions based on the detected emotion
|
112 |
if emotion == 'joy':
|
113 |
+
suggestions = [
|
114 |
+
("Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
|
115 |
+
("Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
|
116 |
+
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")
|
|
|
117 |
]
|
118 |
+
video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A"
|
119 |
elif emotion == 'anger':
|
120 |
+
suggestions = [
|
121 |
+
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
|
122 |
+
("Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"),
|
123 |
+
("Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
|
|
|
124 |
]
|
125 |
+
video_link = "Watch on YouTube: https://youtu.be/MIc299Flibs"
|
126 |
elif emotion == 'fear':
|
127 |
+
suggestions = [
|
128 |
+
("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
|
129 |
+
("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
|
130 |
+
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")
|
|
|
131 |
]
|
132 |
+
video_link = "Watch on YouTube: https://youtu.be/yGKKz185M5o"
|
133 |
elif emotion == 'sadness':
|
134 |
+
suggestions = [
|
135 |
+
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
|
136 |
+
("Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
|
|
|
137 |
]
|
138 |
+
video_link = "Watch on YouTube: https://youtu.be/-e-4Kx5px_I"
|
139 |
elif emotion == 'surprise':
|
140 |
+
suggestions = [
|
141 |
+
("Managing Stress", "https://www.health.harvard.edu/health-a-to-z"),
|
142 |
+
("Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
|
|
|
143 |
]
|
144 |
+
video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A"
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
|
146 |
+
return emotion, suggestions, video_link
|
147 |
|
148 |
# Google Geocoding API setup to convert city name to latitude/longitude
|
149 |
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json"
|
|
|
162 |
return location['lat'], location['lng']
|
163 |
return None, None
|
164 |
|
165 |
+
# Get wellness professionals
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
def get_wellness_professionals(location, api_key):
|
167 |
+
query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist OR nutritionist OR wellness doctor OR holistic practitioner OR integrative medicine OR chiropractor OR naturopath"
|
168 |
+
radius = 50000 # 50 km radius
|
169 |
+
|
170 |
+
# Get the latitude and longitude from the location input
|
171 |
lat, lon = get_lat_lon(location, api_key)
|
172 |
|
173 |
+
if lat is None or lon is None:
|
174 |
+
return "Unable to find coordinates for the given location."
|
175 |
+
|
176 |
+
# Using Google Places API to fetch wellness professionals
|
177 |
+
data = get_places_data(query, f"{lat},{lon}", radius, api_key)
|
178 |
+
|
179 |
+
if data:
|
180 |
+
results = data.get('results', [])
|
181 |
+
wellness_data = []
|
182 |
+
for place in results:
|
183 |
+
name = place.get("name")
|
184 |
+
address = place.get("formatted_address")
|
185 |
+
latitude = place.get("geometry", {}).get("location", {}).get("lat")
|
186 |
+
longitude = place.get("geometry", {}).get("location", {}).get("lng")
|
187 |
+
wellness_data.append([name, address, latitude, longitude])
|
188 |
+
return wellness_data
|
189 |
+
|
190 |
+
return []
|
191 |
+
|
192 |
+
# Function to generate a map with wellness professionals
|
193 |
+
def generate_map(wellness_data):
|
194 |
+
map_center = [23.685, 90.3563] # Default center for Bangladesh (you can adjust this)
|
195 |
+
m = folium.Map(location=map_center, zoom_start=12)
|
196 |
+
|
197 |
+
for place in wellness_data:
|
198 |
+
name, address, lat, lon = place
|
199 |
+
folium.Marker(
|
200 |
+
location=[lat, lon],
|
201 |
+
popup=f"<b>{name}</b><br>{address}",
|
202 |
+
icon=folium.Icon(color='blue', icon='info-sign')
|
203 |
+
).add_to(m)
|
204 |
+
|
205 |
+
# Save map as an HTML file
|
206 |
+
map_file = "wellness_map.html"
|
207 |
+
m.save(map_file)
|
208 |
+
|
209 |
+
# Return the HTML file path to be embedded in Gradio
|
210 |
+
return map_file
|
211 |
|
212 |
+
# Gradio interface setup for user interaction
|
213 |
+
def user_interface(message, location, history, api_key):
|
214 |
+
history, history = chat(message, history)
|
215 |
|
216 |
+
# Sentiment analysis
|
217 |
+
inputs = tokenizer_sentiment(message, return_tensors="pt")
|
218 |
+
outputs = model_sentiment(**inputs)
|
219 |
+
sentiment = ["Negative", "Neutral", "Positive"][torch.argmax(outputs.logits, dim=1).item()]
|
220 |
+
|
221 |
+
# Emotion detection
|
222 |
+
emotion, resources, video_link = detect_emotion(message)
|
223 |
+
|
224 |
+
# Get wellness professionals
|
225 |
+
wellness_data = get_wellness_professionals(location, api_key)
|
226 |
+
|
227 |
+
# Generate the map
|
228 |
+
map_file = generate_map(wellness_data)
|
229 |
+
|
230 |
+
# Create a DataFrame for the suggestions
|
231 |
+
suggestions_df = pd.DataFrame(resources, columns=["Subject", "Article URL"])
|
232 |
+
suggestions_df["Video URL"] = video_link # Add video URL column
|
233 |
+
|
234 |
+
return history, history, sentiment, emotion, resources, video_link, map_file, suggestions_df.to_html(escape=False)
|
235 |
+
|
236 |
+
# Gradio chatbot interface
|
237 |
+
chatbot = gr.Chatbot(label="Mental Health Chatbot")
|
238 |
+
location_input = gr.Textbox(label="Enter your location (latitude,longitude)", placeholder="e.g., 21.3,-157.8")
|
239 |
+
|
240 |
+
# Gradio interface definition
|
241 |
+
demo = gr.Interface(
|
242 |
+
user_interface,
|
243 |
+
[gr.Textbox(label="Message"), location_input, "state", "text"],
|
244 |
+
[chatbot, "state", "text", "text", "json", "text", "html", "html"], # Added additional output for the map
|
245 |
+
allow_flagging="never",
|
246 |
+
title="Mental Health & Well-being Assistant"
|
247 |
)
|
248 |
|
249 |
+
# Launch Gradio interface
|
250 |
+
if __name__ == "__main__":
|
251 |
+
demo.launch()
|