DreamStream-1 commited on
Commit
ae282f5
Β·
verified Β·
1 Parent(s): 48a4b0f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -82
app.py CHANGED
@@ -83,9 +83,26 @@ def chat(message, history, state):
83
  else:
84
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  history.append((message, response))
87
 
88
- # Update state to move to the next feature
89
  state['step'] = 2 # Move to sentiment analysis
90
  except Exception as e:
91
  response = f"An error occurred: {str(e)}"
@@ -104,39 +121,80 @@ def analyze_sentiment(text, state):
104
  predicted_class = torch.argmax(outputs.logits, dim=1).item()
105
  sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
106
 
107
- # Update state to move to the next feature
 
 
 
 
 
 
 
 
108
  state['step'] = 3 # Move to emotion detection and suggestions
109
- return sentiment, state
110
 
111
  # Load pre-trained model and tokenizer for emotion detection
112
  emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
113
  emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
114
 
115
- # Function for emotion detection
116
  def detect_emotion(text, state):
117
  pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
118
  result = pipe(text)
119
  emotion = result[0]['label']
120
-
121
- # Provide suggestions based on emotion
122
  suggestions = provide_suggestions(emotion)
123
 
124
- # Update state to move to the next feature
125
  state['step'] = 4 # Move to wellness professional search
126
  return emotion, suggestions, state
127
 
128
  # Suggestions based on detected emotion
129
  def provide_suggestions(emotion):
130
- if emotion == 'joy':
131
- return "You're feeling happy! Keep up the great mood!"
132
- elif emotion == 'anger':
133
- return "You're feeling angry. It's okay to feel this way. Let's try to calm down."
134
- elif emotion == 'fear':
135
- return "You're feeling fearful. Take deep breaths, everything will be okay."
136
- elif emotion == 'sadness':
137
- return "You're feeling sad. It's okay, things will get better. You're not alone."
138
- else:
139
- return "Sorry, no suggestions available for this emotion."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  # Function to find wellness professionals
142
  def find_wellness_professionals(location, state):
@@ -152,73 +210,84 @@ def find_wellness_professionals(location, state):
152
  "User Ratings Total", "Website", "Types", "Latitude", "Longitude",
153
  "Opening Hours", "Reviews", "Email"
154
  ])
155
- return df, state
 
 
 
 
 
156
  else:
157
- return pd.DataFrame(), state
158
 
159
- # The functions for scraping websites and fetching details
160
  def get_all_places(query, location, radius, api_key):
161
- all_results = []
162
- next_page_token = None
163
- while True:
164
- data = get_places_data(query, location, radius, api_key, next_page_token)
165
- if data:
166
- results = data.get('results', [])
167
- for place in results:
168
- place_id = place.get("place_id")
169
- name = place.get("name")
170
- address = place.get("formatted_address")
171
- rating = place.get("rating", "Not available")
172
- business_status = place.get("business_status", "Not available")
173
- user_ratings_total = place.get("user_ratings_total", "Not available")
174
- website = place.get("website", "Not available")
175
- types = ", ".join(place.get("types", []))
176
- location = place.get("geometry", {}).get("location", {})
177
- latitude = location.get("lat", "Not available")
178
- longitude = location.get("lng", "Not available")
179
- details = get_place_details(place_id, api_key)
180
- phone_number = details.get("phone_number", "Not available")
181
- email = details.get("email", "Not available")
182
- all_results.append([name, address, phone_number, rating, business_status,
183
- user_ratings_total, website, types, latitude, longitude,
184
- details.get("opening_hours", "Not available"),
185
- details.get("reviews", "Not available"), email])
186
- next_page_token = data.get('next_page_token')
187
- if not next_page_token:
188
- break
189
- time.sleep(2)
190
- return all_results
191
 
192
- # Gradio interface
193
- with gr.Blocks() as demo:
194
- gr.Markdown("# Wellbeing Support System")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
- state = gr.State({"step": 1}) # Track the flow step
197
-
198
- with gr.Tab("Chatbot"):
199
- chatbot = gr.Chatbot()
200
- msg = gr.Textbox()
201
- clear = gr.Button("Clear")
202
- msg.submit(chat, inputs=[msg, chatbot, state], outputs=[chatbot, chatbot, state])
203
- clear.click(lambda: None, None, chatbot)
204
-
205
- with gr.Tab("Sentiment Analysis"):
206
- sentiment_output = gr.Textbox(label="Sentiment:")
207
- text_input = gr.Textbox(label="Enter text to analyze sentiment:")
208
- analyze_button = gr.Button("Analyze Sentiment")
209
- analyze_button.click(analyze_sentiment, inputs=[text_input, state], outputs=[sentiment_output, state])
210
-
211
- with gr.Tab("Emotion Detection & Suggestions"):
212
- emotion_input = gr.Textbox(label="How are you feeling today?", value="Enter your thoughts here...")
213
- detect_button = gr.Button("Detect Emotion")
214
- emotion_output = gr.Textbox(label="Detected Emotion:")
215
- suggestions_output = gr.Textbox(label="Suggestions:")
216
- detect_button.click(detect_emotion, inputs=[emotion_input, state], outputs=[emotion_output, suggestions_output, state])
217
-
218
- with gr.Tab("Find Local Wellness Professionals"):
219
- location_input = gr.Textbox(label="Enter your location:", value="Hawaii")
220
- search_button = gr.Button("Search")
221
- results_output = gr.Dataframe(label="Search Results")
222
- search_button.click(find_wellness_professionals, inputs=[location_input, state], outputs=[results_output, state])
223
-
224
- demo.launch()
 
