Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,13 +11,11 @@ import chromedriver_autoinstaller
|
|
11 |
import os
|
12 |
import nltk
|
13 |
import numpy as np
|
|
|
|
|
|
|
14 |
import tflearn
|
15 |
import tensorflow as tf
|
16 |
-
import random
|
17 |
-
import json
|
18 |
-
import pickle
|
19 |
-
from nltk.tokenize import word_tokenize
|
20 |
-
from nltk.stem.lancaster import LancasterStemmer
|
21 |
|
22 |
# Ensure necessary NLTK resources are downloaded
|
23 |
nltk.download('punkt')
|
@@ -39,56 +37,38 @@ try:
|
|
39 |
except FileNotFoundError:
|
40 |
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
|
41 |
|
42 |
-
#
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
#
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
results = model.predict([bag_of_words(message, words)])
|
75 |
-
results_index = np.argmax(results)
|
76 |
-
tag = labels[results_index]
|
77 |
-
|
78 |
-
# Match tag with intent and choose a random response
|
79 |
-
for tg in data["intents"]:
|
80 |
-
if tg['tag'] == tag:
|
81 |
-
responses = tg['responses']
|
82 |
-
response = random.choice(responses)
|
83 |
-
break
|
84 |
-
else:
|
85 |
-
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
86 |
-
|
87 |
-
except Exception as e:
|
88 |
-
response = f"An error occurred: {str(e)}"
|
89 |
-
|
90 |
-
history.append((message, response))
|
91 |
-
return history, history
|
92 |
|
93 |
# Load tokenizer and model for sentiment analysis
|
94 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
@@ -98,16 +78,15 @@ model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp
|
|
98 |
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
99 |
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
|
100 |
|
|
|
|
|
|
|
101 |
# Your actual Google API Key (replace with your key)
|
102 |
api_key = "AIzaSyCcfJzMFfuv_1LN7JPTJJYw_aS0A_SLeW0" # Replace with your own Google API key
|
103 |
|
104 |
# Search query for wellness professionals in Hawaii
|
105 |
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 Hawaii"
|
106 |
|
107 |
-
# Approximate latitude and longitude for Hawaii (e.g., Oahu)
|
108 |
-
location = "21.3,-157.8" # Center of Hawaii (Oahu)
|
109 |
-
radius = 50000 # 50 km radius
|
110 |
-
|
111 |
# Function to send a request to Google Places API and fetch places data
|
112 |
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
113 |
params = {
|
@@ -147,49 +126,6 @@ def get_place_details(place_id, api_key):
|
|
147 |
else:
|
148 |
return {}
|
149 |
|
150 |
-
# Scrape website URL from Google Maps results (using Selenium WebDriver)
|
151 |
-
def scrape_div_from_google_maps(place_name):
|
152 |
-
chrome_options = Options()
|
153 |
-
chrome_options.add_argument("--headless")
|
154 |
-
chrome_options.add_argument("--no-sandbox")
|
155 |
-
chrome_options.add_argument("--disable-dev-shm-usage")
|
156 |
-
|
157 |
-
driver = webdriver.Chrome(options=chrome_options)
|
158 |
-
search_url = f"https://www.google.com/maps/search/{place_name.replace(' ', '+')}"
|
159 |
-
driver.get(search_url)
|
160 |
-
time.sleep(5)
|
161 |
-
|
162 |
-
try:
|
163 |
-
website_element = driver.find_element_by_xpath('//a[contains(@aria-label, "Visit") and contains(@aria-label, "website")]')
|
164 |
-
website_url = website_element.get_attribute('href')
|
165 |
-
except:
|
166 |
-
website_url = "Not available"
|
167 |
-
|
168 |
-
driver.quit()
|
169 |
-
return website_url
|
170 |
-
|
171 |
-
# Scraping the website to extract phone number or email
|
172 |
-
def scrape_div_for_contact_info(website):
|
173 |
-
phone_number = "Not available"
|
174 |
-
email = "Not available"
|
175 |
-
|
176 |
-
try:
|
177 |
-
response = requests.get(website, timeout=5)
|
178 |
-
soup = BeautifulSoup(response.content, 'html.parser')
|
179 |
-
|
180 |
-
phone_match = re.search(r'\(?\+?[0-9]*\)?[0-9_\- \(\)]*', soup.get_text())
|
181 |
-
if phone_match:
|
182 |
-
phone_number = phone_match.group()
|
183 |
-
|
184 |
-
email_match = re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', soup.get_text())
|
185 |
-
if email_match:
|
186 |
-
email = email_match.group()
|
187 |
-
|
188 |
-
except Exception as e:
|
189 |
-
print(f"Error scraping website {website}: {e}")
|
190 |
-
|
191 |
-
return phone_number, email
|
192 |
-
|
193 |
# Function to fetch all places data including pagination
|
194 |
def get_all_places(query, location, radius, api_key):
|
195 |
all_results = []
|
@@ -207,7 +143,7 @@ def get_all_places(query, location, radius, api_key):
|
|
207 |
address = place.get("formatted_address")
|
208 |
rating = place.get("rating", "Not available")
|
209 |
business_status = place.get("business_status", "Not available")
|
210 |
-
|
211 |
website = place.get("website", "Not available")
|
212 |
types = ", ".join(place.get("types", []))
|
213 |
location = place.get("geometry", {}).get("location", {})
|
@@ -225,7 +161,7 @@ def get_all_places(query, location, radius, api_key):
|
|
225 |
website = scrape_div_from_google_maps(name)
|
226 |
|
227 |
all_results.append([name, address, phone_number, rating, business_status,
|
228 |
-
|
229 |
details.get("opening_hours", "Not available"),
|
230 |
details.get("reviews", "Not available"), email])
|
231 |
|
@@ -251,6 +187,24 @@ def save_to_csv(data, filename):
|
|
251 |
writer.writerows(data)
|
252 |
print(f"Data saved to {filename}")
|
253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
# Main function to execute script
|
255 |
def main():
|
256 |
google_places_data = get_all_places(query, location, radius, api_key)
|
@@ -266,31 +220,32 @@ with gr.Blocks() as demo:
|
|
266 |
|
267 |
# User input for text (emotion detection)
|
268 |
user_input_emotion = gr.Textbox(lines=1, label="How are you feeling today?")
|
|
|
269 |
|
270 |
# Model prediction for emotion detection
|
271 |
def predict_emotion(text):
|
272 |
-
|
273 |
-
|
274 |
-
|
|
|
|
|
275 |
return emotion
|
276 |
|
277 |
-
|
278 |
-
|
279 |
-
# Provide suggestions based on the detected emotion
|
280 |
def show_suggestions(emotion):
|
281 |
if emotion == 'joy':
|
282 |
return "You're feeling happy! Keep up the great mood!\nUseful Resources:\n[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)\n[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)"
|
283 |
elif emotion == 'anger':
|
284 |
-
return "You're feeling angry. It's okay to feel this way. Let's try to calm down.\nUseful Resources:\n[Emotional
|
285 |
elif emotion == 'fear':
|
286 |
-
return "You're feeling fearful. Take a moment to breathe and relax.\nUseful Resources:\n[Mindfulness
|
287 |
elif emotion == 'sadness':
|
288 |
-
return "You're feeling sad. It's okay to take a break.\nUseful Resources:\n[Emotional
|
289 |
elif emotion == 'surprise':
|
290 |
-
return "You're feeling surprised. It's okay to feel neutral!\nUseful Resources:\n[Managing
|
291 |
|
292 |
emotion_output = gr.Textbox(label="Emotion Detected")
|
293 |
-
|
294 |
|
295 |
# Button for summary
|
296 |
def show_summary(emotion):
|
@@ -303,7 +258,7 @@ with gr.Blocks() as demo:
|
|
303 |
# Chatbot functionality
|
304 |
chatbot = gr.Chatbot(label="Chat")
|
305 |
message_input = gr.Textbox(lines=1, label="Message")
|
306 |
-
|
307 |
|
308 |
def chat(message, history):
|
309 |
history = history or []
|
@@ -330,11 +285,35 @@ with gr.Blocks() as demo:
|
|
330 |
history.append((message, response))
|
331 |
return history, history
|
332 |
|
333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
334 |
|
335 |
# User input for text (sentiment analysis)
|
336 |
user_input_sentiment = gr.Textbox(lines=1, label="Enter text to analyze sentiment:")
|
337 |
-
|
|
|
338 |
# Prediction button for sentiment analysis
|
339 |
def predict_sentiment(text):
|
340 |
inputs = tokenizer_sentiment(text, return_tensors="pt")
|
@@ -345,7 +324,7 @@ with gr.Blocks() as demo:
|
|
345 |
return sentiment
|
346 |
|
347 |
sentiment_output = gr.Textbox(label="Predicted Sentiment")
|
348 |
-
|
349 |
|
350 |
# Button to fetch wellness professionals data
|
351 |
fetch_button = gr.Button("Fetch Wellness professionals data")
|
|
|
11 |
import os
|
12 |
import nltk
|
13 |
import numpy as np
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
import torch.optim as optim
|
17 |
import tflearn
|
18 |
import tensorflow as tf
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
# Ensure necessary NLTK resources are downloaded
|
21 |
nltk.download('punkt')
|
|
|
37 |
except FileNotFoundError:
|
38 |
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
|
39 |
|
40 |
+
# Define a PyTorch model with the same architecture as your tflearn model
|
41 |
+
class PyTorchModel(nn.Module):
|
42 |
+
def __init__(self, vocab_size, embedding_dim, hidden_dim, num_classes):
|
43 |
+
super(PyTorchModel, self).__init__()
|
44 |
+
self.embedding = nn.Embedding(vocab_size, embedding_dim)
|
45 |
+
self.fc1 = nn.Linear(embedding_dim, hidden_dim)
|
46 |
+
self.relu = nn.ReLU()
|
47 |
+
self.fc2 = nn.Linear(hidden_dim, num_classes)
|
48 |
+
|
49 |
+
def forward(self, x):
|
50 |
+
out = self.embedding(x)
|
51 |
+
out = torch.mean(out, dim=1)
|
52 |
+
out = self.fc1(out)
|
53 |
+
out = self.relu(out)
|
54 |
+
out = self.fc2(out)
|
55 |
+
return out
|
56 |
+
|
57 |
+
# Convert the tflearn model to a PyTorch model
|
58 |
+
vocab_size = len(words)
|
59 |
+
embedding_dim = 128
|
60 |
+
hidden_dim = 64
|
61 |
+
num_classes = len(labels)
|
62 |
+
|
63 |
+
pytorch_model = PyTorchModel(vocab_size, embedding_dim, hidden_dim, num_classes)
|
64 |
+
|
65 |
+
# Load weights from the tflearn model
|
66 |
+
for layer_name, weights in zip(['fc1/kernel:0', 'fc1/bias:0', 'fc2/kernel:0', 'fc2/bias:0'], model.get_weights()):
|
67 |
+
pytorch_layer_name = layer_name.replace(':0', '')
|
68 |
+
pytorch_model.state_dict()[pytorch_layer_name].copy_(torch.tensor(weights))
|
69 |
+
|
70 |
+
# Move the model to the CPU
|
71 |
+
pytorch_model.cpu()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
# Load tokenizer and model for sentiment analysis
|
74 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
|
|
78 |
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
79 |
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
|
80 |
|
81 |
+
# Google Geocoding API endpoint
|
82 |
+
geocoding_url = "https://maps.googleapis.com/maps/api/geocode/json"
|
83 |
+
|
84 |
# Your actual Google API Key (replace with your key)
|
85 |
api_key = "AIzaSyCcfJzMFfuv_1LN7JPTJJYw_aS0A_SLeW0" # Replace with your own Google API key
|
86 |
|
87 |
# Search query for wellness professionals in Hawaii
|
88 |
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 Hawaii"
|
89 |
|
|
|
|
|
|
|
|
|
90 |
# Function to send a request to Google Places API and fetch places data
|
91 |
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
92 |
params = {
|
|
|
126 |
else:
|
127 |
return {}
|
128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
# Function to fetch all places data including pagination
|
130 |
def get_all_places(query, location, radius, api_key):
|
131 |
all_results = []
|
|
|
143 |
address = place.get("formatted_address")
|
144 |
rating = place.get("rating", "Not available")
|
145 |
business_status = place.get("business_status", "Not available")
|
146 |
+
user_reviews_total = place.get("user_reviews_total", "Not available")
|
147 |
website = place.get("website", "Not available")
|
148 |
types = ", ".join(place.get("types", []))
|
149 |
location = place.get("geometry", {}).get("location", {})
|
|
|
161 |
website = scrape_div_from_google_maps(name)
|
162 |
|
163 |
all_results.append([name, address, phone_number, rating, business_status,
|
164 |
+
user_reviews_total, website, types, latitude, longitude,
|
165 |
details.get("opening_hours", "Not available"),
|
166 |
details.get("reviews", "Not available"), email])
|
167 |
|
|
|
187 |
writer.writerows(data)
|
188 |
print(f"Data saved to {filename}")
|
189 |
|
190 |
+
# Geocoding function to convert location text to coordinates
|
191 |
+
def geocode_location(address):
|
192 |
+
params = {
|
193 |
+
"address": address,
|
194 |
+
"key": api_key
|
195 |
+
}
|
196 |
+
response = requests.get(geocoding_url, params=params)
|
197 |
+
|
198 |
+
if response.status_code == 200:
|
199 |
+
data = response.json()
|
200 |
+
if data['status'] == 'OK':
|
201 |
+
location = data['results'][0]['geometry']['location']
|
202 |
+
return location['lat'], location['lng']
|
203 |
+
else:
|
204 |
+
raise ValueError("Geocoding failed.")
|
205 |
+
else:
|
206 |
+
raise ValueError("Failed to retrieve geocoding data.")
|
207 |
+
|
208 |
# Main function to execute script
|
209 |
def main():
|
210 |
google_places_data = get_all_places(query, location, radius, api_key)
|
|
|
220 |
|
221 |
# User input for text (emotion detection)
|
222 |
user_input_emotion = gr.Textbox(lines=1, label="How are you feeling today?")
|
223 |
+
submit_emotion = gr.Button("Submit")
|
224 |
|
225 |
# Model prediction for emotion detection
|
226 |
def predict_emotion(text):
|
227 |
+
inputs = tokenizer_sentiment(text, return_tensors="pt").to('cpu')
|
228 |
+
with torch.no_grad():
|
229 |
+
outputs = pytorch_model(inputs['input_ids'])
|
230 |
+
_, predicted_class = torch.max(outputs, dim=1)
|
231 |
+
emotion = labels[predicted_class.item()]
|
232 |
return emotion
|
233 |
|
234 |
+
# Show suggestions based on the detected emotion
|
|
|
|
|
235 |
def show_suggestions(emotion):
|
236 |
if emotion == 'joy':
|
237 |
return "You're feeling happy! Keep up the great mood!\nUseful Resources:\n[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)\n[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)"
|
238 |
elif emotion == 'anger':
|
239 |
+
return "You're feeling angry. It's okay to feel this way. Let's try to calm down.\nUseful Resources:\n[Emotional wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)\n[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/MIc299Flibs)"
|
240 |
elif emotion == 'fear':
|
241 |
+
return "You're feeling fearful. Take a moment to breathe and relax.\nUseful Resources:\n[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)\n[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n[Emotional wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/yGKKz185M5o)"
|
242 |
elif emotion == 'sadness':
|
243 |
+
return "You're feeling sad. It's okay to take a break.\nUseful Resources:\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/-e-4Kx5px_I)"
|
244 |
elif emotion == 'surprise':
|
245 |
+
return "You're feeling surprised. It's okay to feel neutral!\nUseful Resources:\n[Managing Stress](https://www.health.harvard.edu/health-a-to-z)\n[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)"
|
246 |
|
247 |
emotion_output = gr.Textbox(label="Emotion Detected")
|
248 |
+
submit_emotion.click(predict_emotion, inputs=user_input_emotion, outputs=emotion_output)
|
249 |
|
250 |
# Button for summary
|
251 |
def show_summary(emotion):
|
|
|
258 |
# Chatbot functionality
|
259 |
chatbot = gr.Chatbot(label="Chat")
|
260 |
message_input = gr.Textbox(lines=1, label="Message")
|
261 |
+
submit_chat = gr.Button("Send")
|
262 |
|
263 |
def chat(message, history):
|
264 |
history = history or []
|
|
|
285 |
history.append((message, response))
|
286 |
return history, history
|
287 |
|
288 |
+
submit_chat.click(chat, inputs=[message_input, gr.State()], outputs=[chatbot, gr.State()])
|
289 |
+
|
290 |
+
# Location input for fetching nearby health professionals
|
291 |
+
location_input = gr.Textbox(lines=1, label="Enter your location (plain English):")
|
292 |
+
submit_location = gr.Button("Find Nearby Health Professionals")
|
293 |
+
|
294 |
+
# Fetch and display nearby health professionals
|
295 |
+
def fetch_nearby_health_professionals(location):
|
296 |
+
try:
|
297 |
+
lat, lon = geocode_location(location)
|
298 |
+
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"
|
299 |
+
radius = 50000 # 50 km radius
|
300 |
+
|
301 |
+
all_results = get_all_places(query, f"{lat},{lon}", radius, api_key)
|
302 |
+
if all_results:
|
303 |
+
df = pd.DataFrame(all_results, columns=["Name", "Address", "Phone", "Rating", "Business Status", "User Reviews Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
|
304 |
+
return df
|
305 |
+
else:
|
306 |
+
return "No data found."
|
307 |
+
except Exception as e:
|
308 |
+
return str(e)
|
309 |
+
|
310 |
+
nearby_health_professionals_table = gr.Dataframe(headers=["Name", "Address", "Phone", "Rating", "Business Status", "User Reviews Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
|
311 |
+
submit_location.click(fetch_navby_health_professionals, inputs=location_input, outputs=nearby_health_professionals_table)
|
312 |
|
313 |
# User input for text (sentiment analysis)
|
314 |
user_input_sentiment = gr.Textbox(lines=1, label="Enter text to analyze sentiment:")
|
315 |
+
submit_sentiment = gr.Button("Submit")
|
316 |
+
|
317 |
# Prediction button for sentiment analysis
|
318 |
def predict_sentiment(text):
|
319 |
inputs = tokenizer_sentiment(text, return_tensors="pt")
|
|
|
324 |
return sentiment
|
325 |
|
326 |
sentiment_output = gr.Textbox(label="Predicted Sentiment")
|
327 |
+
submit_sentiment.click(predict_sentiment, inputs=user_input_sentiment, outputs=sentiment_output)
|
328 |
|
329 |
# Button to fetch wellness professionals data
|
330 |
fetch_button = gr.Button("Fetch Wellness professionals data")
|