Testing / app.py
DreamStream-1's picture
Update app.py
5b95047 verified
raw
history blame
11.3 kB
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, response
# 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 and resources in table
def detect_emotion(user_input):
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
result = pipe(user_input)
emotion = result[0]['label']
# Define emotion-specific message and resources
if emotion == 'joy':
emotion_msg = "You're feeling happy! Keep up the great mood!"
resources = [
{"subject": "Relaxation Techniques", "heading": "Mindful Breathing Meditation", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation", "video_url": "https://youtu.be/m1vaUGtyo-A"},
{"subject": "Dealing with Stress", "heading": "Tips for Dealing with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/m1vaUGtyo-A"},
{"subject": "Emotional Wellness Toolkit", "heading": "Emotional Wellness Resources", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "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", "heading": "Managing Emotions", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "https://youtu.be/MIc299Flibs"},
{"subject": "Stress Management Tips", "heading": "Managing Stress Effectively", "link": "https://www.health.harvard.edu/health-a-to-z", "video_url": "https://youtu.be/MIc299Flibs"},
{"subject": "Dealing with Anger", "heading": "Strategies to Calm Anger", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/MIc299Flibs"}
]
elif emotion == 'fear':
emotion_msg = "You're feeling fearful. Take a moment to breathe and relax."
resources = [
{"subject": "Mindfulness Practices", "heading": "Breathing Techniques", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation", "video_url": "https://youtu.be/yGKKz185M5o"},
{"subject": "Coping with Anxiety", "heading": "Overcoming Fear", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/yGKKz185M5o"},
{"subject": "Emotional Wellness Toolkit", "heading": "Calming Your Mind", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "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", "heading": "Restoring Your Emotional Health", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit", "video_url": "https://youtu.be/-e-4Kx5px_I"},
{"subject": "Dealing with Anxiety", "heading": "Coping Strategies for Stress", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "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", "heading": "Relaxation Tips", "link": "https://www.health.harvard.edu/health-a-to-z", "video_url": "https://youtu.be/m1vaUGtyo-A"},
{"subject": "Coping Strategies", "heading": "Dealing with Unexpected Events", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety", "video_url": "https://youtu.be/m1vaUGtyo-A"}
]
else:
emotion_msg = "Could not detect emotion."
resources = []
# Create a DataFrame for resources to display in table format
resource_df = pd.DataFrame(resources)
return emotion_msg, resource_df
# Google Geocoding API setup to convert city name to latitude/longitude
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json"
def get_lat_lon(location, api_key):
params = {
"address": location,
"key": api_key
}
response = requests.get(geocode_url, params=params)
if response.status_code == 200:
result = response.json()
if result['status'] == 'OK':
# Return the first result's latitude and longitude
location = result['results'][0]['geometry']['location']
return location['lat'], location['lng']
return None, None
# Google Places API setup for wellness professionals
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
api_key = os.getenv("GOOGLE_API_KEY") # Use environment variable for security
# Function to get places data using Google Places API
def get_places_data(query, location, radius, api_key, next_page_token=None):
params = {
'query': query,
'location': location,
'radius': radius,
'key': api_key
}
if next_page_token:
params['pagetoken'] = next_page_token
response = requests.get(url, params=params)
return response.json()
# Function to fetch wellness professionals
def get_wellness_professionals(location, api_key):
lat, lon = get_lat_lon(location, api_key)
if lat and lon:
places = get_places_data("wellness professional", f"{lat},{lon}", 10000, api_key)
if places and 'results' in places:
professionals = []
for place in places['results']:
name = place.get("name", "No name available")
rating = place.get("rating", "No rating available")
address = place.get("formatted_address", "No address available")
professionals.append({
"Name": name,
"Rating": rating,
"Address": address
})
professionals_df = pd.DataFrame(professionals)
return professionals_df
else:
return "No wellness professionals found nearby."
else:
return "Location not found. Please check the location."
# Gradio interface function to handle actions and outputs
def interface_function(message, action, location, history):
history = history or []
if action == "Chat":
# Use chat function if 'Chat' button is clicked
history, response = chat(message, history)
elif action == "Detect Emotion":
# Use emotion detection if 'Detect Emotion' button is clicked
emotion_msg, resource_df = detect_emotion(message)
response = emotion_msg
# Return the resource DataFrame as a table
return history, response, resource_df
elif action == "Wellness Resources":
# Use location to get wellness professionals if 'Wellness Resources' is clicked
if not location.strip():
response = "Please enter a valid location."
else:
professionals_df = get_wellness_professionals(location, api_key)
if isinstance(professionals_df, pd.DataFrame):
response = "Found wellness professionals nearby:"
return history, response, professionals_df
else:
response = professionals_df # If error message is returned
return history, response, None
return history, "Invalid action", None
# Gradio Interface with table outputs for emotion and wellness professionals
iface = gr.Interface(
fn=interface_function,
inputs=["text", "radio", "text", "state"], # Include state in the inputs
outputs=["text", "dataframe", "state"], # Add state to the outputs
live=True,
allow_flagging="never"
)
iface.launch(share=True)