Spaces:
Sleeping
Sleeping
File size: 9,232 Bytes
8dc6340 7f5a352 8dc6340 42dd9d9 8dc6340 2c7367f f9f5c08 3aa1ab2 385ba0f a372e79 f9f5c08 a372e79 47fbf8a 8dc6340 47fbf8a a372e79 b102079 47fbf8a a372e79 3fa17a3 47fbf8a 8dc6340 47fbf8a 8dc6340 47fbf8a f9f5c08 8dc6340 47fbf8a 8dc6340 3fa17a3 f9f5c08 47fbf8a 8dc6340 47fbf8a 42dd9d9 47fbf8a 42dd9d9 47fbf8a 42dd9d9 47fbf8a 8dc6340 3aa1ab2 8dc6340 3aa1ab2 47fbf8a |
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 nltk
import numpy as np
import tflearn
import tensorflow
import random
import json
import pickle
import gradio as gr
from nltk.tokenize import word_tokenize
from nltk.stem.lancaster import LancasterStemmer
import requests
import csv
import time
import re
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_autoinstaller
import os
import logging
# 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
# Load the pre-trained model (cached for performance)
def load_model():
return pipeline('sentiment-analysis', model='cardiffnlp/twitter-roberta-base-sentiment')
sentiment_model = load_model()
# Define the function to analyze sentiment
def analyze_sentiment(user_input):
result = sentiment_model(user_input)[0]
sentiment = result['label'].lower() # Convert to lowercase for easier comparison
# Customize messages based on detected sentiment
if sentiment == 'negative':
return "Mood Detected: Negative π\n\nStay positive! π Remember, tough times don't last, but tough people do!"
elif sentiment == 'neutral':
return "Mood Detected: Neutral π\n\nIt's good to reflect on steady days. Keep your goals in mind, and stay motivated!"
elif sentiment == 'positive':
return "Mood Detected: Positive π\n\nYou're on the right track! Keep shining! π"
else:
return "Mood Detected: Unknown π€\n\nKeep going, you're doing great!"
# Load pre-trained model and tokenizer
@st.cache_resource
def load_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, model = load_model()
# Set page config as the very first Streamlit command
st.set_page_config(page_title="Mental Health & Wellness Assistant", layout="wide")
# Display header
st.title("Mental Health & Wellness Assistant")
# User input for text (emotion detection)
user_input = st.text_area("How are you feeling today?", "Enter your thoughts here...")
# Model prediction
if user_input:
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
result = pipe(user_input)
# Extracting the emotion from the model's result
emotion = result[0]['label']
# Display emotion
st.write(f"**Emotion Detected:** {emotion}")
# Provide suggestions based on the detected emotion
if emotion == 'joy':
st.write("You're feeling happy! Keep up the great mood!")
st.write("Useful Resources:")
st.markdown("[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
st.write("[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
st.write("Relaxation Videos:")
st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
elif emotion == 'anger':
st.write("You're feeling angry. It's okay to feel this way. Let's try to calm down.")
st.write("Useful Resources:")
st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
st.write("[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)")
st.write("[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
st.write("Relaxation Videos:")
st.markdown("[Watch on YouTube](https://youtu.be/MIc299Flibs)")
elif emotion == 'fear':
st.write("You're feeling fearful. Take a moment to breathe and relax.")
st.write("Useful Resources:")
st.markdown("[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
st.write("[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
st.write("Relaxation Videos:")
st.markdown("[Watch on YouTube](https://youtu.be/yGKKz185M5o)")
elif emotion == 'sadness':
st.write("You're feeling sad. It's okay to take a break.")
st.write("Useful Resources:")
st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
st.write("[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
st.write("Relaxation Videos:")
st.markdown("[Watch on YouTube](https://youtu.be/-e-4Kx5px_I)")
elif emotion == 'surprise':
st.write("You're feeling surprised. It's okay to feel neutral!")
st.write("Useful Resources:")
st.markdown("[Managing Stress](https://www.health.harvard.edu/health-a-to-z)")
st.write("[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
st.write("Relaxation Videos:")
st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
# Chatbot functionality
def chatbot_interface():
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
chatbot = gr.Chatbot(label="Chat")
demo = gr.Interface(
chat,
[gr.Textbox(lines=1, label="Message"), "state"],
[chatbot, "state"],
allow_flagging="never",
title="Mental Health Chatbot",
description="Your personal mental health assistant.",
)
return demo
# Launch the interfaces
if __name__ == "__main__":
# Create a tabbed interface for different features
tabs = [
gr.TabItem("Sentiment Analysis", chatbot_ui()),
gr.TabItem("Emotion Detection", chatbot_ui()),
gr.TabItem("Google Places Search", chatbot_ui()),
]
with gr.Blocks() as demo:
gr.Tabs(tabs)
demo.launch()
|