83
  else:
84
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
85
 
86
+ # Add emoticons to the response
87
+ emoticon_dict = {
88
+ "joy": "😊",
89
+ "anger": "😑",
90
+ "fear": "😨",
91
+ "sadness": "πŸ˜”",
92
+ "surprise": "😲",
93
+ "neutral": "😐"
94
+ }
95
+
96
+ # Add the emotion-related emoticon to the response
97
+ for tg in data["intents"]:
98
+ if tg['tag'] == tag:
99
+ emotion = tg.get('emotion', 'neutral') # Default to neutral if no emotion is defined
100
+ response = f"{response} {emoticon_dict.get(emotion, '😐')}"
101
+ break
102
+
103
  history.append((message, response))
104
 
105
+ # Transition to the next feature (sentiment analysis)
106
  state['step'] = 2 # Move to sentiment analysis
107
  except Exception as e:
108
  response = f"An error occurred: {str(e)}"
 
121
  predicted_class = torch.argmax(outputs.logits, dim=1).item()
122
  sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
123
 
124
+ # Add emoticon to sentiment
125
+ sentiment_emojis = {
126
+ "Negative": "😞",
127
+ "Neutral": "😐",
128
+ "Positive": "😊"
129
+ }
130
+ sentiment_with_emoji = f"{sentiment} {sentiment_emojis.get(sentiment, '😐')}"
131
+
132
+ # Transition to emotion detection
133
  state['step'] = 3 # Move to emotion detection and suggestions
134
+ return sentiment_with_emoji, state
135
 
136
  # Load pre-trained model and tokenizer for emotion detection
137
  emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
138
  emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
139
 
140
+ # Function for emotion detection and suggestions
141
  def detect_emotion(text, state):
142
  pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
143
  result = pipe(text)
144
  emotion = result[0]['label']
145
+
146
+ # Provide suggestions based on detected emotion
147
  suggestions = provide_suggestions(emotion)
148
 
149
+ # Transition to wellness professional search
150
  state['step'] = 4 # Move to wellness professional search
151
  return emotion, suggestions, state
152
 
153
  # Suggestions based on detected emotion
154
  def provide_suggestions(emotion):
155
+ resources = {
156
+ 'joy': {
157
+ 'message': "You're feeling happy! Keep up the great mood! 😊",
158
+ 'articles': [
159
+ "[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)",
160
+ "[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
161
+ ],
162
+ 'videos': "[Watch Relaxation Video](https://youtu.be/m1vaUGtyo-A)"
163
+ },
164
+ 'anger': {
165
+ 'message': "You're feeling angry. It's okay to feel this way. Let's try to calm down. 😑",
166
+ 'articles': [
167
+ "[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)",
168
+ "[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)"
169
+ ],
170
+ 'videos': "[Watch Anger Management Video](https://youtu.be/MIc299Flibs)"
171
+ },
172
+ 'fear': {
173
+ 'message': "You're feeling fearful. Take a moment to breathe and relax. 😨",
174
+ 'articles': [
175
+ "[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)",
176
+ "[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
177
+ ],
178
+ 'videos': "[Watch Coping Video](https://youtu.be/yGKKz185M5o)"
179
+ },
180
+ 'sadness': {
181
+ 'message': "You're feeling sad. It's okay to take a break. πŸ˜”",
182
+ 'articles': [
183
+ "[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)",
184
+ "[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
185
+ ],
186
+ 'videos': "[Watch Sadness Relief Video](https://youtu.be/-e-4Kx5px_I)"
187
+ },
188
+ 'surprise': {
189
+ 'message': "You're feeling surprised. It's okay to feel neutral! 😲",
190
+ 'articles': [
191
+ "[Managing Stress](https://www.health.harvard.edu/health-a-to-z)",
192
+ "[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
193
+ ],
194
+ 'videos': "[Watch Stress Relief Video](https://youtu.be/m1vaUGtyo-A)"
195
+ }
196
+ }
197
+ return resources.get(emotion, {'message': "Stay calm. πŸ™‚", 'articles': [], 'videos': []})
198
 
