DreamStream-1 commited on
Commit
ebca5ff
·
verified ·
1 Parent(s): 5b95047

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -114
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, response
 
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 in plain English and resources in table
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
- # Define emotion-specific message and resources
 
 
 
107
  if emotion == 'joy':
108
- emotion_msg = "You're feeling happy! Keep up the great mood!"
109
- resources = [
110
- {"subject": "Relaxation Techniques", "heading": "Mindful Breathing Meditation", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation", "video_url": "https://youtu.be/m1vaUGtyo-A"},
111
- {"subject": "Dealing with Stress", "heading": "Tips for Dealing with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/m1vaUGtyo-A"},
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
- emotion_msg = "You're feeling angry. It's okay to feel this way. Let's try to calm down."
117
- resources = [
118
- {"subject": "Emotional Wellness Toolkit", "heading": "Managing Emotions", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "https://youtu.be/MIc299Flibs"},
119
- {"subject": "Stress Management Tips", "heading": "Managing Stress Effectively", "link": "https://www.health.harvard.edu/health-a-to-z", "video_url": "https://youtu.be/MIc299Flibs"},
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
- emotion_msg = "You're feeling fearful. Take a moment to breathe and relax."
125
- resources = [
126
- {"subject": "Mindfulness Practices", "heading": "Breathing Techniques", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation", "video_url": "https://youtu.be/yGKKz185M5o"},
127
- {"subject": "Coping with Anxiety", "heading": "Overcoming Fear", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/yGKKz185M5o"},
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
- emotion_msg = "You're feeling sad. It's okay to take a break."
133
- resources = [
134
- {"subject": "Emotional Wellness Toolkit", "heading": "Restoring Your Emotional Health", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "https://youtu.be/-e-4Kx5px_I"},
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
- emotion_msg = "You're feeling surprised. It's okay to feel neutral!"
140
- resources = [
141
- {"subject": "Managing Stress", "heading": "Relaxation Tips", "link": "https://www.health.harvard.edu/health-a-to-z", "video_url": "https://youtu.be/m1vaUGtyo-A"},
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 emotion_msg, resource_df
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
- # Google Places API setup for wellness professionals
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 and lon:
195
- places = get_places_data("wellness professional", f"{lat},{lon}", 10000, api_key)
196
-
197
- if places and 'results' in places:
198
- professionals = []
199
- for place in places['results']:
200
- name = place.get("name", "No name available")
201
- rating = place.get("rating", "No rating available")
202
- address = place.get("formatted_address", "No address available")
203
- professionals.append({
204
- "Name": name,
205
- "Rating": rating,
206
- "Address": address
207
- })
208
-
209
- professionals_df = pd.DataFrame(professionals)
210
- return professionals_df
211
- else:
212
- return "No wellness professionals found nearby."
213
- else:
214
- return "Location not found. Please check the location."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
- # Gradio interface function to handle actions and outputs
217
- def interface_function(message, action, location, history):
218
- history = history or []
219
 
220
- if action == "Chat":
221
- # Use chat function if 'Chat' button is clicked
222
- history, response = chat(message, history)
223
- elif action == "Detect Emotion":
224
- # Use emotion detection if 'Detect Emotion' button is clicked
225
- emotion_msg, resource_df = detect_emotion(message)
226
- response = emotion_msg
227
- # Return the resource DataFrame as a table
228
- return history, response, resource_df
229
- elif action == "Wellness Resources":
230
- # Use location to get wellness professionals if 'Wellness Resources' is clicked
231
- if not location.strip():
232
- response = "Please enter a valid location."
233
- else:
234
- professionals_df = get_wellness_professionals(location, api_key)
235
- if isinstance(professionals_df, pd.DataFrame):
236
- response = "Found wellness professionals nearby:"
237
- return history, response, professionals_df
238
- else:
239
- response = professionals_df # If error message is returned
240
- return history, response, None
241
-
242
- return history, "Invalid action", None
243
-
244
- # Gradio Interface with table outputs for emotion and wellness professionals
245
- iface = gr.Interface(
246
- fn=interface_function,
247
- inputs=["text", "radio", "text", "state"], # Include state in the inputs
248
- outputs=["text", "dataframe", "state"], # Add state to the outputs
249
- live=True,
250
- allow_flagging="never"
251
  )
252
 
253
- iface.launch(share=True)
 
 
 
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()