File size: 11,632 Bytes
d3aead7
 
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
 
 
7684892
d3aead7
7684892
d3aead7
0aa146d
d3aead7
0aa146d
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
956a1f8
7684892
 
d3aead7
7684892
 
 
d3aead7
7684892
 
 
d3aead7
7684892
d3aead7
 
 
 
 
7684892
d3aead7
 
7684892
 
d3aead7
7684892
d3aead7
 
 
 
 
7684892
d3aead7
 
7684892
 
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
d3aead7
7684892
 
 
d3aead7
7684892
d3aead7
7684892
d3aead7
 
 
7684892
d3aead7
 
7684892
 
d3aead7
7684892
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7684892
 
d3aead7
7684892
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7684892
0aa146d
d3aead7
0aa146d
d3aead7
0aa146d
 
 
d3aead7
0aa146d
d3aead7
0aa146d
 
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aa146d
 
d3aead7
0aa146d
d3aead7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import gradio as gr

import nltk

import numpy as np

import tflearn

import tensorflow

import random

import json

import pickle

import nltk

from nltk.tokenize import word_tokenize

from nltk.stem.lancaster import LancasterStemmer

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

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

import chromedriver_autoinstaller

import os

import torch

# Ensure necessary NLTK resources are downloaded

nltk.download('punkt')

# 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.")

# Build the model structure

net = tflearn.input_data(shape=[None, len(training[0])])

net = tflearn.fully_connected(net, 8)

net = tflearn.fully_connected(net, 8)

net = tflearn.fully_connected(net, len(output[0]), activation="softmax")

net = tflearn.regression(net)

# Load the trained model

model = tflearn.DNN(net)

try:

model.load("MentalHealthChatBotmodel.tflearn")

except FileNotFoundError:

raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")

# Function to process user input into a bag-of-words format

def bag_of_words(s, words):

bag = [0 for _ in range(len(words))]

s_words = word_tokenize(s)

s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]

for se in s_words:

for i, w in enumerate(words):

if w == se:

bag[i] = 1

return np.array(bag)

# Chat function

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

# Load pre-trained model and tokenizer for sentiment analysis

tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")

sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")

# Load pre-trained model and tokenizer for emotion detection

emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")

emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")

# Function for sentiment analysis

def analyze_sentiment(text):

inputs = tokenizer(text, return_tensors="pt")

with torch.no_grad():

outputs = sentiment_model(**inputs)

predicted_class = torch.argmax(outputs.logits, dim=1).item()

sentiment = ["Negative", "Neutral", "Positive"][predicted_class]

return sentiment

# Function for emotion detection

def detect_emotion(text):

pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)

result = pipe(text)

emotion = result[0]['label']

return emotion

# Function to provide suggestions based on emotion

def provide_suggestions(emotion):

if emotion == 'joy':

return "You're feeling happy! Keep up the great mood!"

elif emotion == 'anger':

return "You're feeling angry. It's okay to feel this way. Let's try to calm down."

# Add more conditions for other emotions...

else:

return "Sorry, no suggestions available for this emotion."

# Combined function for emotion detection and suggestions

def detect_emotion_and_suggest(text):

emotion = detect_emotion(text)

suggestions = provide_suggestions(emotion)

return emotion, suggestions

# Function to scrape website URL from Google Maps using Selenium

def scrape_website_from_google_maps(place_name):

chrome_options = Options()

chrome_options.add_argument("--headless")

chrome_options.add_argument("--no-sandbox")

chrome_options.add_argument("--disable-dev-shm-usage")

driver = webdriver.Chrome(options=chrome_options)

search_url = f"https://www.google.com/maps/search/{place_name.replace(' ', '+')}"

driver.get(search_url)

time.sleep(5)

try:

website_element = driver.find_element_by_xpath('//a[contains(@aria-label, "Visit") and contains(@aria-label, "website")]')

website_url = website_element.get_attribute('href')

except:

website_url = "Not available"

driver.quit()

return website_url

# Function to scrape website for contact information

def scrape_website_for_contact_info(website):

