Spaces:
Sleeping
Sleeping
import gradio as gr | |
import random | |
import requests | |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline | |
# Replace with your Google Maps API and Places API Key | |
GOOGLE_API_KEY = "GOOGLE_API_KEY" | |
# Load pre-trained models for sentiment and emotion detection | |
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment") | |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base") | |
# Function to get latitude and longitude from city using Google Maps Geocoding API | |
def get_lat_lng_from_city(city): | |
geocode_url = f"https://maps.googleapis.com/maps/api/geocode/json?address={city}&key={GOOGLE_API_KEY}" | |
response = requests.get(geocode_url) | |
data = response.json() | |
if data["status"] == "OK": | |
lat_lng = data["results"][0]["geometry"]["location"] | |
return lat_lng["lat"], lat_lng["lng"] | |
else: | |
return None, None | |
# Function to get wellness professionals using Google Places API | |
def get_wellness_professionals(location): | |
lat, lng = get_lat_lng_from_city(location) | |
if lat and lng: | |
places_url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lng}&radius=5000&type=health&key={GOOGLE_API_KEY}" | |
response = requests.get(places_url) | |
data = response.json() | |
professionals = [] | |
if 'results' in data: | |
for place in data['results']: | |
name = place['name'] | |
address = place.get('vicinity', 'No address available') | |
url = place.get('website', '#') | |
professionals.append(f"**{name}** - {address} - [Visit Website]({url})") | |
if not professionals: | |
professionals.append("No wellness professionals found nearby.") | |
return "\n".join(professionals) | |
else: | |
return "Couldn't fetch your location. Please make sure you entered a valid location." | |
# 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] | |
# Add emoticon to sentiment | |
sentiment_emojis = { | |
"Negative": "π", | |
"Neutral": "π", | |
"Positive": "π" | |
} | |
sentiment_with_emoji = f"{sentiment} {sentiment_emojis.get(sentiment, 'π')}" | |
# Transition to emotion detection | |
state['step'] = 3 # Move to emotion detection and suggestions | |
return sentiment_with_emoji, state | |
# Function for emotion detection and suggestions | |
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 detected emotion | |
suggestions = provide_suggestions(emotion) | |
# Transition to wellness professional search | |
state['step'] = 4 # Move to wellness professional search | |
return emotion, suggestions, state | |
# Suggestions based on detected emotion | |
def provide_suggestions(emotion): | |
resources = { | |
'joy': { | |
'message': "You're feeling happy! Keep up the great mood! π", | |
'articles': [ | |
"[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)" | |
], | |
'videos': "[Watch Relaxation Video](https://youtu.be/m1vaUGtyo-A)" | |
}, | |
'anger': { | |
'message': "You're feeling angry. It's okay to feel this way. Let's try to calm down. π‘", | |
'articles': [ | |
"[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)", | |
"[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)" | |
], | |
'videos': "[Watch Anger Management Video](https://youtu.be/MIc299Flibs)" | |
}, | |
'fear': { | |
'message': "You're feeling fearful. Take a moment to breathe and relax. π¨", | |
'articles': [ | |
"[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)" | |
], | |
'videos': "[Watch Coping Video](https://youtu.be/yGKKz185M5o)" | |
}, | |
'sadness': { | |
'message': "You're feeling sad. It's okay to take a break. π", | |
'articles': [ | |
"[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)" | |
], | |
'videos': "[Watch Sadness Relief Video](https://youtu.be/-e-4Kx5px_I)" | |
}, | |
'surprise': { | |
'message': "You're feeling surprised. It's okay to feel neutral! π²", | |
'articles': [ | |
"[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)" | |
], | |
'videos': "[Watch Stress Relief Video](https://youtu.be/m1vaUGtyo-A)" | |
} | |
} | |
# Ensure we return a message even if no articles/videos are found | |
return resources.get(emotion, {'message': "Stay calm. π", 'articles': ["[General Wellbeing Tips](https://www.helpguide.org)"], 'videos': []}) | |
# Function to ask for location and provide wellness professionals | |
def search_wellness_professionals(location, state): | |
professionals = get_wellness_professionals(location) | |
state['step'] = 5 # Move to the next step | |
return professionals, state | |
# Create the UI with location input for wellness professionals | |
def create_ui(): | |
with gr.Blocks() as demo: | |
state = gr.State({'step': 1}) | |
chatbot = gr.Chatbot(elem_id="chatbot", label="Mental Health Chatbot") | |
message_input = gr.Textbox(placeholder="Ask me something...", label="Enter your message") | |
sentiment_output = gr.Textbox(placeholder="Sentiment result", label="Sentiment") | |
emotion_output = gr.Textbox(placeholder="Detected emotion", label="Emotion") | |
wellness_output = gr.Textbox(placeholder="Wellness professionals nearby", label="Wellness Professionals") | |
location_input = gr.Textbox(placeholder="Enter your city for wellness professionals", label="Location") | |
message_input.submit(chat, [message_input, chatbot, state], [chatbot, chatbot, state]) | |
message_input.submit(analyze_sentiment, [message_input, state], [sentiment_output, state]) | |
sentiment_output.submit(detect_emotion, [sentiment_output, state], [emotion_output, wellness_output, state]) | |
location_input.submit(search_wellness_professionals, [location_input, state], [wellness_output, state]) | |
return demo | |
# Launch Gradio interface | |
demo = create_ui() | |
demo.launch(debug=True) | |