Testing / app.py
DreamStream-1's picture
Update app.py
37c8a73 verified
raw
history blame
8.75 kB
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 googlemaps
import folium
import pandas as pd
import torch
# Disable GPU usage for TensorFlow
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# Ensure necessary NLTK resources are downloaded
nltk.download('punkt')
# Initialize the stemmer
stemmer = LancasterStemmer()
# Load intents.json for Well-Being Chatbot
try:
with open("intents.json") as file:
data = json.load(file)
except FileNotFoundError:
print("Error: 'intents.json' file not found.")
# Load preprocessed data for Well-Being Chatbot
try:
with open("data.pickle", "rb") as f:
words, labels, training, output = pickle.load(f)
except FileNotFoundError:
print("Error: 'data.pickle' file not found.")
# Build the model structure for Well-Being Chatbot
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 IOError:
print("Error: Model file not found or corrupted.")
# Function to process user input into a bag-of-words format for Chatbot
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 for Well-Being Chatbot
def chatbot(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)}"
# Convert the new message and response to the 'messages' format
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response})
return history, history
# Sentiment Analysis using Hugging Face model
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
def analyze_sentiment(user_input):
try:
inputs = tokenizer(user_input, return_tensors="pt")
with torch.no_grad():
outputs = model_sentiment(**inputs)
predicted_class = torch.argmax(outputs.logits, dim=1).item()
sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
return f"Predicted Sentiment: {sentiment}"
except Exception as e:
return f"Sentiment analysis error: {str(e)}"
# Emotion Detection using Hugging Face model
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
def detect_emotion(user_input):
try:
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
result = pipe(user_input)
emotion = result[0]['label']
return f"Emotion Detected: {emotion}"
except Exception as e:
return f"Emotion detection error: {str(e)}"
# Initialize Google Maps API client securely
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
# Function to search for health professionals
def search_health_professionals(query, location, radius=10000):
try:
places_result = gmaps.places_nearby(location, radius=radius, type='doctor', keyword=query)
if 'results' in places_result:
return places_result['results']
else:
return []
except Exception as e:
print(f"Error fetching health professionals: {str(e)}")
return []
# Function to get directions and display on Gradio UI
def get_health_professionals_and_map(current_location, health_professional_query):
# Get health professionals using the search function
health_professionals = search_health_professionals(health_professional_query, current_location)
# Generate the map with the professionals' locations
map_obj = folium.Map(location=current_location, zoom_start=13)
for professional in health_professionals:
location = professional['geometry']['location']
folium.Marker([location['lat'], location['lng']], popup=professional['name']).add_to(map_obj)
# Save the map to an HTML file
map_html = "health_professionals_map.html"
map_obj.save(map_html)
# Generate route information (basic for now)
route_info = [f"{hp['name']} - {hp['vicinity']}" for hp in health_professionals]
return route_info, map_html
# Function to generate suggestions based on the detected emotion
def generate_suggestions(emotion):
suggestions = {
'joy': [
{"Title": "Relaxation Techniques", "Subject": "Relaxation", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
{"Title": "Dealing with Stress", "Subject": "Stress Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
],
'anger': [
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
{"Title": "Stress Management Tips", "Subject": "Stress Management", "Link": "https://www.health.harvard.edu/health-a-to-z"},
{"Title": "Dealing with Anger", "Subject": "Anger Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/MIc299Flibs"}
],
'fear': [
{"Title": "Mindfulness Practices", "Subject": "Mindfulness", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
{"Title": "Coping with Anxiety", "Subject": "Anxiety Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/yGKKz185M5o"}
],
'sadness': [
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
{"Title": "Dealing with Anxiety", "Subject": "Anxiety Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/-e-4Kx5px_I"}
],
'surprise': [
{"Title": "Managing Stress", "Subject": "Stress Management", "Link": "https://www.health.harvard.edu/health-a-to-z"},
{"Title": "Coping Strategies", "Subject": "Coping", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
]
}
return suggestions.get(emotion.lower(), [])
# Define the Gradio interface
iface = gr.Interface(fn=chatbot,
inputs=[gr.Textbox(label="Message"),
gr.State()],
outputs=[gr.Chatbot(), gr.State()],
allow_flagging="never", theme="compact")
iface.launch()