phone_number = "Not available"

email = "Not available"

try:

response = requests.get(website, timeout=5)

soup = BeautifulSoup(response.content, 'html.parser')

phone_match = re.search(r'$$?\+?[0-9]*$$?[0-9_\- $$$$]*', soup.get_text())

if phone_match:

phone_number = phone_match.group()

email_match = re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', soup.get_text())

if email_match:

email = email_match.group()

except Exception as e:

print(f"Error scraping website {website}: {e}")

return phone_number, email

# Function to fetch detailed information for a specific place using its place_id

def get_place_details(place_id, api_key):

details_url = "https://maps.googleapis.com/maps/api/place/details/json"

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 get 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', [])

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_ratings_total = place.get("user_ratings_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_website_for_contact_info(website)

else:

email = "Not available"

if website == "Not available":

website = scrape_website_from_google_maps(name)

all_results.append([name, address, phone_number, rating, business_status,

user_ratings_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 Ratings Total", "Website", "Types", "Latitude", "Longitude",

"Opening Hours", "Reviews", "Email"

])

writer.writerows(data)

print(f"Data saved to {filename}")

# Function to get places data from Google Places API

def get_places_data(query, location, radius, api_key, next_page_token=None):

url = "https://maps.googleapis.com/maps/api/place/textsearch/json"

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:

data = response.json()

return data

else:

print(f"Error: {response.status_code} - {response.text}")

return None

# Function to find local wellness professionals

def find_wellness_professionals(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 in " + location

api_key = "AIzaSyCcfJzMFfuv_1LN7JPTJJYw_aS0A_SLeW0"  # Replace with your own Google API key

location_coords = "21.3,-157.8"  # Default to Oahu, Hawaii

radius = 50000  # 50 km radius

# Install Chrome and Chromedriver

def install_chrome_and_driver():

os.system("apt-get update")

os.system("apt-get install -y wget curl")

os.system("wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb")

os.system("dpkg -i google-chrome-stable_current_amd64.deb")

os.system("apt-get install -y -f")

os.system("google-chrome-stable --version")

chromedriver_autoinstaller.install()

install_chrome_and_driver()

# Get all places data

google_places_data = get_all_places(query, location_coords, radius, api_key)

if google_places_data:

df = pd.DataFrame(google_places_data, columns=[

"Name", "Address", "Phone", "Rating", "Business Status",

"User Ratings Total", "Website", "Types", "Latitude", "Longitude",

"Opening Hours", "Reviews", "Email"

])

return df

else:

return pd.DataFrame()

with gr.Blocks() as demo:

gr.Markdown("# Wellbeing Support System")

with gr.Tab("Chatbot"):

chatbot = gr.Chatbot()

msg = gr.Textbox()

clear = gr.Button("Clear")

msg.submit(chat, inputs=[msg, chatbot], outputs=chatbot)

clear.click(lambda: None, None, chatbot)

with gr.Tab("Sentiment Analysis"):

text_input = gr.Textbox(label="Enter text to analyze sentiment:")

analyze_button = gr.Button("Analyze Sentiment")

sentiment_output = gr.Textbox(label="Sentiment:")

analyze_button.click(analyze_sentiment, inputs=text_input, outputs=sentiment_output)

with gr.Tab("Emotion Detection & Suggestions"):

emotion_input = gr.Textbox(label="How are you feeling today?", value="Enter your thoughts here...")

detect_button = gr.Button("Detect Emotion")

emotion_output = gr.Textbox(label="Detected Emotion:")

suggestions_output = gr.Textbox(label="Suggestions:")

detect_button.click(detect_emotion_and_suggest, inputs=emotion_input, outputs=[emotion_output, suggestions_output])

with gr.Tab("Find Local Wellness Professionals"):

location_input = gr.Textbox(label="Enter your location:", value="Hawaii")

search_button = gr.Button("Search")

results_output = gr.Dataframe(label="Search Results")

search_button.click(find_wellness_professionals, inputs=location_input, outputs=results_output)

demo.launch()