File size: 10,320 Bytes
334ba26
 
7684892
334ba26
 
 
 
7684892
334ba26
 
5e7f7ee
 
334ba26
 
5e7f7ee
7684892
334ba26
 
ae282f5
334ba26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48a4b0f
334ba26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aaa501
334ba26
 
 
 
 
 
 
 
ae282f5
334ba26
 
 
 
 
 
 
 
 
 
5e7f7ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334ba26
 
 
 
5e7f7ee
 
334ba26
 
 
 
 
 
 
 
 
 
 
 
5e7f7ee
 
 
334ba26
6239dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334ba26
 
 
ae282f5
334ba26
 
 
 
ae282f5
334ba26
6239dea
48a4b0f
334ba26
 
fce43ab
6239dea
 
 
 
334ba26
 
 
 
 
 
 
 
 
6239dea
334ba26
 
 
613b05f
fce43ab
334ba26
 
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
import json
import pickle
import random
import nltk
import numpy as np
import tflearn
import gradio as gr
import requests
import torch
import pandas as pd
from bs4 import BeautifulSoup
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
from nltk.tokenize import word_tokenize
from nltk.stem.lancaster import LancasterStemmer
import os

# 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


# Sentiment analysis setup
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")

# Emotion detection setup
def load_emotion_model():
    tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
    model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
    return tokenizer, model

tokenizer_emotion, model_emotion = load_emotion_model()

# Google Places API setup for wellness professionals
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
api_key = os.getenv("GOOGLE_API_KEY")  # Use environment variable for security

# Function to get places data using Google Places API
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

# Web scraping function to get wellness professional data (alternative to API)
def scrape_wellness_professionals(query, location):
    # User-Agent header to simulate a browser request
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    
    search_url = f"https://www.google.com/search?q={query}+near+{location}"
    
    # Make a request to the search URL with headers
    response = requests.get(search_url, headers=headers)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Parse and extract wellness professionals from the HTML
        wellness_data = []
        results = soup.find_all("div", class_="BVG0Nb")  # Adjust class based on the actual HTML structure
        for result in results:
            name = result.get_text()
            link = result.find("a")["href"] if result.find("a") else None
            wellness_data.append([name, link])
        
        return wellness_data
    else:
        return []

# Main function to fetch wellness professional data and display on map
def get_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"
    radius = 50000  # 50 km radius
    
    # Using Google Places API if available
    data = get_places_data(query, location, radius, api_key)

    if data:
        results = data.get('results', [])
        wellness_data = []
        for place in results:
            name = place.get("name")
            address = place.get("formatted_address")
            latitude = place.get("geometry", {}).get("location", {}).get("lat")
            longitude = place.get("geometry", {}).get("location", {}).get("lng")
            wellness_data.append([name, address, latitude, longitude])
        return wellness_data

    # Fallback to scraping if API is not available or fails
    return scrape_wellness_professionals(query, location)

# Emotion detection function with suggestions
def detect_emotion(user_input):
    pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
    result = pipe(user_input)
    emotion = result[0]['label']
    
    # Provide suggestions based on the detected emotion
    if emotion == 'joy':
        return ("You're feeling happy! Keep up the great mood!", 
                [("Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
                 ("Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
                 ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")],
                "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.", 
                [("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
                 ("Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"),
                 ("Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")],
                "Watch on YouTube: https://youtu.be/MIc299Flibs")
    elif emotion == 'fear':
        return ("You're feeling fearful. Take a moment to breathe and relax.", 
                [("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
                 ("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
                 ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")],
                "Watch on YouTube: https://youtu.be/yGKKz185M5o")
    elif emotion == 'sadness':
        return ("You're feeling sad. It's okay to take a break.", 
                [("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
                 ("Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")],
                "Watch on YouTube: https://youtu.be/-e-4Kx5px_I")
    elif emotion == 'surprise':
        return ("You're feeling surprised. It's okay to feel neutral!", 
                [("Managing Stress", "https://www.health.harvard.edu/health-a-to-z"),
                 ("Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")],
                "Watch on YouTube: https://youtu.be/m1vaUGtyo-A")
    return ("Could not detect emotion.", [], "")

# Gradio interface setup for user interaction
def user_interface(message, location, history):
    history, history = chat(message, history)
    
    # Sentiment analysis
    inputs = tokenizer_sentiment(message, return_tensors="pt")
    outputs = model_sentiment(**inputs)
    sentiment = ["Negative", "Neutral", "Positive"][torch.argmax(outputs.logits, dim=1).item()]
    
    # Emotion detection
    emotion_msg, resources, video_link = detect_emotion(message)
    
    # Get wellness professionals
    wellness_data = get_wellness_professionals(location)
    
    # Display wellness professionals in a table format
    wellness_df = pd.DataFrame(wellness_data, columns=["Name", "Address", "Latitude", "Longitude"])
    
    return history, history, sentiment, emotion_msg, resources, video_link, wellness_df.to_html(escape=False)

# Gradio chatbot interface
chatbot = gr.Chatbot(label="Mental Health Chatbot")
location_input = gr.Textbox(label="Enter your location (latitude,longitude)", placeholder="e.g., 21.3,-157.8")

# Gradio interface definition
demo = gr.Interface(
    user_interface,
    [gr.Textbox(label="Message"), location_input, "state"],
    [chatbot, "state", "text", "text", "json", "text", "html"],
    allow_flagging="never",
    title="Mental Health & Well-being Assistant"
)

# Launch Gradio interface
if __name__ == "__main__":
    demo.launch()