File size: 10,141 Bytes
d3aead7
7684892
 
 
 
 
 
48a4b0f
7684892
 
48a4b0f
7684892
 
 
540646a
d3aead7
7684892
 
 
 
 
 
 
 
48a4b0f
 
7684892
48a4b0f
7684892
 
 
48a4b0f
 
7684892
48a4b0f
7684892
 
 
 
 
 
 
 
 
 
 
48a4b0f
7684892
48a4b0f
7684892
 
 
48a4b0f
 
 
 
 
 
 
 
7684892
 
48a4b0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae282f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48a4b0f
 
ae282f5
48a4b0f
 
 
 
 
7684892
0aa146d
 
 
 
48a4b0f
 
 
 
 
 
 
 
ae282f5
 
 
 
 
 
 
 
 
48a4b0f
ae282f5
d3aead7
48a4b0f
0aa146d
 
 
ae282f5
48a4b0f
 
 
 
ae282f5
 
48a4b0f
 
ae282f5
48a4b0f
 
 
 
d3aead7
ae282f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48a4b0f
 
 
ba98e87
 
 
 
 
 
 
48a4b0f
c5f3d57
48a4b0f
 
 
 
613b05f
 
 
48a4b0f
613b05f
 
 
48a4b0f
613b05f
0aa146d
613b05f
 
 
 
 
 
48a4b0f
613b05f
 
ae282f5
613b05f
 
 
 
 
 
ae282f5
613b05f
 
 
 
 
 
 
 
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
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, pipeline
import requests
from bs4 import BeautifulSoup
import pandas as pd
import geocoder  # Use geocoder to get latitude/longitude from city

# 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, state):
    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?"

        # Add emoticons to the response
        emoticon_dict = {
            "joy": "😊",
            "anger": "😑",
            "fear": "😨",
            "sadness": "πŸ˜”",
            "surprise": "😲",
            "neutral": "😐"
        }

        # Add the emotion-related emoticon to the response
        for tg in data["intents"]:
            if tg['tag'] == tag:
                emotion = tg.get('emotion', 'neutral')  # Default to neutral if no emotion is defined
                response = f"{response} {emoticon_dict.get(emotion, '😐')}"
                break
        
        history.append((message, response))

        # Transition to the next feature (sentiment analysis)
        state['step'] = 2  # Move to sentiment analysis
    except Exception as e:
        response = f"An error occurred: {str(e)}"

    return history, history, state

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

# Function for sentiment analysis
def analyze_sentiment(text, state):
    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]
    
    # Add emoticon to sentiment
    sentiment_emojis = {
        "Negative": "😞",
        "Neutral": "😐",
        "Positive": "😊"
    }
    sentiment_with_emoji = f"{sentiment} {sentiment_emojis.get(sentiment, '😐')}"
    
    # Transition to emotion detection
    state['step'] = 3  # Move to emotion detection and suggestions
    return sentiment_with_emoji, state

# 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 emotion detection and suggestions
def detect_emotion(text, state):
    pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
    result = pipe(text)
    emotion = result[0]['label']
    
    # Provide suggestions based on detected emotion
    suggestions = provide_suggestions(emotion)
    
    # Transition to wellness professional search
    state['step'] = 4  # Move to wellness professional search
    return emotion, suggestions, state

# Suggestions based on detected emotion
def provide_suggestions(emotion):
    resources = {
        'joy': {
            'message': "You're feeling happy! Keep up the great mood! 😊",
            'articles': [
                "[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)"
            ],
            'videos': "[Watch Relaxation Video](https://youtu.be/m1vaUGtyo-A)"
        },
        'anger': {
            'message': "You're feeling angry. It's okay to feel this way. Let's try to calm down. 😑",
            'articles': [
                "[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)",
                "[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)"
            ],
            'videos': "[Watch Anger Management Video](https://youtu.be/MIc299Flibs)"
        },
        'fear': {
            'message': "You're feeling fearful. Take a moment to breathe and relax. 😨",
            'articles': [
                "[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)"
            ],
            'videos': "[Watch Coping Video](https://youtu.be/yGKKz185M5o)"
        },
        'sadness': {
            'message': "You're feeling sad. It's okay to take a break. πŸ˜”",
            'articles': [
                "[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)"
            ],
            'videos': "[Watch Sadness Relief Video](https://youtu.be/-e-4Kx5px_I)"
        },
        'surprise': {
            'message': "You're feeling surprised. It's okay to feel neutral! 😲",
            'articles': [
                "[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)"
            ],
            'videos': "[Watch Stress Relief Video](https://youtu.be/m1vaUGtyo-A)"
        }
    }
    return resources.get(emotion, {'message': "Stay calm. πŸ™‚", 'articles': [], 'videos': []})

# Function to find wellness professionals
def find_wellness_professionals(location, state):
    # Geocode the location to get latitude and longitude
    g = geocoder.osm(location)  # Using OpenStreetMap's geocoding service
    if g.ok:
        location_coords = f"{g.lat},{g.lng}"
    else:
        return "Sorry, could not retrieve coordinates for the location. Please try again.", state
    
    query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist in " + location
    api_key = "GOOGLE_API_KEY"  # Replace with your own API key
    radius = 50000  # 50 km radius
    
    google_places_data = get_all_places(query, location_coords, radius, api_key)
    if google_places_data:
        response = "Wellness professionals near you:\n"
        for place in google_places_data:
            response += f"- {place['name']} at {place['formatted_address']}\n"
    else:
        response = "Sorry, no wellness professionals found in your area. Please try another location."

    return response, state

# Call Google Places API
def get_all_places(query, location, radius, api_key):
    search_url = f"https://maps.googleapis.com/maps/api/place/textsearch/json?query={query}&location={location}&radius={radius}&key={api_key}"
    response = requests.get(search_url).json()
    
    if 'results' in response:
        return response['results']
    return []

# Gradio UI components
def create_ui():
    with gr.Blocks() as demo:
        state = gr.State()
        chatbot = gr.Chatbot(elem_id="chatbot", label="Mental Health Chatbot")
        message_input = gr.Textbox(placeholder="Ask me something...", label="Enter your message")
        sentiment_output = gr.Textbox(placeholder="Sentiment result", label="Sentiment")
        emotion_output = gr.Textbox(placeholder="Detected emotion", label="Emotion")
        wellness_output = gr.Textbox(placeholder="Wellness professional list", label="Wellness Professionals")
        
        message_input.submit(chat, [message_input, chatbot, state], [chatbot, chatbot, state])
        message_input.submit(analyze_sentiment, [message_input, state], [sentiment_output, state])
        sentiment_output.submit(detect_emotion, [sentiment_output, state], [emotion_output, wellness_output, state])
        return demo

# Launch the Gradio interface
demo = create_ui()
demo.launch(debug=True)