DreamStream-1 commited on
Commit
0aa146d
Β·
verified Β·
1 Parent(s): b9c6c79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +241 -137
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import nltk
2
  import numpy as np
3
  import tflearn
@@ -8,6 +9,8 @@ import pickle
8
  import gradio as gr
9
  from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
 
 
11
  import requests
12
  import csv
13
  import time
@@ -18,7 +21,6 @@ from selenium import webdriver
18
  from selenium.webdriver.chrome.options import Options
19
  import chromedriver_autoinstaller
20
  import os
21
- import logging
22
 
23
  # Ensure necessary NLTK resources are downloaded
24
  nltk.download('punkt')
@@ -91,153 +93,255 @@ def chat(message, history):
91
  history.append((message, response))
92
  return history, history
93
 
94
- # Load the pre-trained model (cached for performance)
95
- def load_model():
96
- return pipeline('sentiment-analysis', model='cardiffnlp/twitter-roberta-base-sentiment')
97
-
98
- sentiment_model = load_model()
99
-
100
- # Define the function to analyze sentiment
101
- def analyze_sentiment(user_input):
102
- result = sentiment_model(user_input)[0]
103
- sentiment = result['label'].lower() # Convert to lowercase for easier comparison
104
-
105
- # Customize messages based on detected sentiment
106
- if sentiment == 'negative':
107
- return "Mood Detected: Negative πŸ˜”\n\nStay positive! 🌟 Remember, tough times don't last, but tough people do!"
108
- elif sentiment == 'neutral':
109
- return "Mood Detected: Neutral 😐\n\nIt's good to reflect on steady days. Keep your goals in mind, and stay motivated!"
110
- elif sentiment == 'positive':
111
- return "Mood Detected: Positive 😊\n\nYou're on the right track! Keep shining! 🌞"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  else:
113
- return "Mood Detected: Unknown πŸ€”\n\nKeep going, you're doing great!"
114
-
115
- # Load pre-trained model and tokenizer
116
- @st.cache_resource
117
- def load_model():
118
- tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
119
- model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
120
- return tokenizer, model
121
-
122
- tokenizer, model = load_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
- # Set page config as the very first Streamlit command
125
- st.set_page_config(page_title="Mental Health & Wellness Assistant", layout="wide")
126
 
127
  # Display header
128
- st.title("Mental Health & Wellness Assistant")
129
-
130
- # User input for text (emotion detection)
131
- user_input = st.text_area("How are you feeling today?", "Enter your thoughts here...")
132
-
133
- # Model prediction
134
- if user_input:
135
- pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
136
- result = pipe(user_input)
137
 
138
- # Extracting the emotion from the model's result
139
- emotion = result[0]['label']
140
 
