File size: 9,592 Bytes
1aa6549
0bbb821
d5331b4
4525308
e623c13
 
 
19503c4
e623c13
19503c4
e623c13
2ae19d7
 
97f0957
 
 
2ae19d7
fd60b30
bdc8fc1
ed12172
c69efb6
fa97be4
e623c13
334ba26
dacc7c0
9b1c27f
 
 
e623c13
334ba26
 
e623c13
dacc7c0
 
 
 
e623c13
334ba26
e623c13
dacc7c0
e623c13
 
dacc7c0
e623c13
0e313c1
c69efb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5331b4
 
c69efb6
d5331b4
c69efb6
 
 
d5331b4
c69efb6
 
 
 
97f0957
c69efb6
 
 
d5331b4
c69efb6
 
 
d5331b4
c69efb6
e623c13
 
 
 
 
 
c69efb6
 
e623c13
23325a3
c69efb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4525308
c69efb6
e623c13
c69efb6
97f0957
c69efb6
e623c13
c69efb6
e623c13
 
d5331b4
97f0957
e623c13
d5331b4
e623c13
c69efb6
e623c13
97f0957
d5331b4
 
c69efb6
d5331b4
c69efb6
d5331b4
c69efb6
d5331b4
c69efb6
d5331b4
c69efb6
d5331b4
 
97f0957
d5331b4
 
 
c69efb6
d5331b4
 
 
 
e623c13
 
 
 
97f0957
e623c13
 
 
 
d5331b4
e623c13
e91aed5
0bbb821
e623c13
 
 
e91aed5
e623c13
 
 
 
 
 
 
 
 
 
d5331b4
e623c13
 
 
97f0957
 
 
 
 
 
 
 
c69efb6
 
97f0957
c69efb6
9b1c27f
e623c13
d5331b4
 
97f0957
 
d5331b4
 
c69efb6
d5331b4
 
97f0957
d5331b4
e623c13
c69efb6
 
e623c13
 
c69efb6
 
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
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
import random

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

# 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 = nltk.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 be 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_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
sentiment_pipeline = pipeline("sentiment-analysis")

def predict_sentiment(text):
    result = sentiment_pipeline(text)[0]
    return result['label']

# Emotion detection
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
emotion_pipeline = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)

def predict_emotion(text):
    result = emotion_pipeline(text)[0]
    return result['label']

# Fetching nearby health professionals
google_places_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
google_geocoding_url = "https://maps.googleapis.com/maps/api/geocode/json"

def get_places_data(query, location, radius, api_key):
    params = {
        "query": query,
        "location": location,
        "radius": radius,
        "key": api_key
    }
    response = requests.get(google_places_url, params=params)
    return response.json()

def get_place_details(place_id, api_key):
    details_url = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&fields=name,rating,formatted_phone_number&key={api_key}"
    response = requests.get(details_url)
    return response.json()

def fetch_nearby_health_professionals(location):
    api_key = "GOOGLE_API_KEY"  # Replace with your actual Google API key
    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
    
    response = get_places_data(query, location, radius, api_key)
    results = response.get('results', [])
    
    data = []
    for place in results:
        place_id = place['place_id']
        place_details = get_place_details(place_id, api_key)
        name = place_details.get('result', {}).get('name', 'N/A')
        rating = place_details.get('result', {}).get('rating', 'N/A')
        phone_number = place_details.get('result', {}).get('formatted_phone_number', 'N/A')
        
        data.append([name, rating, phone_number])
    
    return pd.DataFrame(data, columns=['Name', 'Rating', 'Phone Number'])

# Save results to CSV
def save_to_csv(data, filename):
    data.to_csv(filename, index=False)

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# Mental Health Assistant")

    # 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):
        return predict_emotion(text)

    # Show suggestions based on the detected emotion
    def show_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."
        elif emotion == 'fear':
            return "You're feeling fearful. Take a moment to breathe and relax."
        elif emotion == 'sadness':
            return "You're feeling sad. It's okay to take a break."
        elif emotion == 'surprise':
            return "You're feeling surprised. It's okay to feel neutral!"

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

    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):
        df = fetch_nearby_health_professionals(location)
        return df

    nearby_health_professionals_table = gr.Dataframe(headers=["Name", "Rating", "Phone Number"])
    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):
        return predict_sentiment(text)

    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", "Rating", "Phone Number"])

    def fetch_data():
        df = fetch_nearby_health_professionals("Hawaii")
        return df

    fetch_button.click(fetch_data, inputs=None, outputs=data_output)

# Launch Gradio interface
demo.launch()