DreamStream-1 commited on
Commit
31cd9bf
·
verified ·
1 Parent(s): 3efaeb9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -71
app.py CHANGED
@@ -1,16 +1,22 @@
1
  import gradio as gr
 
 
 
 
 
 
2
  import nltk
3
  import numpy as np
4
  import tflearn
5
- import random
6
- import json
7
- import pickle
8
- import torch
 
 
9
  from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
11
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
- import requests
13
- import pandas as pd
14
 
15
  # Ensure necessary NLTK resources are downloaded
16
  nltk.download('punkt')
@@ -61,7 +67,7 @@ def bag_of_words(s, words):
61
  def chat(message, history):
62
  history = history or []
63
  message = message.lower()
64
-
65
  try:
66
  # Predict the tag
67
  results = model.predict([bag_of_words(message, words)])
@@ -78,7 +84,7 @@ def chat(message, history):
78
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
79
  except Exception as e:
80
  response = f"An error occurred: {str(e)}"
81
-
82
  history.append((message, response))
83
  return history, history
84
 
@@ -146,13 +152,26 @@ def provide_suggestions(emotion):
146
  "Article URL": "https://www.health.harvard.edu/health-a-to-z",
147
  "Video URL": "https://youtu.be/m1vaUGtyo-A"
148
  }, ignore_index=True)
149
-
150
  return suggestions
151
 
152
  # Google Places API to get nearby wellness professionals
