DreamStream-1 commited on
Commit
fce43ab
·
verified ·
1 Parent(s): 11f26d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -42
app.py CHANGED
@@ -10,8 +10,6 @@ from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
11
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  import requests
13
- from bs4 import BeautifulSoup
14
- import pandas as pd
15
  import geocoder # Use geocoder to get latitude/longitude from city
16
 
17
  # Ensure necessary NLTK resources are downloaded
@@ -108,13 +106,11 @@ def chat(message, history, state):
108
  tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
109
  sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
110
 
111
- # Function for sentiment analysis
112
  # Function for sentiment analysis
113
  def analyze_sentiment(text, state):
114
- # Initialize state if it's None
115
  if state is None:
116
  state = {'step': 1}
117
-
118
  inputs = tokenizer(text, return_tensors="pt")
119
  with torch.no_grad():
120
  outputs = sentiment_model(**inputs)
@@ -194,56 +190,60 @@ def provide_suggestions(emotion):
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):
201
- # Geocode the location to get latitude and longitude
202
- g = geocoder.osm(location) # Using OpenStreetMap's geocoding service
203
  if g.ok:
204
- location_coords = f"{g.lat},{g.lng}"
205
- else:
206
- return "Sorry, could not retrieve coordinates for the location. Please try again.", state
207
-
208
- query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist in " + location
209
- api_key = "GOOGLE_API_KEY" # Replace with your own API key
210
- radius = 50000 # 50 km radius
211
-
212
- google_places_data = get_all_places(query, location_coords, radius, api_key)
213
- if google_places_data:
214
- response = "Wellness professionals near you:\n"
215
- for place in google_places_data:
216
- response += f"- {place['name']} at {place['formatted_address']}\n"
 
 
 
 
 
217
  else:
218
- response = "Sorry, no wellness professionals found in your area. Please try another location."
219
-
220
- return response, state
221
 
222
- # Call Google Places API
223
- def get_all_places(query, location, radius, api_key):
224
- search_url = f"https://maps.googleapis.com/maps/api/place/textsearch/json?query={query}&location={location}&radius={radius}&key={api_key}"
225
- response = requests.get(search_url).json()
226
-
227
- if 'results' in response:
228
- return response['results']
229
- return []
230
 
231
- # Gradio UI components
232
- # Function to create the UI with state initialization
233
  def create_ui():
234
  with gr.Blocks() as demo:
235
- state = gr.State({'step': 1}) # Initialize state with a default value
236
  chatbot = gr.Chatbot(elem_id="chatbot", label="Mental Health Chatbot")
237
  message_input = gr.Textbox(placeholder="Ask me something...", label="Enter your message")
238
  sentiment_output = gr.Textbox(placeholder="Sentiment result", label="Sentiment")
239
  emotion_output = gr.Textbox(placeholder="Detected emotion", label="Emotion")
240
- wellness_output = gr.Textbox(placeholder="Wellness professional list", label="Wellness Professionals")
241
-
 
242
  message_input.submit(chat, [message_input, chatbot, state], [chatbot, chatbot, state])
243
  message_input.submit(analyze_sentiment, [message_input, state], [sentiment_output, state])
244
  sentiment_output.submit(detect_emotion, [sentiment_output, state], [emotion_output, wellness_output, state])
245
- return demo
 
 
246
 
247
- # Launch the Gradio interface
248
  demo = create_ui()
249
- demo.launch(debug=True)
 
10
  from nltk.stem.lancaster import LancasterStemmer
11
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  import requests
 
 
13
  import geocoder # Use geocoder to get latitude/longitude from city
14
 
15
  # Ensure necessary NLTK resources are downloaded
 
106
  tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
107
  sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
108
 
 
109
  # Function for sentiment analysis
110
  def analyze_sentiment(text, state):
 
111
  if state is None:
112
  state = {'step': 1}
113
+
114
  inputs = tokenizer(text, return_tensors="pt")
115
  with torch.no_grad():
116
  outputs = sentiment_model(**inputs)
 
190
  'videos': "[Watch Stress Relief Video](https://youtu.be/m1vaUGtyo-A)"
191
  }
192
  }
193
+
194
+ # Ensure we return a message even if no articles/videos are found
195
+ return resources.get(emotion, {'message': "Stay calm. 🙂", 'articles': ["[General Wellbeing Tips](https://www.helpguide.org)"], 'videos': []})
196
 
197
+ # Function to fetch wellness professionals based on location
198
+ def get_wellness_professionals(location):
199
+ # Use Geocoder to get latitude/longitude from city
200
+ g = geocoder.osm(location)
201
  if g.ok:
202
+ latitude, longitude = g.latlng
203
+ google_api_url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{longitude}&radius=5000&type=health&key=YOUR_GOOGLE_API_KEY"
204
+
205
+ response = requests.get(google_api_url)
206
+ data = response.json()
207
+
208
+ professionals = []
209
+ if 'results' in data:
210
+ for place in data['results']:
211
+ name = place['name']
212
+ address = place.get('vicinity', 'No address available')
213
+ url = place.get('website', '#')
214
+ professionals.append(f"**{name}** - {address} - [Visit Website]({url})")
215
+
216
+ if not professionals:
217
+ professionals.append("No wellness professionals found nearby.")
218
+
219
+ return "\n".join(professionals)
220
  else:
221
+ return "Couldn't fetch your location. Please make sure you entered a valid location."
 
 
222
 
223
+ # Function to ask for location and provide wellness professionals
224
+ def search_wellness_professionals(location, state):
225
+ professionals = get_wellness_professionals(location)
226
+ state['step'] = 5 # Move to the next step
227
+ return professionals, state
 
 
 
228
 
229
+ # Create the UI with location input for wellness professionals
 
230
  def create_ui():
231
  with gr.Blocks() as demo:
232
+ state = gr.State({'step': 1})
233
  chatbot = gr.Chatbot(elem_id="chatbot", label="Mental Health Chatbot")
234
  message_input = gr.Textbox(placeholder="Ask me something...", label="Enter your message")
235
  sentiment_output = gr.Textbox(placeholder="Sentiment result", label="Sentiment")
236
  emotion_output = gr.Textbox(placeholder="Detected emotion", label="Emotion")
237
+ wellness_output = gr.Textbox(placeholder="Wellness professionals nearby", label="Wellness Professionals")
238
+ location_input = gr.Textbox(placeholder="Enter your city for wellness professionals", label="Location")
239
+
240
  message_input.submit(chat, [message_input, chatbot, state], [chatbot, chatbot, state])
241
  message_input.submit(analyze_sentiment, [message_input, state], [sentiment_output, state])
242
  sentiment_output.submit(detect_emotion, [sentiment_output, state], [emotion_output, wellness_output, state])
243
+ location_input.submit(search_wellness_professionals, [location_input, state], [wellness_output, state])
244
+
245
+ return demo
246
 
247
+ # Launch Gradio interface
248
  demo = create_ui()
249
+ demo.launch(debug=True)