Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
from transformers import pipeline | |
import requests | |
import csv | |
import time | |
import re | |
from bs4 import BeautifulSoup | |
import pandas as pd | |
import chromedriver_autoinstaller | |
import os | |
import nltk | |
import numpy as np | |
import torch | |
import torch.nn as nn | |
import torch.optim as optim | |
import tflearn | |
import tensorflow as tf | |
import json | |
import pickle | |
import random | |
# Ensure necessary NLTK resources are downloaded | |
nltk.download('punkt') | |
# Import LancasterStemmer from nltk.stem | |
from nltk.stem import LancasterStemmer | |
# 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 = nltk.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 | |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
sentiment_pipeline = pipeline("sentiment-analysis") | |
def predict_sentiment(text): | |
result = sentiment_pipeline(text) | |
return result[0]['label'] | |
# Emotion detection | |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
emotion_pipeline = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion) | |
def predict_emotion(text): | |
result = emotion_pipeline(text) | |
return result[0]['label'] | |
# Fetching nearby health professionals | |
google_places_url = "https://maps.googleapis.com/maps/api/place/textsearch/json" | |
google_geocoding_url = "https://maps.googleapis.com/maps/api/geocode/json" | |
def get_places_data(query, location, radius, api_key): | |
params = { | |
"query": query, | |
"location": location, | |
"radius": radius, | |
"key": api_key | |
} | |
response = requests.get(google_places_url, params=params) | |
return response.json() | |
def get_place_details(place_id, api_key): | |
details_url = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&fields=name,rating,formatted_phone_number&key={api_key}" | |
response = requests.get(details_url) | |
return response.json() | |
def fetch_nearby_health_professionals(location): | |
api_key = "GOOGLE_API_KEY" # Replace with your actual Google API key | |
query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist OR nutritionist OR wellness doctor OR holistic practitioner OR integrative medicine OR chiropractor OR naturopath" | |
radius = 50000 # 50 km radius | |
response = get_places_data(query, location, radius, api_key) | |
results = response.get('results', []) | |
data = [] | |
for place in results: | |
place_id = place['place_id'] | |
place_details = get_place_details(place_id, api_key) | |
name = place_details.get('result', {}).get('name', 'N/A') | |
rating = place_details.get('result', {}).get('rating', 'N/A') | |
phone_number = place_details.get('result', {}).get('formatted_phone_number', 'N/A') | |
data.append([name, rating, phone_number]) | |
return pd.DataFrame(data, columns=['Name', 'Rating', 'Phone Number']) | |
# Gradio interface for recommendations | |
def generate_recommendations(emotion): | |
if emotion == 'joy': | |
return [ | |
{"title": "Mindful Breathing Meditation", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"}, | |
{"title": "Dealing with Stress", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}, | |
{"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"} | |
] | |
elif emotion == 'anger': | |
return [ | |
{"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"}, | |
{"title": "Stress Management Tips", "link": "https://www.health.harvard.edu/health-a-to-z"}, | |
{"title": "Dealing with Anger", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"} | |
] | |
elif emotion == 'fear': | |
return [ | |
{"title": "Mindfulness Practices", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"}, | |
{"title": "Coping with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}, | |
{"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"} | |
] | |
elif emotion == 'sadness': | |
return [ | |
{"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"}, | |
{"title": "Dealing with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"} | |
] | |
elif emotion == 'surprise': | |
return [ | |
{"title": "Managing Stress", "link": "https://www.health.harvard.edu/health-a-to-z"}, | |
{"title": "Coping Strategies", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"} | |
] | |
else: | |
return [] | |
def recommendations_interface(emotion): | |
recs = generate_recommendations(emotion) | |
html = "<ul>" | |
for rec in recs: | |
html += f"<li><a href='{rec['link']}'>{rec['title']}</a></li>" | |
html += "</ul>" | |
return html | |
# Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("# Well-Being Assistant") | |
# User input for text (emotion detection) | |
user_input_emotion = gr.Textbox(lines=1, label="How are you feeling today?") | |
submit_emotion = gr.Button("Submit") | |
# Model prediction for emotion detection | |
def predict_emotion(text): | |
result = emotion_pipeline(text) | |
return result[0]['label'] | |
# Show suggestions based on the detected emotion | |
def show_suggestions(emotion): | |
if emotion == 'joy': | |
return "You're feeling happy! Keep up the great mood!" | |
elif emotion == 'anger': | |
return "You're feeling angry. It's okay to feel this way. Let's try to calm down." | |
elif emotion == 'fear': | |
return "You're feeling fearful. Take a moment to breathe and relax." | |
elif emotion == 'sadness': | |
return "You're feeling sad. It's okay to take a break." | |
elif emotion == 'surprise': | |
return "You're feeling surprised. It's okay to feel neutral!" | |
emotion_output = gr.Textbox(label="Emotion Detected") | |
submit_emotion.click(predict_emotion, inputs=user_input_emotion, outputs=emotion_output) | |
# Button for summary | |
def show_summary(emotion): | |
return f"Emotion Detected: {emotion}" | |
summary_button = gr.Button("Show Summary") | |
summary_output = gr.Textbox(label="Summary") | |
summary_button.click(show_summary, inputs=emotion_output, outputs=summary_output) | |
# Chatbot functionality | |
chatbot = gr.Chatbot(label="Chat") | |
message_input = gr.Textbox(lines=1, label="Message") | |
submit_chat = gr.Button("Send") | |
def chat_with_sentiment_and_emotion(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)) | |
# Sentiment analysis | |
sentiment_result = predict_sentiment(message) | |
emotion_result = predict_emotion(message) | |
return history, history, sentiment_result, emotion_result | |
submit_chat.click(chat_with_sentiment_and_emotion, inputs=[message_input, gr.State()], outputs=[chatbot, gr.State(), gr.Textbox(), gr.Textbox()]) | |
# Location input for fetching nearby health professionals | |
location_input = gr.Textbox(lines=1, label="Enter your location (plain English):") | |
submit_location = gr.Button("Find Nearby Health Professionals") | |
# Fetch and display nearby health professionals | |
def fetch_nearby_health_professionals(location): | |
df = fetch_nearby_health_professionals(location) | |
return df | |
nearby_health_professionals_table = gr.Dataframe(headers=["Name", "Rating", "Phone Number"]) | |
submit_location.click(fetch_nearby_health_professionals, inputs=location_input, outputs=nearby_health_professionals_table) | |
# Article and video recommendations | |
article_video_recs = gr.HTML("<h2>Article and Video Recommendations</h2><p>No recommendations yet.</p>") | |
recommendations_ui = gr.Interface( | |
fn=recommendations_interface, | |
inputs="text", | |
outputs="html", | |
title="Article and Video Recommendations", | |
description="Get personalized recommendations based on your mood." | |
) | |
def update_recommendations(emotion): | |
recs_html = recommendations_interface(emotion) | |
article_video_recs.update(recs_html) | |
emotion_output.change(update_recommendations, inputs=emotion_output, outputs=article_video_recs) | |
# Launch Gradio interface | |
demo.launch() | |