Spaces:
Sleeping
Sleeping
import gradio as gr | |
import nltk | |
import numpy as np | |
import tflearn | |
import random | |
import json | |
import pickle | |
import torch | |
from nltk.tokenize import word_tokenize | |
from nltk.stem.lancaster import LancasterStemmer | |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline | |
import requests | |
import re | |
from bs4 import BeautifulSoup | |
import time | |
import pandas as pd | |
from selenium import webdriver | |
from selenium.webdriver.chrome.options import Options | |
import chromedriver_autoinstaller | |
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, state): | |
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?" | |
history.append((message, response)) | |
# Update state to move to the next feature | |
state['step'] = 2 # Move to sentiment analysis | |
except Exception as e: | |
response = f"An error occurred: {str(e)}" | |
return history, history, state | |
# Load pre-trained model and tokenizer for sentiment analysis | |
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
# Function for sentiment analysis | |
def analyze_sentiment(text, state): | |
inputs = tokenizer(text, return_tensors="pt") | |
with torch.no_grad(): | |
outputs = sentiment_model(**inputs) | |
predicted_class = torch.argmax(outputs.logits, dim=1).item() | |
sentiment = ["Negative", "Neutral", "Positive"][predicted_class] | |
# Update state to move to the next feature | |
state['step'] = 3 # Move to emotion detection and suggestions | |
return sentiment, state | |
# Load pre-trained model and tokenizer for emotion detection | |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
# Function for emotion detection | |
def detect_emotion(text, state): | |
pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer) | |
result = pipe(text) | |
emotion = result[0]['label'] | |
# Provide suggestions based on emotion | |
suggestions = provide_suggestions(emotion) | |
# Update state to move to the next feature | |
state['step'] = 4 # Move to wellness professional search | |
return emotion, suggestions, state | |
# Suggestions based on detected emotion | |
def provide_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 deep breaths, everything will be okay." | |
elif emotion == 'sadness': | |
return "You're feeling sad. It's okay, things will get better. You're not alone." | |
else: | |
return "Sorry, no suggestions available for this emotion." | |
# Function to find wellness professionals | |
def find_wellness_professionals(location, state): | |
query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist in " + location | |
api_key = "YOUR_GOOGLE_API_KEY" # Replace with your own API key | |
location_coords = "21.3,-157.8" # Default to Oahu, Hawaii | |
radius = 50000 # 50 km radius | |
google_places_data = get_all_places(query, location_coords, radius, api_key) | |
if google_places_data: | |
df = pd.DataFrame(google_places_data, columns=[ | |
"Name", "Address", "Phone", "Rating", "Business Status", | |
"User Ratings Total", "Website", "Types", "Latitude", "Longitude", | |
"Opening Hours", "Reviews", "Email" | |
]) | |
return df, state | |
else: | |
return pd.DataFrame(), state | |
# The functions for scraping websites and fetching details | |
def get_all_places(query, location, radius, api_key): | |
all_results = [] | |
next_page_token = None | |
while True: | |
data = get_places_data(query, location, radius, api_key, next_page_token) | |
if data: | |
results = data.get('results', []) | |
for place in results: | |
place_id = place.get("place_id") | |
name = place.get("name") | |
address = place.get("formatted_address") | |
rating = place.get("rating", "Not available") | |
business_status = place.get("business_status", "Not available") | |
user_ratings_total = place.get("user_ratings_total", "Not available") | |
website = place.get("website", "Not available") | |
types = ", ".join(place.get("types", [])) | |
location = place.get("geometry", {}).get("location", {}) | |
latitude = location.get("lat", "Not available") | |
longitude = location.get("lng", "Not available") | |
details = get_place_details(place_id, api_key) | |
phone_number = details.get("phone_number", "Not available") | |
email = details.get("email", "Not available") | |
all_results.append([name, address, phone_number, rating, business_status, | |
user_ratings_total, website, types, latitude, longitude, | |
details.get("opening_hours", "Not available"), | |
details.get("reviews", "Not available"), email]) | |
next_page_token = data.get('next_page_token') | |
if not next_page_token: | |
break | |
time.sleep(2) | |
return all_results | |
# Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("# Wellbeing Support System") | |
state = gr.State({"step": 1}) # Track the flow step | |
with gr.Tab("Chatbot"): | |
chatbot = gr.Chatbot() | |
msg = gr.Textbox() | |
clear = gr.Button("Clear") | |
msg.submit(chat, inputs=[msg, chatbot, state], outputs=[chatbot, chatbot, state]) | |
clear.click(lambda: None, None, chatbot) | |
with gr.Tab("Sentiment Analysis"): | |
sentiment_output = gr.Textbox(label="Sentiment:") | |
text_input = gr.Textbox(label="Enter text to analyze sentiment:") | |
analyze_button = gr.Button("Analyze Sentiment") | |
analyze_button.click(analyze_sentiment, inputs=[text_input, state], outputs=[sentiment_output, state]) | |
with gr.Tab("Emotion Detection & Suggestions"): | |
emotion_input = gr.Textbox(label="How are you feeling today?", value="Enter your thoughts here...") | |
detect_button = gr.Button("Detect Emotion") | |
emotion_output = gr.Textbox(label="Detected Emotion:") | |
suggestions_output = gr.Textbox(label="Suggestions:") | |
detect_button.click(detect_emotion, inputs=[emotion_input, state], outputs=[emotion_output, suggestions_output, state]) | |
with gr.Tab("Find Local Wellness Professionals"): | |
location_input = gr.Textbox(label="Enter your location:", value="Hawaii") | |
search_button = gr.Button("Search") | |
results_output = gr.Dataframe(label="Search Results") | |
search_button.click(find_wellness_professionals, inputs=[location_input, state], outputs=[results_output, state]) | |
demo.launch() | |