Spaces:
Sleeping
Sleeping
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 | |
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() | |