Testing / app.py
DreamStream-1's picture
Update app.py
d7c7798 verified
raw
history blame
10.8 kB
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
# 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"
@lru_cache(maxsize=128)
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(
location=[lat, lon],
popup=f"<b>{name}</b><br>{address}",
icon=folium.Icon(color='blue', icon='info-sign')
).add_to(m)
# Save map as an HTML string
map_html = m._repr_html_()
return map_html
# Gradio interface setup for user interaction
def user_interface(message, location, history, api_key, words, labels, model):
history, history = chat(message, history, words, labels, model)
# Sentiment analysis
inputs = tokenizer_sentiment(message, return_tensors="pt")
outputs = model_sentiment(**inputs)
sentiment = ["Negative", "Neutral", "Positive"][torch.argmax(outputs.logits, dim=1).item()]
# Emotion detection
emotion, resources, video_link = detect_emotion(message)
# Get wellness professionals
wellness_data = get_wellness_professionals(location, api_key)
# Generate the map
map_html = generate_map(wellness_data)
# Create a DataFrame for the suggestions
suggestions_df = pd.DataFrame(resources, columns=["Resource", "Link"])
# Format the final output
output = f"**Chat Response:** {history[-1][1]}\n\n"
output += f"**Sentiment:** {sentiment}\n\n"
output += f"**Detected Emotion:** {emotion}\n\n"
output += "**Suggestions based on Emotion:**\n"
for resource in resources:
output += f"- [{resource[0]}]({resource[1]})\n"
output += f"\n**Video Suggestion:** {video_link}\n\n"
output += "**Wellness Professionals near you:**\n"
output += map_html
return output, history
# Load intents and preprocessed data
data = load_intents('intents.json')
words, labels, training, output = load_preprocessed_data('data.pkl')
# Build and load the model
net = build_model(words, labels, training, output)
model = load_model('model.tflearn', net)
# Gradio interface
iface = gr.Interface(
fn=user_interface,
inputs=[
gr.inputs.Textbox(label="Message"),
gr.inputs.Textbox(label="Location"),
gr.State([]), # History
gr.State(os.getenv("GOOGLE_API_KEY")), # API Key
gr.State(words),
gr.State(labels),
gr.State(model)
],
outputs=[
gr.outputs.Markdown(label="Response"),
gr.outputs.Chatbot(label="Chat History")
],
title="Wellness Chatbot",
description="A chatbot to provide wellness support and locate professionals near you."
)
iface.launch(debug=True)