141
- # Display emotion
142
- st.write(f"**Emotion Detected:** {emotion}")
143
-
144
- # Provide suggestions based on the detected emotion
145
- if emotion == 'joy':
146
- st.write("You're feeling happy! Keep up the great mood!")
147
- st.write("Useful Resources:")
148
- st.markdown("[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
149
- st.write("[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
150
- st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
151
-
152
- st.write("Relaxation Videos:")
153
- st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
154
-
155
- elif emotion == 'anger':
156
- st.write("You're feeling angry. It's okay to feel this way. Let's try to calm down.")
157
- st.write("Useful Resources:")
158
- st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
159
- st.write("[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)")
160
- st.write("[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
161
-
162
- st.write("Relaxation Videos:")
163
- st.markdown("[Watch on YouTube](https://youtu.be/MIc299Flibs)")
164
-
165
- elif emotion == 'fear':
166
- st.write("You're feeling fearful. Take a moment to breathe and relax.")
167
- st.write("Useful Resources:")
168
- st.markdown("[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
169
- st.write("[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
170
- st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
171
-
172
- st.write("Relaxation Videos:")
173
- st.markdown("[Watch on YouTube](https://youtu.be/yGKKz185M5o)")
174
-
175
- elif emotion == 'sadness':
176
- st.write("You're feeling sad. It's okay to take a break.")
177
- st.write("Useful Resources:")
178
- st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
179
- st.write("[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
180
-
181
- st.write("Relaxation Videos:")
182
- st.markdown("[Watch on YouTube](https://youtu.be/-e-4Kx5px_I)")
183
-
184
- elif emotion == 'surprise':
185
- st.write("You're feeling surprised. It's okay to feel neutral!")
186
- st.write("Useful Resources:")
187
- st.markdown("[Managing Stress](https://www.health.harvard.edu/health-a-to-z)")
188
- st.write("[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
189
-
190
- st.write("Relaxation Videos:")
191
- st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
192
-
193
- # Chatbot functionality
194
- def chatbot_interface():
195
- def chat(message, history):
196
- history = history or []
197
- message = message.lower()
198
-
199
- try:
200
- # Predict the tag
201
- results = model.predict([bag_of_words(message, words)])
202
- results_index = np.argmax(results)
203
- tag = labels[results_index]
204
-
205
- # Match tag with intent and choose a random response
206
- for tg in data["intents"]:
207
- if tg['tag'] == tag:
208
- responses = tg['responses']
209
- response = random.choice(responses)
210
- break
211
- else:
212
- response = "I'm sorry, I didn't understand that. Could you please rephrase?"
213
-
214
- except Exception as e:
215
- response = f"An error occurred: {str(e)}"
216
-
217
- history.append((message, response))
218
- return history, history
219
 
 
 
 
220
  chatbot = gr.Chatbot(label="Chat")
221
  demo = gr.Interface(
222
  chat,
223
  [gr.Textbox(lines=1, label="Message"), "state"],
224
  [chatbot, "state"],
225
  allow_flagging="never",
226
- title="Mental Health Chatbot",
227
- description="Your personal mental health assistant.",
228
  )
229
- return demo
230
-
231
- # Launch the interfaces
232
- if __name__ == "__main__":
233
- # Create a tabbed interface for different features
234
- tabs = [
235
- gr.TabItem("Sentiment Analysis", chatbot_ui()),
236
- gr.TabItem("Emotion Detection", chatbot_ui()),
237
- gr.TabItem("Google Places Search", chatbot_ui()),
238
- ]
239
-
240
- with gr.Blocks() as demo:
241
- gr.Tabs(tabs)
242
-
243
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
  import nltk
3
  import numpy as np
4
  import tflearn
 
9
  import gradio as gr
10
  from nltk.tokenize import word_tokenize
11
  from nltk.stem.lancaster import LancasterStemmer
12
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
13
+ from transformers import pipeline
14
  import requests
15
  import csv
16
  import time
 
21
  from selenium.webdriver.chrome.options import Options
22
  import chromedriver_autoinstaller
23
  import os
 
24
 
25
  # Ensure necessary NLTK resources are downloaded
26
  nltk.download('punkt')
 
93
  history.append((message, response))
94
  return history, history
95
 
96
+ # Load pre-trained model and tokenizer for sentiment analysis
97
+ tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
98
+ sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
99
+
100
+ # Load pre-trained model and tokenizer for emotion detection
101
+ emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
102
+ emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
103
+
104
+ # Function for sentiment analysis
105
+ def analyze_sentiment(text):
106
+ inputs = tokenizer(text, return_tensors="pt")
107
+ with torch.no_grad():
108
+ outputs = sentiment_model(**inputs)
109
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
110
+ sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
111
+ return sentiment
112
+
113
+ # Function for emotion detection
114
+ def detect_emotion(text):
115
+ pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
116
+ result = pipe(text)
117
+ emotion = result[0]['label']
118
+ return emotion
119
+
120
+ # Function to scrape website URL from Google Maps using Selenium
121
+ def scrape_website_from_google_maps(place_name):
122
+ chrome_options = Options()
123
+ chrome_options.add_argument("--headless")
124
+ chrome_options.add_argument("--no-sandbox")
125
+ chrome_options.add_argument("--disable-dev-shm-usage")
126
+ driver = webdriver.Chrome(options=chrome_options)
127
+ search_url = f"https://www.google.com/maps/search/{place_name.replace(' ', '+')}"
128
+ driver.get(search_url)
129
+ time.sleep(5)
130
+ try:
131
+ website_element = driver.find_element_by_xpath('//a[contains(@aria-label, "Visit") and contains(@aria-label, "website")]')
132
+ website_url = website_element.get_attribute('href')
133
+ except:
134
+ website_url = "Not available"
135
+ driver.quit()
136
+ return website_url
137
+
138
+ # Function to scrape website for contact information
139
+ def scrape_website_for_contact_info(website):
140
+ phone_number = "Not available"
141
+ email = "Not available"
142
+ try:
143
+ response = requests.get(website, timeout=5)
144
+ soup = BeautifulSoup(response.content, 'html.parser')
145
+ phone_match = re.search(r'$$?\+?[0-9]*$$?[0-9_\- $$$$]*', soup.get_text())
146
+ if phone_match:
147
+ phone_number = phone_match.group()
148
+ email_match = re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', soup.get_text())
149
+ if email_match:
150
+ email = email_match.group()
151
+ except Exception as e:
152
+ print(f"Error scraping website {website}: {e}")
153
+ return phone_number, email
154
+
155
+ # Function to fetch detailed information for a specific place using its place_id
156
+ def get_place_details(place_id, api_key):
157
+ details_url = "https://maps.googleapis.com/maps/api/place/details/json"
158
+ params = {
159
+ "place_id": place_id,
160
+ "key": api_key
161
+ }
162
+ response = requests.get(details_url, params=params)
163
+ if response.status_code == 200:
164
+ details_data = response.json().get("result", {})
165
+ return {
166
+ "opening_hours": details_data.get("opening_hours", {}).get("weekday_text", "Not available"),
167
+ "reviews": details_data.get("reviews", "Not available"),
168
+ "phone_number": details_data.get("formatted_phone_number", "Not available"),
169
+ "website": details_data.get("website", "Not available")
170
+ }
171
  else:
172
+ return {}
173
+
174
+ # Function to get all places data including pagination
175
+ def get_all_places(query, location, radius, api_key):
176
+ all_results = []
177
+ next_page_token = None
178
+ while True:
179
+ data = get_places_data(query, location, radius, api_key, next_page_token)
180
+ if data:
181
+ results = data.get('results', [])
182
+ for place in results:
183
+ place_id = place.get("place_id")
184
+ name = place.get("name")
185
+ address = place.get("formatted_address")
186
+ rating = place.get("rating", "Not available")
187
+ business_status = place.get("business_status", "Not available")
188
+ user_ratings_total = place.get("user_ratings_total", "Not available")
189
+ website = place.get("website", "Not available")
190
+ types = ", ".join(place.get("types", []))
191
+ location = place.get("geometry", {}).get("location", {})
192
+ latitude = location.get("lat", "Not available")
193
+ longitude = location.get("lng", "Not available")
194
+ details = get_place_details(place_id, api_key)
195
+ phone_number = details.get("phone_number", "Not available")
196
+ if phone_number == "Not available" and website != "Not available":
197
+ phone_number, email = scrape_website_for_contact_info(website)
198
+ else:
199
+ email = "Not available"
200
+ if website == "Not available":
201
+ website = scrape_website_from_google_maps(name)
202
+ all_results.append([name, address, phone_number, rating, business_status,
203
+ user_ratings_total, website, types, latitude, longitude,
204
+ details.get("opening_hours", "Not available"),
205
+ details.get("reviews", "Not available"), email
206
+ ])
207
+ next_page_token = data.get('next_page_token')
208
+ if not next_page_token:
209
+ break
210
+ time.sleep(2)
211
+ else:
212
+ break
213
+ return all_results
214
+
215
+ # Function to save results to CSV file
216
+ def save_to_csv(data, filename):
217
+ with open(filename, mode='w', newline='', encoding='utf-8') as file:
218
+ writer = csv.writer(file)
219
+ writer.writerow([
220
+ "Name", "Address", "Phone", "Rating", "Business Status",
221
+ "User Ratings Total", "Website", "Types", "Latitude", "Longitude",
222
+ "Opening Hours", "Reviews", "Email"
223
+ ])
224
+ writer.writerows(data)
225
+ print(f"Data saved to {filename}")
226
+
227
+ # Function to get places data from Google Places API
228
+ def get_places_data(query, location, radius, api_key, next_page_token=None):
229
+ url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
230
+ params = {
231
+ "query": query,
232
+ "location": location,
233
+ "radius": radius,
234
+ "key": api_key
235
+ }
236
+ if next_page_token:
237
+ params["pagetoken"] = next_page_token
238
+ response = requests.get(url, params=params)
239
+ if response.status_code == 200:
240
+ data = response.json()
241
+ return data
242
+ else:
243
+ print(f"Error: {response.status_code} - {response.text}")
244
+ return None
245
 
246
+ # Set page config
247
+ st.set_page_config(page_title="Wellbeing Support System", layout="wide")
248
 
249
  # Display header
250
+ st.title("Wellbeing Support System")
 
 
 
 
 
 
 
 
251
 
252
+ # User input for location
253
+ location = st.text_input("Enter your location:", "Hawaii")
254
 
255
+ # Tabs for different functionalities
256
+ tabs = ["Chatbot", "Sentiment Analysis", "Emotion Detection & Suggestions", "Find Local Wellness Professionals"]
257
+ selected_tab = st.selectbox("Select a functionality:", tabs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
 
259
+ if selected_tab == "Chatbot":
260
+ # Chatbot functionality
261
+ st.subheader("Chat with the Mental Health Support Bot")
262
  chatbot = gr.Chatbot(label="Chat")
263
  demo = gr.Interface(
264
  chat,
265
  [gr.Textbox(lines=1, label="Message"), "state"],
266
  [chatbot, "state"],
267
  allow_flagging="never",
268
+ title="Wellbeing for All, ** I am your Best Friend **",
 
269
  )
270
+ demo.launch()
271
+
272
+ elif selected_tab == "Sentiment Analysis":
273
+ # Sentiment Analysis
274
+ st.subheader("Sentiment Analysis")
275
+ user_input = st.text_area("Enter text to analyze sentiment:")
276
+ if st.button("Analyze Sentiment"):
277
+ if user_input:
278
+ sentiment = analyze_sentiment(user_input)
279
+ st.write(f"**Sentiment:** {sentiment}")
280
+ else:
281
+ st.warning("Please enter some text to analyze.")
282
+
283
+ elif selected_tab == "Emotion Detection & Suggestions":
284
+ # Emotion Detection and Suggestions
285
+ st.subheader("Emotion Detection and Well-Being Suggestions")
286
+ user_input = st.text_area("How are you feeling today?", "Enter your thoughts here...")
287
+ if st.button("Detect Emotion"):
288
+ if user_input:
289
+ emotion = detect_emotion(user_input)
290
+ st.write(f"**Emotion Detected:** {emotion}")
291
+ # Provide suggestions based on the detected emotion
292
+ if emotion == 'joy':
293
+ st.write("You're feeling happy! Keep up the great mood!")
294
+ st.write("Useful Resources:")
295
+ st.markdown("[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
296
+ st.write("[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
297
+ st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
298
+ st.write("Relaxation Videos:")
299
+ st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
300
+ elif emotion == 'anger':
301
+ st.write("You're feeling angry. It's okay to feel this way. Let's try to calm down.")
302
+ st.write("Useful Resources:")
303
+ st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
304
+ st.write("[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)")
305
+ st.write("[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
306
+ st.write("Relaxation Videos:")
307
+ st.markdown("[Watch on YouTube](https://youtu.be/MIc299Flibs)")
308
+ # Add more conditions for other emotions...
309
+ else:
310
+ st.warning("Please enter some text to analyze.")
311
+
312
+ elif selected_tab == "Find Local Wellness Professionals":
313
+ # Find Local Wellness Professionals
314
+ st.subheader("Find Local Wellness Professionals")
315
+ if st.button("Search"):
316
+ # Define search parameters
317
+ 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 in " + location
318
+ api_key = "AIzaSyCcfJzMFfuv_1LN7JPTJJYw_aS0A_SLeW0" # Replace with your own Google API key
319
+ location_coords = "21.3,-157.8" # Default to Oahu, Hawaii
320
+ radius = 50000 # 50 km radius
321
+
322
+ # Install Chrome and Chromedriver
323
+ def install_chrome_and_driver():
324
+ os.system("apt-get update")
325
+ os.system("apt-get install -y wget curl")
326
+ os.system("wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb")
327
+ os.system("dpkg -i google-chrome-stable_current_amd64.deb")
328
+ os.system("apt-get install -y -f")
329
+ os.system("google-chrome-stable --version")
330
+ chromedriver_autoinstaller.install()
331
+
332
+ install_chrome_and_driver()
333
+
334
+ # Get all places data
335
+ google_places_data = get_all_places(query, location_coords, radius, api_key)
336
+ if google_places_data:
337
+ # Display the results
338
+ df = pd.DataFrame(google_places_data, columns=[
339
+ "Name", "Address", "Phone", "Rating", "Business Status",
340
+ "User Ratings Total", "Website", "Types", "Latitude", "Longitude",
341
+ "Opening Hours", "Reviews", "Email"
342
+ ])
343
+ st.write(df)
344
+ # Save to CSV
345
+ save_to_csv(google_places_data, "wellness_professionals.csv")
346
+ else:
347
+ st.write("No data found.")