Spaces:
Sleeping
Sleeping
Update app.py
#2
by
DreamStream-1
- opened
app.py
CHANGED
@@ -8,6 +8,17 @@ import pickle
|
|
8 |
import gradio as gr
|
9 |
from nltk.tokenize import word_tokenize
|
10 |
from nltk.stem.lancaster import LancasterStemmer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
# Ensure necessary NLTK resources are downloaded
|
13 |
nltk.download('punkt')
|
@@ -80,16 +91,153 @@ def chat(message, history):
|
|
80 |
history.append((message, response))
|
81 |
return history, history
|
82 |
|
83 |
-
#
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
)
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
demo.launch()
|
|
|
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')
|
|
|
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()
|