Spaces:
Sleeping
Sleeping
import json | |
import pickle | |
import random | |
import nltk | |
import numpy as np | |
import tflearn | |
import gradio as gr | |
import requests | |
import torch | |
import folium | |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline | |
from nltk.tokenize import word_tokenize | |
from nltk.stem.lancaster import LancasterStemmer | |
import os | |
from functools import lru_cache | |
import pandas as pd | |
import tensorflow as tf # Added to enable resource variables | |
# Enable resource variables in TensorFlow to avoid deprecated warnings | |
tf.compat.v1.enable_resource_variables() | |
# Ensure necessary NLTK resources are downloaded | |
nltk.download('punkt') | |
# Initialize the stemmer | |
stemmer = LancasterStemmer() | |
# Load intents.json | |
def load_intents(file_path): | |
with open(file_path) as file: | |
return json.load(file) | |
# Load preprocessed data from pickle | |
def load_preprocessed_data(file_path): | |
with open(file_path, "rb") as f: | |
return pickle.load(f) | |
# Build the model structure | |
def build_model(words, labels, training, output): | |
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) | |
return tflearn.DNN(net) | |
# Load the trained model | |
def load_model(model_path, net): | |
model = tflearn.DNN(net) | |
model.load(model_path) | |
return model | |
# 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, words, labels, model): | |
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 | |
# 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 | |
def detect_emotion(user_input): | |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion) | |
result = pipe(user_input) | |
emotion = result[0]['label'] | |
suggestions = [] | |
video_link = "" | |
# Provide suggestions based on the detected emotion | |
if emotion == 'joy': | |
suggestions = [ | |
("Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"), | |
("Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"), | |
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit") | |
] | |
video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A" | |
elif emotion == 'anger': | |
suggestions = [ | |
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"), | |
("Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"), | |
("Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety") | |
] | |
video_link = "Watch on YouTube: https://youtu.be/MIc299Flibs" | |
elif emotion == 'fear': | |
suggestions = [ | |
("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"), | |
("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"), | |
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit") | |
] | |
video_link = "Watch on YouTube: https://youtu.be/yGKKz185M5o" | |
elif emotion == 'sadness': | |
suggestions = [ | |
("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"), | |
("Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety") | |
] | |
video_link = "Watch on YouTube: https://youtu.be/-e-4Kx5px_I" | |
elif emotion == 'surprise': | |
suggestions = [ | |
("Managing Stress", "https://www.health.harvard.edu/health-a-to-z"), | |
("Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety") | |
] | |
video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A" | |
return emotion, suggestions, video_link | |
# 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 | |
} | |
try: | |
response = requests.get(geocode_url, params=params) | |
response.raise_for_status() | |
result = response.json() | |
if result['status'] == 'OK': | |
location = result['results'][0]['geometry']['location'] | |
return location['lat'], location['lng'] | |
else: | |
return None, None | |
except requests.RequestException as e: | |
print(f"Error fetching coordinates: {e}") | |
return None, None | |
# Function to fetch places data using Google Places API | |
def get_places_data(query, location, radius, api_key): | |
places_url = "https://maps.googleapis.com/maps/api/place/textsearch/json" | |
params = { | |
"query": query, | |
"location": location, | |
"radius": radius, | |
"key": api_key | |
} | |
try: | |
response = requests.get(places_url, params=params) | |
response.raise_for_status() | |
return response.json() | |
except requests.RequestException as e: | |
print(f"Error fetching places data: {e}") | |
return None | |
# Get wellness professionals | |
def get_wellness_professionals(location, 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 | |
lat, lon = get_lat_lon(location, api_key) | |
if lat is None or lon is None: | |
return "Unable to find coordinates for the given location." | |
# Using Google Places API to fetch wellness professionals | |
data = get_places_data(query, f"{lat},{lon}", radius, api_key) | |
if data: | |
results = data.get('results', []) | |
wellness_data = [] | |
for place in results: | |
name = place.get("name") | |
address = place.get("formatted_address") | |
latitude = place.get("geometry", {}).get("location", {}).get("lat") | |
longitude = place.get("geometry", {}).get("location", {}).get("lng") | |
wellness_data.append([name, address, latitude, longitude]) | |
return wellness_data | |
return [] | |
# Function to generate a map with wellness professionals | |
def generate_map(wellness_data): | |
map_center = [23.685, 90.3563] # Default center for Bangladesh (you can adjust this) | |
m = folium.Map(location=map_center, zoom_start=12) | |
for place in wellness_data: | |
name, address, lat, lon = place | |
folium.Marker([lat, lon], popup=f"{name}\n{address}").add_to(m) | |
return m | |
# Initialize the necessary files | |
data = load_intents("intents.json") | |
words, labels, training, output = load_preprocessed_data("data.pickle") | |
# Build the model | |
model = build_model(words, labels, training, output) | |
model = load_model("model.tflearn", model) | |
# Gradio interface | |
def chatbot_interface(message, history): | |
return chat(message, history, words, labels, model) | |
# Example usage with Gradio UI | |
gr.Interface(fn=chatbot_interface, inputs=["text", "state"], outputs=["chatbot", "state"]).launch() | |