199
  # Function to find wellness professionals
200
  def find_wellness_professionals(location, state):
 
210
  "User Ratings Total", "Website", "Types", "Latitude", "Longitude",
211
  "Opening Hours", "Reviews", "Email"
212
  ])
213
+ # Display results in Gradio interface
214
+ if not df.empty:
215
+ df_html = df.to_html(classes="table table-striped", index=False)
216
+ return f"Found wellness professionals in your area: \n{df_html}", state
217
+ else:
218
+ return "No wellness professionals found for your location. Try another search.", state
219
  else:
220
+ return "Sorry, there was an issue fetching data. Please try again later.", state
221
 
222
+ # Function to fetch places data using Google Places API
223
  def get_all_places(query, location, radius, api_key):
224
+ url = f"https://maps.googleapis.com/maps/api/place/textsearch/json?query={query}&location={location}&radius={radius}&key={api_key}"
225
+ response = requests.get(url)
226
+ if response.status_code == 200:
227
+ results = response.json().get("results", [])
228
+ places = []
229
+ for place in results:
230
+ name = place.get("name")
231
+ address = place.get("formatted_address")
232
+ phone = place.get("formatted_phone_number", "Not available")
233
+ rating = place.get("rating", "Not rated")
234
+ business_status = place.get("business_status", "N/A")
235
+ user_ratings_total = place.get("user_ratings_total", "N/A")
236
+ website = place.get("website", "Not available")
237
+ types = place.get("types", [])
238
+ lat, lng = place.get("geometry", {}).get("location", {}).values()
239
+ opening_hours = place.get("opening_hours", {}).get("weekday_text", [])
240
+ reviews = place.get("reviews", [])
241
+ email = "Not available" # Assume email is not included in the API response
242
+
243
+ # Adding the place data to the list
244
+ places.append([name, address, phone, rating, business_status, user_ratings_total,
245
+ website, types, lat, lng, opening_hours, reviews, email])
246
+ return places
247
+ else:
248
+ return []
 
 
 
 
 
249
 
250
+ # Gradio interface setup
251
+ def gradio_interface():
252
+ with gr.Blocks() as demo:
253
+ # Set title and description
254
+ gr.Markdown("<h1 style='text-align: center;'>Mental Health Support Chatbot πŸ€–</h1>")
255
+ gr.Markdown("<p style='text-align: center;'>Get emotional well-being suggestions and find wellness professionals nearby.</p>")
256
+
257
+ # State to manage step transitions
258
+ state = gr.State({"step": 1})
259
+
260
+ # Chat interface
261
+ with gr.Row():
262
+ chatbot = gr.Chatbot(label="Chatbot")
263
+ user_input = gr.Textbox(placeholder="Type your message here...", label="Your Message")
264
+ send_button = gr.Button("Send")
265
+
266
+ # Output for emotion, sentiment, suggestions
267
+ with gr.Row():
268
+ sentiment_output = gr.Textbox(label="Sentiment Analysis")
269
+ emotion_output = gr.Textbox(label="Emotion Detection")
270
+ suggestions_output = gr.Textbox(label="Suggestions")
271
+
272
+ # Input for location for wellness professionals
273
+ with gr.Row():
274
+ location_input = gr.Textbox(label="Your Location (City/Region)", placeholder="Enter your city...")
275
+ search_button = gr.Button("Search Wellness Professionals")
276
+
277
+ # Button actions
278
+ send_button.click(chat, inputs=[user_input, chatbot, state], outputs=[chatbot, chatbot, state])
279
+ user_input.submit(chat, inputs=[user_input, chatbot, state], outputs=[chatbot, chatbot, state])
280
+
281
+ send_button.click(analyze_sentiment, inputs=[user_input, state], outputs=[sentiment_output, state])
282
+ user_input.submit(analyze_sentiment, inputs=[user_input, state], outputs=[sentiment_output, state])
283
+
284
+ send_button.click(detect_emotion, inputs=[user_input, state], outputs=[emotion_output, suggestions_output, state])
285
+ user_input.submit(detect_emotion, inputs=[user_input, state], outputs=[emotion_output, suggestions_output, state])
286
+
287
+ search_button.click(find_wellness_professionals, inputs=[location_input, state], outputs=[suggestions_output, state])
288
 
289
+ demo.launch()
290
+
291
+ # Run the Gradio interface
292
+ if __name__ == "__main__":
293
+ gradio_interface()