import os import gradio as gr import nltk import numpy as np import tflearn import random import json import pickle from nltk.tokenize import word_tokenize from nltk.stem.lancaster import LancasterStemmer from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline import pandas as pd import torch # Disable GPU usage for TensorFlow os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Download required NLTK resources nltk.download('punkt') # Initialize Lancaster Stemmer stemmer = LancasterStemmer() # Load intents.json for the chatbot with open("intents.json") as file: intents_data = json.load(file) # Load tokenized training data with open("data.pickle", "rb") as f: words, labels, training, output = pickle.load(f) # Build the TFlearn model def build_chatbot_model(): 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) model = tflearn.DNN(net) model.load("MentalHealthChatBotmodel.tflearn") return model chatbot_model = build_chatbot_model() # Function: Bag of words 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.isalnum()] for se in s_words: for i, w in enumerate(words): if w == se: bag[i] = 1 return np.array(bag) # Chatbot response generator def chatbot_response(message, history): history = history or [] try: result = chatbot_model.predict([bag_of_words(message, words)]) idx = np.argmax(result) tag = labels[idx] response = "I'm not sure how to respond to that 🤔" for intent in intents_data["intents"]: if intent["tag"] == tag: response = random.choice(intent["responses"]) break except Exception as e: response = f"Error generating response: {str(e)} 💥" history.append({"role": "user", "content": f"💬 {message}"}) history.append({"role": "assistant", "content": f"🤖 {response}"}) return history, response # Hugging Face transformers model for emotion detection emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base") emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base") # Detect emotion def detect_emotion(user_input): pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer) try: result = pipe(user_input) emotion = result[0]["label"] emotion_map = { "joy": "😊 Joy", "anger": "😠 Anger", "sadness": "😢 Sadness", "fear": "😨 Fear", "surprise": "😲 Surprise", "neutral": "😐 Neutral", } return emotion_map.get(emotion, "Unknown Emotion 🤔") except Exception as e: return f"Error detecting emotion: {str(e)} 💥" # Sentiment analysis using Hugging Face sentiment_tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") def analyze_sentiment(user_input): """Analyze sentiment of user input.""" inputs = sentiment_tokenizer(user_input, return_tensors="pt") try: with torch.no_grad(): outputs = sentiment_model(**inputs) sentiment = torch.argmax(outputs.logits, dim=1).item() sentiment_map = ["Negative 😔", "Neutral 😐", "Positive 😊"] return sentiment_map[sentiment] except Exception as e: return f"Error in sentiment analysis: {str(e)} 💥" # Suggestions based on emotion def generate_suggestions(emotion): suggestions = { "😊 Joy": [ {"Title": "Mindful Meditation 🧘‍♂️", "Link": "https://www.helpguide.org/meditation"}, {"Title": "Explore a new skill 🚀", "Link": "https://www.skillshare.com/"}, ], "😢 Sadness": [ {"Title": "Improve mental resilience ✨", "Link": "https://www.psychologytoday.com/"}, {"Title": "Reach out to a therapist 💬", "Link": "https://www.betterhelp.com/"}, ], "😠 Anger": [ {"Title": "Anger Management Guide 🔥", "Link": "https://www.mentalhealth.org.uk/"}, {"Title": "Calming Exercises 🌿", "Link": "https://www.calm.com/"}, ], } return suggestions.get(emotion, [{"Title": "General Wellness Resources 🌈", "Link": "https://www.wellness.com/"}]) # Main App Function def well_being_app(user_input, history): """Main function for chatbot, emotion detection, sentiment analysis, and suggestions.""" # Chatbot response history, chatbot_reply = chatbot_response(user_input, history) # Emotion detection emotion = detect_emotion(user_input) # Sentiment analysis sentiment = analyze_sentiment(user_input) # Generating suggestions detected_emotion = emotion.split(": ")[-1] suggestions = generate_suggestions(detected_emotion) suggestions_df = pd.DataFrame(suggestions) return history, sentiment, emotion, suggestions_df # Custom CSS for Beautification custom_css = """ body { background: linear-gradient(135deg, #8e44ad, #3498db); font-family: 'Arial', sans-serif; color: white; text-align: center; } #component-0 span { color: #ffcccc; } button { background-color: #1abc9c; border: none; color: white; padding: 12px 24px; text-align: center; font-size: 16px; border-radius: 8px; cursor: pointer; } button:hover { background-color: #16a085; } """ # Gradio UI with gr.Blocks(css=custom_css) as interface: gr.Markdown("# 🌸 **Mental Health & Well-Being Assistant**") gr.Markdown("### Powered by NLP & AI") with gr.Row(): user_input = gr.Textbox(lines=2, placeholder="How can I support you today?", label="Your Input") with gr.Row(): submit_button = gr.Button("Submit", elem_id="submit") with gr.Row(): chatbot_out = gr.Chatbot(label="Chat History") sentiment_out = gr.Textbox(label="Sentiment") emotion_out = gr.Textbox(label="Detected Emotion") with gr.Row(): suggestions_out = gr.DataFrame(label="Suggestions", headers=["Title", "Link"]) submit_button.click( well_being_app, inputs=[user_input, chatbot_out], outputs=[chatbot_out, sentiment_out, emotion_out, suggestions_out], ) # Launch App interface.launch()