File size: 10,590 Bytes
1aa6549
334ba26
 
dacc7c0
4525308
 
ef41952
4525308
334ba26
 
19503c4
4525308
 
23325a3
19503c4
 
 
 
fa97be4
dacc7c0
334ba26
dacc7c0
19503c4
 
 
 
 
 
 
 
 
 
 
334ba26
 
dacc7c0
 
 
 
19503c4
334ba26
dacc7c0
 
 
 
19503c4
0e313c1
 
 
 
 
 
9164577
dacc7c0
 
 
 
4525308
0e313c1
334ba26
 
 
 
 
 
 
 
 
 
dacc7c0
334ba26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebca5ff
 
19503c4
 
dacc7c0
 
19503c4
 
 
 
 
 
 
 
 
 
dacc7c0
19503c4
 
 
 
674b44a
19503c4
dacc7c0
19503c4
 
4525308
19503c4
4525308
dacc7c0
 
 
 
 
 
4525308
 
dacc7c0
19503c4
 
 
 
 
4525308
23325a3
19503c4
23325a3
 
 
 
 
 
 
 
 
 
19503c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4525308
 
 
 
19503c4
4525308
 
 
19503c4
 
 
 
23325a3
19503c4
23325a3
4525308
 
 
 
 
 
 
19503c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23325a3
19503c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4525308
19503c4
4525308
0e313c1
dacc7c0
0e313c1
dacc7c0
19503c4
 
 
 
0bf96c0
 
456391b
 
 
 
 
19503c4
0bf96c0
456391b
 
19503c4
0bf96c0
 
456391b
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
import gradio as gr
import nltk
import numpy as np
import tflearn
import random
import json
import pickle
import torch
from nltk.tokenize import word_tokenize
from nltk.stem.lancaster import LancasterStemmer
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import requests
import pandas as pd
import os
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_autoinstaller

# Ensure necessary NLTK resources are downloaded
nltk.download('punkt')

# --- Constants ---
GOOGLE_MAPS_API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY")  # Get API key from environment variable
if not GOOGLE_MAPS_API_KEY:
    raise ValueError("Error: GOOGLE_MAPS_API_KEY environment variable not set.")

url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
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"


# --- Chatbot Logic ---
stemmer = LancasterStemmer()

try:
    with open("intents.json") as file:
        data = json.load(file)
except FileNotFoundError:
    raise FileNotFoundError("Error: 'intents.json' file not found.")

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

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)

model = tflearn.DNN(net)
try:
    model.load("MentalHealthChatBotmodel.tflearn")
except FileNotFoundError:
    raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")

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)

def chat(message, history):
    history = history or []
    message = message.lower()
    try:
        results = model.predict([bag_of_words(message, words)])
        results_index = np.argmax(results)
        tag = labels[results_index]
        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

# --- Sentiment Analysis ---
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")

def analyze_sentiment(text):
    try:
        inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
        with torch.no_grad():
            outputs = model_sentiment(**inputs)
        predicted_class = torch.argmax(outputs.logits, dim=1).item()
        sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
        return f"**Predicted Sentiment:** {sentiment}"
    except Exception as e:
        return f"Error analyzing sentiment: {str(e)}"

# --- Emotion Detection (Placeholder) ---
def detect_emotion(text):
    # Replace with your actual emotion detection logic
    return "Emotion detection not implemented"

# --- Suggestion Generation (Placeholder) ---
def provide_suggestions(emotion):
    # Replace with your actual suggestion generation logic
    return pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])

# --- Google Places API Functions ---
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:
        print(f"Error: {response.status_code} - {response.text}")
        return None

def get_place_details(place_id, api_key):
    params = {"place_id": place_id, "key": api_key}
    response = requests.get(places_details_url, params=params)
    if response.status_code == 200:
        details_data = response.json().get("result", {})
        return {
            "phone_number": details_data.get("formatted_phone_number", "Not available"),
            "website": details_data.get("website", "Not available")
        }
    else:
        return {}

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("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

def get_all_places(query, location, radius, api_key):
    all_results = []
    next_page_token = None
    while True:
        data = get_places_data(query + f" in {location}", 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")
                details = get_place_details(place_id, api_key)
                phone_number = details.get("phone_number", "Not available")
                website = details.get("website", "Not available")
                all_results.append([name, address, phone_number, website])
            next_page_token = data.get('next_page_token')
            if not next_page_token:
                break
        else:
            break
    return all_results

# --- Gradio Interface ---
def gradio_interface(message, location, state, btn_chat, btn_search):
    history = state or []
    if len(history) == 0:
        if btn_chat:
            history, _ = chat(message, history)
            sentiment = analyze_sentiment(message)
            emotion = detect_emotion(message)
            suggestions = provide_suggestions(emotion)
            if location:
                try:
                    wellness_results = pd.DataFrame(get_all_places(query, location, 50000, GOOGLE_MAPS_API_KEY), columns=["Name", "Address", "Phone", "Website"])
                except Exception as e:
                    wellness_results = pd.DataFrame([["Error fetching data: " + str(e), "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
            else:
                wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
        else:
            history = history
            sentiment = ""
            emotion = ""
            suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
            wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
    elif len(history) > 0 and location == "":
        if btn_chat:
            history, _ = chat(message, history)
            sentiment = analyze_sentiment(message)
            emotion = detect_emotion(message)
            suggestions = provide_suggestions(emotion)
            wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
        else:
            history = history
            sentiment = ""
            emotion = ""
            suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
            wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
    elif len(history) > 0 and location != "" and btn_search:
        try:
            wellness_results = pd.DataFrame(get_all_places(query, location, 50000, GOOGLE_MAPS_API_KEY), columns=["Name", "Address", "Phone", "Website"])
            sentiment = analyze_sentiment(message)
            emotion = detect_emotion(message)
            suggestions = provide_suggestions(emotion)
            history, _ = chat(message, history)
        except Exception as e:
            wellness_results = pd.DataFrame([["Error: " + str(e), "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
    else:
        history = history
        sentiment = ""
        emotion = ""
        suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
        wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])

    return history, sentiment, emotion, suggestions, wellness_results, history

iface = gr.Interface(
    fn=gradio_interface,
    inputs=[
        gr.Textbox(label="Enter your message", placeholder="How are you feeling today?"),
        gr.Textbox(label="Enter your location (e.g., 'Hawaii, USA')", placeholder="Enter your location (optional)"),
        gr.State(),
        gr.Button("Chat"),
        gr.Button("Search")
    ],
    outputs=[
        gr.Chatbot(label="Chatbot Responses"),
        gr.Textbox(label="Sentiment Analysis"),
        gr.Textbox(label="Emotion Detected"),
        gr.DataFrame(label="Suggested Articles & Videos"),
        gr.DataFrame(label="Nearby Wellness Professionals"),
        gr.State()
    ],
    live=True,
    title="Mental Health Chatbot with Wellness Professional Search",
    description="This chatbot provides mental health support with sentiment analysis, emotion detection, suggestions, and a list of nearby wellness professionals. Interact with the chatbot first, then enter a location to search."
)

iface.launch(debug=True, share=True)