Spaces:
Sleeping
Sleeping
import json | |
import pickle | |
import random | |
import nltk | |
import numpy as np | |
import tflearn | |
import gradio as gr | |
import requests | |
import torch | |
import pandas as pd | |
from bs4 import BeautifulSoup | |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline | |
from nltk.tokenize import word_tokenize | |
from nltk.stem.lancaster import LancasterStemmer | |
import os | |
# 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 | |
# Sentiment analysis setup | |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
# Emotion detection setup | |
def load_emotion_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_emotion, model_emotion = load_emotion_model() | |
# Emotion detection function with suggestions in plain English | |
def detect_emotion(user_input): | |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion) | |
result = pipe(user_input) | |
emotion = result[0]['label'] | |
# Provide suggestions based on the detected emotion | |
if emotion == 'joy': | |
emotion_msg = "You're feeling happy! Keep up the great mood!" | |
resources = [ | |
{"subject": "Relaxation Techniques", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"}, | |
{"subject": "Dealing with Stress", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}, | |
{"subject": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"} | |
] | |
video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A" | |
elif emotion == 'anger': | |
emotion_msg = "You're feeling angry. It's okay to feel this way. Let's try to calm down." | |
resources = [ | |
{"subject": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"}, | |
{"subject": "Stress Management Tips", "link": "https://www.health.harvard.edu/health-a-to-z"}, | |
{"subject": "Dealing with Anger", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"} | |
] | |
video_link = "Watch on YouTube: https://youtu.be/MIc299Flibs" | |
elif emotion == 'fear': | |
emotion_msg = "You're feeling fearful. Take a moment to breathe and relax." | |
resources = [ | |
{"subject": "Mindfulness Practices", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"}, | |
{"subject": "Coping with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}, | |
{"subject": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"} | |
] | |
video_link = "Watch on YouTube: https://youtu.be/yGKKz185M5o" | |
elif emotion == 'sadness': | |
emotion_msg = "You're feeling sad. It's okay to take a break." | |
resources = [ | |
{"subject": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"}, | |
{"subject": "Dealing with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"} | |
] | |
video_link = "Watch on YouTube: https://youtu.be/-e-4Kx5px_I" | |
elif emotion == 'surprise': | |
emotion_msg = "You're feeling surprised. It's okay to feel neutral!" | |
resources = [ | |
{"subject": "Managing Stress", "link": "https://www.health.harvard.edu/health-a-to-z"}, | |
{"subject": "Coping Strategies", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"} | |
] | |
video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A" | |
else: | |
emotion_msg = "Could not detect emotion." | |
resources = [] | |
video_link = "" | |
return emotion_msg, resources, video_link | |
# Create the interface with multiple buttons | |
def interface_function(message, action, history): | |
history = history or [] | |
if action == "Chat": | |
# Use chat function if 'Chat' button is clicked | |
history, _ = chat(message, history) | |
return history, history | |
elif action == "Detect Emotion": | |
# Detect emotion if 'Detect Emotion' button is clicked | |
emotion_msg, resources, video_link = detect_emotion(message) | |
result = f"Emotion: {emotion_msg}\nResources:\n" | |
for res in resources: | |
result += f"- {res['subject']}: {res['link']}\n" | |
result += f"Suggested Video: {video_link}" | |
return result, history | |
elif action == "Wellness Resources": | |
# Return wellness resources if 'Wellness Resources' button is clicked | |
result = "Here are some wellness resources you can explore:\n" | |
result += "1. Mental Health Support: https://www.helpguide.org/mental-health/mental-health-support.htm\n" | |
result += "2. Meditation Guide: https://www.headspace.com/meditation\n" | |
return result, history | |
# Gradio interface with multiple buttons | |
iface = gr.Interface( | |
fn=interface_function, | |
inputs=[gr.Textbox(label="Enter message"), | |
gr.Radio(["Chat", "Detect Emotion", "Wellness Resources"], label="Choose Action"), | |
gr.State()], | |
outputs=[gr.Textbox(label="Response"), gr.State()], | |
allow_flagging="never", | |
live=True | |
) | |
iface.launch(share=True) | |