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|
|
|
|
1 |
+
import nltk
|
2 |
+
import numpy as np
|
3 |
+
import tflearn
|
4 |
+
import tensorflow
|
5 |
+
import random
|
6 |
+
import json
|
7 |
+
import pickle
|
8 |
+
import gradio as gr
|
9 |
+
from nltk.tokenize import word_tokenize
|
10 |
+
from nltk.stem.lancaster import LancasterStemmer
|
11 |
+
import requests
|
12 |
+
import csv
|
13 |
+
import time
|
14 |
+
import re
|
15 |
+
from bs4 import BeautifulSoup
|
16 |
+
import pandas as pd
|
17 |
+
from selenium import webdriver
|
18 |
+
from selenium.webdriver.chrome.options import Options
|
19 |
+
import chromedriver_autoinstaller
|
20 |
+
import os
|
21 |
+
import logging
|
22 |
+
|
23 |
+
# Ensure necessary NLTK resources are downloaded
|
24 |
+
nltk.download('punkt')
|
25 |
+
|
26 |
+
# Initialize the stemmer
|
27 |
+
stemmer = LancasterStemmer()
|
28 |
+
|
29 |
+
# Load intents.json
|
30 |
+
try:
|
31 |
+
with open("intents.json") as file:
|
32 |
+
data = json.load(file)
|
33 |
+
except FileNotFoundError:
|
34 |
+
raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
|
35 |
+
|
36 |
+
# Load preprocessed data from pickle
|
37 |
+
try:
|
38 |
+
with open("data.pickle", "rb") as f:
|
39 |
+
words, labels, training, output = pickle.load(f)
|
40 |
+
except FileNotFoundError:
|
41 |
+
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
|
42 |
+
|
43 |
+
# Build the model structure
|
44 |
+
net = tflearn.input_data(shape=[None, len(training[0])])
|
45 |
+
net = tflearn.fully_connected(net, 8)
|
46 |
+
net = tflearn.fully_connected(net, 8)
|
47 |
+
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
48 |
+
net = tflearn.regression(net)
|
49 |
+
|
50 |
+
# Load the trained model
|
51 |
+
model = tflearn.DNN(net)
|
52 |
+
try:
|
53 |
+
model.load("MentalHealthChatBotmodel.tflearn")
|
54 |
+
except FileNotFoundError:
|
55 |
+
raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
|
56 |
+
|
57 |
+
# Function to process user input into a bag-of-words format
|
58 |
+
def bag_of_words(s, words):
|
59 |
+
bag = [0 for _ in range(len(words))]
|
60 |
+
s_words = word_tokenize(s)
|
61 |
+
s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
|
62 |
+
for se in s_words:
|
63 |
+
for i, w in enumerate(words):
|
64 |
+
if w == se:
|
65 |
+
bag[i] = 1
|
66 |
+
return np.array(bag)
|
67 |
+
|
68 |
+
# Chat function
|
69 |
+
def chat(message, history):
|
70 |
+
history = history or []
|
71 |
+
message = message.lower()
|
72 |
+
|
73 |
+
try:
|
74 |
+
# Predict the tag
|
75 |
+
results = model.predict([bag_of_words(message, words)])
|
76 |
+
results_index = np.argmax(results)
|
77 |
+
tag = labels[results_index]
|
78 |
+
|
79 |
+
# Match tag with intent and choose a random response
|
80 |
+
for tg in data["intents"]:
|
81 |
+
if tg['tag'] == tag:
|
82 |
+
responses = tg['responses']
|
83 |
+
response = random.choice(responses)
|
84 |
+
break
|
85 |
+
else:
|
86 |
+
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
87 |
+
|
88 |
+
except Exception as e:
|
89 |
+
response = f"An error occurred: {str(e)}"
|
90 |
+
|
91 |
+
history.append((message, response))
|
92 |
+
return history, history
|
93 |
+
|
94 |
+
# Load the pre-trained model (cached for performance)
|
95 |
+
def load_model():
|
96 |
+
return pipeline('sentiment-analysis', model='cardiffnlp/twitter-roberta-base-sentiment')
|
97 |
+
|
98 |
+
sentiment_model = load_model()
|
99 |
+
|
100 |
+
# Define the function to analyze sentiment
|
101 |
+
def analyze_sentiment(user_input):
|
102 |
+
result = sentiment_model(user_input)[0]
|
103 |
+
sentiment = result['label'].lower() # Convert to lowercase for easier comparison
|
104 |
+
|
105 |
+
# Customize messages based on detected sentiment
|
106 |
+
if sentiment == 'negative':
|
107 |
+
return "Mood Detected: Negative π\n\nStay positive! π Remember, tough times don't last, but tough people do!"
|
108 |
+
elif sentiment == 'neutral':
|
109 |
+
return "Mood Detected: Neutral π\n\nIt's good to reflect on steady days. Keep your goals in mind, and stay motivated!"
|
110 |
+
elif sentiment == 'positive':
|
111 |
+
return "Mood Detected: Positive π\n\nYou're on the right track! Keep shining! π"
|
112 |
+
else:
|
113 |
+
return "Mood Detected: Unknown π€\n\nKeep going, you're doing great!"
|
114 |
+
|
115 |
+
# Load pre-trained model and tokenizer
|
116 |
+
@st.cache_resource
|
117 |
+
def load_model():
|
118 |
+
tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
119 |
+
model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
120 |
+
return tokenizer, model
|
121 |
+
|
122 |
+
tokenizer, model = load_model()
|
123 |
+
|
124 |
+
# Set page config as the very first Streamlit command
|
125 |
+
st.set_page_config(page_title="Mental Health & Wellness Assistant", layout="wide")
|
126 |
+
|
127 |
+
# Display header
|
128 |
+
st.title("Mental Health & Wellness Assistant")
|
129 |
+
|
130 |
+
# User input for text (emotion detection)
|
131 |
+
user_input = st.text_area("How are you feeling today?", "Enter your thoughts here...")
|
132 |
+
|
133 |
+
# Model prediction
|
134 |
+
if user_input:
|
135 |
+
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
|
136 |
+
result = pipe(user_input)
|
137 |
+
|
138 |
+
# Extracting the emotion from the model's result
|
139 |
+
emotion = result[0]['label']
|
140 |
+
|
141 |
+
# Display emotion
|
142 |
+
st.write(f"**Emotion Detected:** {emotion}")
|
143 |
+
|
144 |
+
# Provide suggestions based on the detected emotion
|
145 |
+
if emotion == 'joy':
|
146 |
+
st.write("You're feeling happy! Keep up the great mood!")
|
147 |
+
st.write("Useful Resources:")
|
148 |
+
st.markdown("[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
|
149 |
+
st.write("[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
|
150 |
+
st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
|
151 |
+
|
152 |
+
st.write("Relaxation Videos:")
|
153 |
+
st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
|
154 |
+
|
155 |
+
elif emotion == 'anger':
|
156 |
+
st.write("You're feeling angry. It's okay to feel this way. Let's try to calm down.")
|
157 |
+
st.write("Useful Resources:")
|
158 |
+
st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
|
159 |
+
st.write("[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)")
|
160 |
+
st.write("[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
|
161 |
+
|
162 |
+
st.write("Relaxation Videos:")
|
163 |
+
st.markdown("[Watch on YouTube](https://youtu.be/MIc299Flibs)")
|
164 |
+
|
165 |
+
elif emotion == 'fear':
|
166 |
+
st.write("You're feeling fearful. Take a moment to breathe and relax.")
|
167 |
+
st.write("Useful Resources:")
|
168 |
+
st.markdown("[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
|
169 |
+
st.write("[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
|
170 |
+
st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
|
171 |
+
|
172 |
+
st.write("Relaxation Videos:")
|
173 |
+
st.markdown("[Watch on YouTube](https://youtu.be/yGKKz185M5o)")
|
174 |
+
|
175 |
+
elif emotion == 'sadness':
|
176 |
+
st.write("You're feeling sad. It's okay to take a break.")
|
177 |
+
st.write("Useful Resources:")
|
178 |
+
st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
|
179 |
+
st.write("[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
|
180 |
+
|
181 |
+
st.write("Relaxation Videos:")
|
182 |
+
st.markdown("[Watch on YouTube](https://youtu.be/-e-4Kx5px_I)")
|
183 |
+
|
184 |
+
elif emotion == 'surprise':
|
185 |
+
st.write("You're feeling surprised. It's okay to feel neutral!")
|
186 |
+
st.write("Useful Resources:")
|
187 |
+
st.markdown("[Managing Stress](https://www.health.harvard.edu/health-a-to-z)")
|
188 |
+
st.write("[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
|
189 |
+
|
190 |
+
st.write("Relaxation Videos:")
|
191 |
+
st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
|
192 |
+
|
193 |
+
# Chatbot functionality
|
194 |
+
def chatbot_interface():
|
195 |
+
def chat(message, history):
|
196 |
+
history = history or []
|
197 |
+
message = message.lower()
|
198 |
+
|
199 |
+
try:
|
200 |
+
# Predict the tag
|
201 |
+
results = model.predict([bag_of_words(message, words)])
|
202 |
+
results_index = np.argmax(results)
|
203 |
+
tag = labels[results_index]
|
204 |
+
|
205 |
+
# Match tag with intent and choose a random response
|
206 |
+
for tg in data["intents"]:
|
207 |
+
if tg['tag'] == tag:
|
208 |
+
responses = tg['responses']
|
209 |
+
response = random.choice(responses)
|
210 |
+
break
|
211 |
+
else:
|
212 |
+
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
213 |
+
|
214 |
+
except Exception as e:
|
215 |
+
response = f"An error occurred: {str(e)}"
|
216 |
+
|
217 |
+
history.append((message, response))
|
218 |
+
return history, history
|
219 |
+
|
220 |
+
chatbot = gr.Chatbot(label="Chat")
|
221 |
+
demo = gr.Interface(
|
222 |
+
chat,
|
223 |
+
[gr.Textbox(lines=1, label="Message"), "state"],
|
224 |
+
[chatbot, "state"],
|
225 |
+
allow_flagging="never",
|
226 |
+
title="Mental Health Chatbot",
|
227 |
+
description="Your personal mental health assistant.",
|
228 |
+
)
|
229 |
+
return demo
|
230 |
+
|
231 |
+
# Launch the interfaces
|
232 |
+
if __name__ == "__main__":
|
233 |
+
# Create a tabbed interface for different features
|
234 |
+
tabs = [
|
235 |
+
gr.TabItem("Sentiment Analysis", chatbot_ui()),
|
236 |
+
gr.TabItem("Emotion Detection", chatbot_ui()),
|
237 |
+
gr.TabItem("Google Places Search", chatbot_ui()),
|
238 |
+
]
|
239 |
+
|
240 |
+
with gr.Blocks() as demo:
|
241 |
+
gr.Tabs(tabs)
|
242 |
+
|
243 |
+
demo.launch()
|