Testing / app.py
DreamStream-1's picture
Update app.py
936af04 verified
raw
history blame
7.4 kB
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
import json
import pickle
import random
import pandas as pd
import requests
import nltk
from nltk.stem import LancasterStemmer
import numpy as np
import tensorflow as tf
from bs4 import BeautifulSoup
# Download necessary NLTK resources
nltk.download('punkt')
# Initialize the stemmer
stemmer = LancasterStemmer()
# Load intents.json
with open("intents.json") as file:
data = json.load(file)
# Load preprocessed data from pickle
with open("data.pickle", "rb") as f:
words, labels, training, output = pickle.load(f)
# 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)
model.load("MentalHealthChatBotmodel.tflearn")
# 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")
# 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)
# 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)
# Function to generate recommendations based on emotion
def generate_recommendations(emotion):
if emotion == 'joy':
return [
{"title": "Mindful Breathing Meditation", "link": "https://www.example.com/joy"},
{"title": "Dealing with Stress", "link": "https://www.example.com/stress"},
{"title": "Emotional Wellness Toolkit", "link": "https://www.example.com/wellness"}
]
elif emotion == 'anger':
return [
{"title": "Anger Management Techniques", "link": "https://www.example.com/anger"},
{"title": "Stress Management Tips", "link": "https://www.example.com/stress"},
{"title": "Dealing with Anger", "link": "https://www.example.com/dealing_with_anger"}
]
# Add more cases for other emotions
else:
return []
# Function to fetch nearby health professionals
def fetch_nearby_health_professionals(location):
# Placeholder for fetching nearby health professionals
# Actual implementation depends on the API used and should replace the placeholder data
return pd.DataFrame([
{'Name': 'Dr. Jane Smith', 'Address': '123 Wellness St.', 'Phone': '555-1234'},
{'Name': 'Dr. John Doe', 'Address': '456 Health Rd.', 'Phone': '555-5678'}
])
# Function to detect emotion and provide suggestions
def detect_emotion_and_suggest(text):
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
result = pipe(text)
emotion = result[0]['label']
# Prepare suggestions based on the detected emotion
suggestions = ""
relaxation_videos = ""
if emotion == 'joy':
suggestions = "You're feeling happy! Keep up the great mood!\n\nUseful Resources:\n- Relaxation Techniques: [Link](https://www.example.com/joy)\n- Dealing with Stress: [Link](https://www.example.com/stress)\n- Emotional Wellness Toolkit: [Link](https://www.example.com/wellness)"
relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/m1vaUGtyo-A)"
elif emotion == 'anger':
suggestions = "You're feeling angry. It's okay to feel this way. Let's try to calm down.\n\nUseful Resources:\n- Emotional Wellness Toolkit: [Link](https://www.example.com/anger)\n- Stress Management Tips: [Link](https://www.example.com/stress)\n- Dealing with Anger: [Link](https://www.example.com/dealing_with_anger)"
relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/MIc299Flibs)"
elif emotion == 'fear':
suggestions = "You're feeling fearful. Take a moment to breathe and relax.\n\nUseful Resources:\n- Mindfulness Practices: [Link](https://www.example.com/fear)\n- Coping with Anxiety: [Link](https://www.example.com/anxiety)\n- Emotional Wellness Toolkit: [Link](https://www.example.com/wellness)"
relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/yGKKz185M5o)"
elif emotion == 'sadness':
suggestions = "You're feeling sad. It's okay to take a break.\n\nUseful Resources:\n- Emotional Wellness Toolkit: [Link](https://www.example.com/sadness)\n- Dealing with Anxiety: [Link](https://www.example.com/anxiety)"
relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/-e-4Kx5px_I)"
elif emotion == 'surprise':
suggestions = "You're feeling surprised. It's okay to feel neutral!\n\nUseful Resources:\n- Managing Stress: [Link](https://www.example.com/surprise)\n- Coping Strategies: [Link](https://www.example.com/coping)"
relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/m1vaUGtyo-A)"
return emotion, suggestions, relaxation_videos
# Gradio interface for emotion detection and suggestions
iface = gr.Interface(
fn=detect_emotion_and_suggest,
inputs="text",
outputs=[
"text", # For displaying detected emotion
"markdown", # For displaying suggestions
"markdown", # For displaying relaxation videos
],
title="Emotion Detection and Well-Being Suggestions",
description="Enter your thoughts below to detect your current emotion and receive personalized well-being suggestions.",
)
# Function to show a summary of the detected emotion and suggestions
def show_summary(emotion, suggestions):
return f"**Emotion Detected:** {emotion}\n{suggestions}"
# Gradio interface for showing summary
summary_iface = gr.Interface(
fn=show_summary,
inputs=[
"text", # For detected emotion
"text", # For suggestions
],
outputs="markdown",
title="Summary of Emotion and Suggestions",
description="Click the button to see a summary of your detected emotion and the suggested well-being resources.",
)
# Function to fetch and display nearby health professionals
def fetch_and_display_health_professionals(location):
df = fetch_nearby_health_professionals(location)
return df
# Gradio interface for fetching nearby health professionals
health_professionals_iface = gr.Interface(
fn=fetch_and_display_health_professionals,
inputs="text",
outputs="dataframe",
title="Find Nearby Health Professionals",
description="Enter your location to find nearby health professionals.",
)
# Launch the Gradio interfaces
iface.launch()
summary_iface.launch()
health_professionals_iface.launch()