153
- api_key = "GOOGLE_API_KEY" # Replace with your actual API key
154
-
155
- def get_places_data(query, location, radius, api_key, next_page_token=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
157
  params = {
158
  "query": query,
@@ -160,62 +179,48 @@ def get_places_data(query, location, radius, api_key, next_page_token=None):
160
  "radius": radius,
161
  "key": api_key
162
  }
163
- if next_page_token:
164
- params["pagetoken"] = next_page_token
165
  response = requests.get(url, params=params)
166
- return response.json() if response.status_code == 200 else None
167
-
168
- def get_all_places(query, location, radius, api_key):
169
- all_results = []
170
- next_page_token = None
171
- while True:
172
- data = get_places_data(query, location, radius, api_key, next_page_token)
173
- if data:
174
- results = data.get('results', [])
175
- for place in results:
176
- place_id = place.get("place_id")
177
- name = place.get("name")
178
- address = place.get("formatted_address")
179
- website = place.get("website", "Not available")
180
- all_results.append([name, address, website])
181
- next_page_token = data.get('next_page_token')
182
- if not next_page_token:
183
- break
184
- else:
185
- break
186
- return all_results
187
-
188
- def search_wellness_professionals(location):
189
- query = "therapist OR counselor OR mental health professional"
190
- radius = 50000
191
- google_places_data = get_all_places(query, location, radius, api_key)
192
- if google_places_data:
193
- df = pd.DataFrame(google_places_data, columns=["Name", "Address", "Website"])
194
- return df
195
- else:
196
- return pd.DataFrame([["No data found.", "", ""]], columns=["Name", "Address", "Website"])
197
-
198
- # Gradio Interface
199
- def gradio_interface(message, location, state):
200
- history = state or [] # If state is None, initialize it as an empty list
201
-
202
- # Stage 1: Mental Health Chatbot
203
- history, _ = chat(message, history)
204
-
205
- # Stage 2: Sentiment Analysis
206
- sentiment = analyze_sentiment(message)
207
-
208
- # Stage 3: Emotion Detection and Suggestions
209
- emotion = detect_emotion(message)
210
- suggestions = provide_suggestions(emotion)
211
-
212
- # Stage 4: Search for Wellness Professionals
213
- wellness_results = search_wellness_professionals(location)
214
-
215
- # Return the results in a tabular form within the Gradio interface
216
- return history, sentiment, emotion, suggestions, wellness_results, history # Last 'history' is for state
217
-
218
- # Gradio interface setup
219
  iface = gr.Interface(
220
  fn=gradio_interface,
221
  inputs=[
@@ -224,11 +229,11 @@ iface = gr.Interface(
224
  gr.State() # One state input
225
  ],
226
  outputs=[
227
- gr.Chatbot(label="Chat History", type="messages"), # Set type="messages" as per the warning
228
  gr.Textbox(label="Sentiment Analysis"),
229
  gr.Textbox(label="Detected Emotion"),
230
  gr.Dataframe(label="Suggestions & Resources"),
231
- gr.Dataframe(label="Nearby Wellness Professionals"), # Display results as a table
232
  gr.State() # One state output
233
  ],
234
  allow_flagging="never",
@@ -236,5 +241,4 @@ iface = gr.Interface(
236
  description="This app provides a mental health chatbot, sentiment analysis, emotion detection, and wellness professional search functionality.",
237
  )
238
 
239
- # Launch Gradio interface
240
- iface.launch(debug=True, share=True) # Set share=True to create a public link
 
1
  import gradio as gr
2
+ import requests
3
+ import time
4
+ import re
5
+ import csv
6
+ import json
7
+ import random
8
  import nltk
9
  import numpy as np
10
  import tflearn
11
+ import os
12
+ from selenium import webdriver
13
+ from selenium.webdriver.chrome.options import Options
14
+ from bs4 import BeautifulSoup
15
+ import chromedriver_autoinstaller
16
+ import pandas as pd
17
  from nltk.tokenize import word_tokenize
18
  from nltk.stem.lancaster import LancasterStemmer
19
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
 
 
20
 
21
  # Ensure necessary NLTK resources are downloaded
22
  nltk.download('punkt')
 
67
  def chat(message, history):
68
  history = history or []
69
  message = message.lower()
70
+
71
  try:
72
  # Predict the tag
73
  results = model.predict([bag_of_words(message, words)])
 
84
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
85
  except Exception as e:
86
  response = f"An error occurred: {str(e)}"
87
+
88
  history.append((message, response))
89
  return history, history
90
 
 
152
  "Article URL": "https://www.health.harvard.edu/health-a-to-z",
153
  "Video URL": "https://youtu.be/m1vaUGtyo-A"
154
  }, ignore_index=True)
155
+
156
  return suggestions
157
 
158
  # Google Places API to get nearby wellness professionals
159
+ api_key = "YOUR_GOOGLE_API_KEY" # Replace with your actual API key
160
+
161
+ def install_chrome_and_driver():
162
+ os.system("apt-get update")
163
+ os.system("apt-get install -y wget curl")
164
+ os.system("wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb")
165
+ os.system("dpkg -i google-chrome-stable_current_amd64.deb")
166
+ os.system("apt-get install -y -f")
167
+ os.system("google-chrome-stable --version")
168
+ chromedriver_autoinstaller.install()
169
+
170
+ # Install Chrome and Chromedriver
171
+ install_chrome_and_driver()
172
+
173
+ # Fetch places data using Google Places API
174
+ def get_places_data(query, location, radius, api_key):
175
  url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
176
  params = {
177
  "query": query,
 
179
  "radius": radius,
180
  "key": api_key
181
  }
 
 
182
  response = requests.get(url, params=params)
183
+ if response.status_code == 200:
184
+ return response.json()
185
+ return None
186
+
187
+ # Scrape website URL from Google Maps results (using Selenium)
188
+ def scrape_website_from_google_maps(place_name):
189
+ chrome_options = Options()
190
+ chrome_options.add_argument("--headless")
191
+ chrome_options.add_argument("--no-sandbox")
192
+ chrome_options.add_argument("--disable-dev-shm-usage")
193
+ driver = webdriver.Chrome(options=chrome_options)
194
+ search_url = f"https://www.google.com/maps/search/{place_name.replace(' ', '+')}"
195
+ driver.get(search_url)
196
+ time.sleep(5)
197
+ try:
198
+ website_element = driver.find_element_by_xpath('//a[contains(@aria-label, "Visit") and contains(@aria-label, "website")]')
199
+ website_url = website_element.get_attribute('href')
200
+ except:
201
+ website_url = "Not available"
202
+ driver.quit()
203
+ return website_url
204
+
205
+ # Get all wellness professionals based on the location
206
+ def get_wellness_professionals(location):
207
+ 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"
208
+ radius = 50000 # 50 km radius
209
+ data = get_places_data(query, location, radius, api_key)
210
+ if data:
211
+ results = data.get('results', [])
212
+ wellness_data = []
213
+ for place in results:
214
+ name = place.get('name')
215
+ address = place.get('formatted_address')
216
+ website = place.get('website', 'Not available')
217
+ if website == 'Not available':
218
+ website = scrape_website_from_google_maps(name)
219
+ wellness_data.append([name, address, website])
220
+ return pd.DataFrame(wellness_data, columns=["Name", "Address", "Website"])
221
+ return pd.DataFrame()
222
+
223
+ # Gradio Interface Setup
 
 
 
 
 
 
 
 
 
 
 
 
224
  iface = gr.Interface(
225
  fn=gradio_interface,
226
  inputs=[
 
229
  gr.State() # One state input
230
  ],
231
  outputs=[
232
+ gr.Chatbot(label="Chat History", type="messages"), # Set type="messages"
233
  gr.Textbox(label="Sentiment Analysis"),
234
  gr.Textbox(label="Detected Emotion"),
235
  gr.Dataframe(label="Suggestions & Resources"),
236
+ gr.Dataframe(label="Nearby Wellness Professionals"),
237
  gr.State() # One state output
238
  ],
239
  allow_flagging="never",
 
241
  description="This app provides a mental health chatbot, sentiment analysis, emotion detection, and wellness professional search functionality.",
242
  )
243
 
244
+ iface.launch(debug=True, share=True) # Launch with share=True to create a public link