Spaces:
Sleeping
Sleeping
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 TensorFlow GPU warnings | |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" | |
# Download necessary NLTK resources | |
nltk.download("punkt") | |
# Initialize Lancaster Stemmer | |
stemmer = LancasterStemmer() | |
# Load intents.json for 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 TFlearn Chatbot 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() | |
# Bag of Words Function | |
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 Function | |
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": message}) | |
history.append({"role": "assistant", "content": response}) | |
return history, response | |
# Emotion Detection | |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
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 | |
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): | |
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_map = { | |
"π Joy": [ | |
{"Title": "Mindful Meditation π§", "Link": "https://www.helpguide.org/meditation"}, | |
{"Title": "Learn a New Skill β¨", "Link": "https://www.skillshare.com/"}, | |
], | |
"π’ Sadness": [ | |
{"Title": "Talk to a Professional π¬", "Link": "https://www.betterhelp.com/"}, | |
{"Title": "Mental Health Toolkit π οΈ", "Link": "https://www.psychologytoday.com/"}, | |
], | |
"π Anger": [ | |
{"Title": "Anger Management Tips π₯", "Link": "https://www.mentalhealth.org.uk"}, | |
{"Title": "Stress Relieving Exercises πΏ", "Link": "https://www.calm.com/"}, | |
], | |
} | |
return suggestions_map.get(emotion, [{"Title": "General Wellness Resources π", "Link": "https://www.helpguide.org/wellness"}]) | |
# Nearby Professionals Function | |
def search_nearby_professionals(location, query): | |
"""Returns a list of professionals as a list of lists for compatibility with DataFrame.""" | |
if location and query: | |
results = [ | |
{"Name": "Wellness Center", "Address": "123 Wellness Way"}, | |
{"Name": "Mental Health Clinic", "Address": "456 Recovery Road"}, | |
{"Name": "Therapy Hub", "Address": "789 Peace Avenue"}, | |
] | |
return [[item["Name"], item["Address"]] for item in results] | |
return [] | |
# Main App Logic | |
def well_being_app(user_input, location, query, history): | |
history, _ = chatbot_response(user_input, history) | |
emotion = detect_emotion(user_input) | |
sentiment = analyze_sentiment(user_input) | |
emotion_name = emotion.split(": ")[-1] | |
suggestions = generate_suggestions(emotion_name) | |
suggestions_df = pd.DataFrame(suggestions) | |
professionals = search_nearby_professionals(location, query) | |
return history, sentiment, emotion, suggestions_df, professionals | |
# Gradio Interface | |
with gr.Blocks() as interface: | |
gr.Markdown("## π± Well-being Companion") | |
gr.Markdown("> Empowering Your Mental Health! π") | |
with gr.Row(): | |
user_input = gr.Textbox(label="Your Message") | |
location_input = gr.Textbox(label="Location") | |
query_input = gr.Textbox(label="Search Query") | |
submit_button = gr.Button("Submit") | |
chatbot_output = gr.Chatbot(label="Chatbot Interaction", type="messages", value=[]) | |
sentiment_output = gr.Textbox(label="Sentiment Analysis") | |
emotion_output = gr.Textbox(label="Emotion Detected") | |
suggestions_output = gr.DataFrame(label="Suggestions", value=[], headers=["Title", "Link"]) | |
nearby_professionals_output = gr.DataFrame(label="Nearby Professionals", headers=["Name", "Address"]) | |
submit_button.click( | |
well_being_app, | |
inputs=[user_input, location_input, query_input, chatbot_output], | |
outputs=[ | |
chatbot_output, | |
sentiment_output, | |
emotion_output, | |
suggestions_output, | |
nearby_professionals_output, | |
], | |
) | |
interface.launch() |