Spaces:
Sleeping
Sleeping
File size: 16,059 Bytes
1aa6549 0bbb821 d5331b4 4525308 e623c13 19503c4 e623c13 19503c4 e623c13 2ae19d7 97f0957 2ae19d7 fd60b30 bdc8fc1 ed12172 fa97be4 e623c13 334ba26 dacc7c0 9b1c27f e623c13 334ba26 e623c13 dacc7c0 e623c13 334ba26 e623c13 dacc7c0 e623c13 dacc7c0 e623c13 0e313c1 97f0957 cd4c7ed 97f0957 cd4c7ed 24060be 157e55a 24060be 157e55a 97f0957 4525308 d5331b4 97f0957 d5331b4 e623c13 4525308 e623c13 4525308 e623c13 dacc7c0 e623c13 19503c4 4525308 e623c13 23325a3 e623c13 23325a3 e623c13 23325a3 e623c13 4525308 ee50fd8 4525308 e623c13 4525308 19503c4 e623c13 97f0957 e623c13 19503c4 23325a3 e623c13 e91aed5 e623c13 e91aed5 e623c13 97f0957 e623c13 4525308 e623c13 4525308 e623c13 4525308 e623c13 d5331b4 e91aed5 d5331b4 e623c13 97f0957 e623c13 19503c4 e623c13 d5331b4 97f0957 e623c13 d5331b4 e623c13 97f0957 e623c13 97f0957 d5331b4 24060be d5331b4 24060be d5331b4 97f0957 d5331b4 97f0957 d5331b4 97f0957 d5331b4 e623c13 97f0957 e623c13 d5331b4 e623c13 e91aed5 0bbb821 e623c13 e91aed5 e623c13 d5331b4 e623c13 97f0957 9b1c27f e623c13 d5331b4 97f0957 d5331b4 97f0957 d5331b4 e623c13 e91aed5 e623c13 e91aed5 e623c13 53595f6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import pipeline
import requests
import csv
import time
import re
from bs4 import BeautifulSoup
import pandas as pd
import chromedriver_autoinstaller
import os
import nltk
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import tflearn
import tensorflow as tf
import json
import pickle
# Ensure necessary NLTK resources are downloaded
nltk.download('punkt')
# Import LancasterStemmer from nltk.stem
from nltk.stem import LancasterStemmer
# Initialize the stemmer
stemmer = LancasterStemmer()
# Load intents.json
try:
with open("intents.json") as file:
data = json.load(file)
except FileNotFoundError:
raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
# Load preprocessed data from pickle
try:
with open("data.pickle", "rb") as f:
words, labels, training, output = pickle.load(f)
except FileNotFoundError:
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
# Define a PyTorch model with the same architecture as your tflearn model
class PyTorchModel(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, num_classes):
super(PyTorchModel, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.fc1 = nn.Linear(embedding_dim, hidden_dim)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_dim, num_classes)
def forward(self, x):
out = self.embedding(x)
out = torch.mean(out, dim=1)
out = self.fc1(out)
out = self.relu(out)
out = self.fc2(out)
return out
# Convert the tflearn model to a PyTorch model
vocab_size = len(words)
embedding_dim = 128
hidden_dim = 64
num_classes = len(labels)
# Load the TensorFlow model
model_tf = tflearn.DNN(tflearn.input_data(shape=[None, len(training[0])]))
model_tf.load("MentalHealthChatBotmodel.tflearn")
# Convert the TensorFlow model to a PyTorch model
pytorch_model = PyTorchModel(vocab_size, embedding_dim, hidden_dim, num_classes)
# Load weights from the TensorFlow model
layer_names = ['fc1/kernel', 'fc1/bias', 'fc2/kernel', 'fc2/bias']
for layer_name in layer_names:
weight_tensor = getattr(model_tf, layer_name)
pytorch_layer_name = layer_name.replace('/', '_')
pytorch_model.state_dict()[pytorch_layer_name].copy_(torch.tensor(weight_tensor.eval(session=model_tf.trainer.session)))
# Move the model to the CPU
pytorch_model.cpu()
# Load tokenizer and model for sentiment analysis
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
# Google Places API endpoint
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
# Google Geocoding API endpoint
geocoding_url = "https://maps.googleapis.com/maps/api/geocode/json"
# Your actual Google API Key (replace with your key)
api_key = "AIzaSyCcfJzMFfuv_1LN7JPTJJYw_aS0A_SLeW0" # Replace with your own Google API key
# Search query for wellness professionals in Hawaii
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"
# Function to send a request to Google Places API and fetch places data
def get_places_data(query, location, radius, api_key, next_page_token=None):
params = {
"query": query,
"location": location,
"radius": radius,
"key": api_key
}
if next_page_token:
params["pagetoken"] = next_page_token
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
return None
# Function to fetch detailed information for a specific place using its place_id
def get_place_details(place_id, api_key):
details_url = places_details_url
params = {
"place_id": place_id,
"key": api_key
}
response = requests.get(details_url, params=params)
if response.status_code == 200:
details_data = response.json().get("result", {})
return {
"opening_hours": details_data.get("opening_hours", {}).get("weekday_text", "Not available"),
"reviews": details_data.get("reviews", "Not available"),
"phone_number": details_data.get("formatted_phone_number", "Not available"),
"website": details_data.get("website", "Not available")
}
else:
return {}
# Function to fetch all places data including pagination
def get_all_places(query, location, radius, api_key):
all_results = []
next_page_token = None
while True:
data = get_places_data(query, location, radius, api_key, next_page_token)
if data:
results = data.get('results', [])
if not results:
break
for place in results:
place_id = place.get("place_id")
name = place.get("name")
address = place.get("formatted_address")
rating = place.get("rating", "Not available")
business_status = place.get("business_status", "Not available")
user_reviews_total = place.get("user_reviews_total", "Not available")
website = place.get("website", "Not available")
types = ", ".join(place.get("types", []))
location = place.get("geometry", {}).get("location", {})
latitude = location.get("lat", "Not available")
longitude = location.get("lng", "Not available")
details = get_place_details(place_id, api_key)
phone_number = details.get("phone_number", "Not available")
if phone_number == "Not available" and website != "Not available":
phone_number, email = scrape_div_for_contact_info(website)
else:
email = "Not available"
if website == "Not available":
website = scrape_div_from_google_maps(name)
all_results.append([name, address, phone_number, rating, business_status,
user_reviews_total, website, types, latitude, longitude,
details.get("opening_hours", "Not available"),
details.get("reviews", "Not available"), email])
next_page_token = data.get('next_page_token')
if not next_page_token:
break
time.sleep(2)
else:
break
return all_results
# Function to save results to CSV file
def save_to_csv(data, filename):
with open(filename, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
"Name", "Address", "Phone", "Rating", "Business Status",
"User Reviews Total", "Website", "Types", "Latitude", "Longitude",
"Opening Hours", "Reviews", "Email"
])
writer.writerows(data)
print(f"Data saved to {filename}")
# Geocoding function to convert location text to coordinates
def geocode_location(address):
params = {
"address": address,
"key": api_key
}
response = requests.get(geocoding_url, params=params)
if response.status_code == 200:
data = response.json()
if data['status'] == 'OK':
location = data['results'][0]['geometry']['location']
return location['lat'], location['lng']
else:
raise ValueError("Geocoding failed.")
else:
raise ValueError("Failed to retrieve geocoding data.")
# Main function to execute script
def main():
google_places_data = get_all_places(query, location, radius, api_key)
if google_places_data:
save_to_csv(google_places_data, "wellness_professionals_hawaii.csv")
else:
print("No data found.")
# Gradio UI setup
with gr.Blocks() as demo:
# Display header
gr.Markdown("# Emotion Detection and Well-Being Suggestions")
# User input for text (emotion detection)
user_input_emotion = gr.Textbox(lines=1, label="How are you feeling today?")
submit_emotion = gr.Button("Submit")
# Model prediction for emotion detection
def predict_emotion(text):
inputs = tokenizer_sentiment(text, return_tensors="pt").to('cpu')
with torch.no_grad():
outputs = pytorch_model(inputs['input_ids'])
_, predicted_class = torch.max(outputs, dim=1)
emotion = labels[predicted_class.item()]
return emotion
# Show suggestions based on the detected emotion
def show_suggestions(emotion):
if emotion == 'joy':
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)"
elif emotion == 'anger':
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)"
elif emotion == 'fear':
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)"
elif emotion == 'sadness':
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)"
elif emotion == 'surprise':
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)"
emotion_output = gr.Textbox(label="Emotion Detected")
submit_emotion.click(predict_emotion, inputs=user_input_emotion, outputs=emotion_output)
# Button for summary
def show_summary(emotion):
return f"Emotion Detected: {emotion}\nUseful Resources based on your mood:\n{show_suggestions(emotion)}"
summary_button = gr.Button("Show Summary")
summary_output = gr.Textbox(label="Summary")
summary_button.click(show_summary, inputs=emotion_output, outputs=summary_output)
# Chatbot functionality
chatbot = gr.Chatbot(label="Chat")
message_input = gr.Textbox(lines=1, label="Message")
submit_chat = gr.Button("Send")
def chat(message, history):
history = history or []
message = message.lower()
try:
# Predict the tag
results = model.predict([bag_of_words(message, words)])
results_index = np.argmax(results)
tag = labels[results_index]
# Match tag with intent and choose a random response
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
response = random.choice(responses)
break
else:
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
except Exception as e:
response = f"An error occurred: {str(e)}"
history.append((message, response))
return history, history
submit_chat.click(chat, inputs=[message_input, gr.State()], outputs=[chatbot, gr.State()])
# Location input for fetching nearby health professionals
location_input = gr.Textbox(lines=1, label="Enter your location (plain English):")
submit_location = gr.Button("Find Nearby Health Professionals")
# Fetch and display nearby health professionals
def fetch_nearby_health_professionals(location):
try:
lat, lon = geocode_location(location)
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"
radius = 50000 # 50 km radius
all_results = get_all_places(query, f"{lat},{lon}", radius, api_key)
if all_results:
df = pd.DataFrame(all_results, columns=["Name", "Address", "Phone", "Rating", "Business Status", "User Reviews Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
return df
else:
return "No data found."
except Exception as e:
return str(e)
nearby_health_professionals_table = gr.Dataframe(headers=["Name", "Address", "Phone", "Rating", "Business Status", "User Reviews Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
submit_location.click(fetch_nearby_health_professionals, inputs=location_input, outputs=nearby_health_professionals_table)
# User input for text (sentiment analysis)
user_input_sentiment = gr.Textbox(lines=1, label="Enter text to analyze sentiment:")
submit_sentiment = gr.Button("Submit")
# Prediction button for sentiment analysis
def predict_sentiment(text):
inputs = tokenizer_sentiment(text, return_tensors="pt")
with torch.no_grad():
outputs = model_sentiment(**inputs)
predicted_class = torch.argmax(outputs.logits, dim=1).item()
sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
return sentiment
sentiment_output = gr.Textbox(label="Predicted Sentiment")
submit_sentiment.click(predict_sentiment, inputs=user_input_sentiment, outputs=sentiment_output)
# Button to fetch wellness professionals data
fetch_button = gr.Button("Fetch Wellness professionals data")
data_output = gr.Dataframe(headers=["Name", "Address", "Phone", "Rating", "Business Status", "User Reviews Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
def fetch_data():
all_results = get_all_places(query, location, radius, api_key)
if all_results:
return pd.DataFrame(all_results, columns=["Name", "Address", "Phone", "Rating", "Business Status", "User Reviews Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
else:
return "No data found."
fetch_button.click(fetch_data, inputs=None, outputs=data_output)
# Launch Gradio interface
demo.launch() |