Testing / app.py
DreamStream-1's picture
Update app.py
c69efb6 verified
raw
history blame
9.59 kB
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 be 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)[0]
return result['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)[0]
return result['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'])
# Save results to CSV
def save_to_csv(data, filename):
data.to_csv(filename, index=False)
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Mental Health 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):
return predict_emotion(text)
# 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(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
submit_chat.click(chat, inputs=[message_input, gr.State()], outputs=[chatbot, gr.State()])
# 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)
# User input for text (sentiment analysis)
user_input_sentiment = gr.Textbox(lines=1, label="Enter text to analyze sentiment:")
submit_sentiment = gr.Button("Submit")
# Prediction button for sentiment analysis
def predict_sentiment(text):
return predict_sentiment(text)
sentiment_output = gr.Textbox(label="Predicted Sentiment")
submit_sentiment.click(predict_sentiment, inputs=user_input_sentiment, outputs=sentiment_output)
# Button to fetch wellness professionals data
fetch_button = gr.Button("Fetch Wellness Professionals Data")
data_output = gr.Dataframe(headers=["Name", "Rating", "Phone Number"])
def fetch_data():
df = fetch_nearby_health_professionals("Hawaii")
return df
fetch_button.click(fetch_data, inputs=None, outputs=data_output)
# Launch Gradio interface
demo.launch()