Spaces:
Sleeping
Sleeping
import streamlit as st | |
from transformers import pipeline | |
import torch | |
import time | |
# Enhanced Suggestion Database (Now includes resources) | |
suggestion_database = { | |
"sadness": { | |
"suggestions": ["Try a guided meditation", "Take a walk in nature", "Connect with a friend"], | |
"articles": [ | |
{"title": "Overcoming Sadness", "url": "https://example.com/sadness1"}, | |
{"title": "Understanding Depression", "url": "https://example.com/sadness2"}, | |
], | |
"videos": [ | |
{"title": "Mindfulness for Sadness", "url": "https://www.youtube.com/watch?v=sadnessvideo1"}, | |
{"title": "Coping with Grief", "url": "https://www.youtube.com/watch?v=sadnessvideo2"}, | |
], | |
}, | |
"joy": { | |
"suggestions": ["Practice gratitude", "Engage in a hobby", "Spend time with loved ones"], | |
"articles": [ | |
{"title": "The Benefits of Joy", "url": "https://example.com/joy1"}, | |
{"title": "Maintaining Positive Emotions", "url": "https://example.com/joy2"}, | |
], | |
"videos": [ | |
{"title": "Boosting Your Happiness", "url": "https://www.youtube.com/watch?v=joyvideo1"}, | |
{"title": "Practicing Gratitude", "url": "https://www.youtube.com/watch?v=joyvideo2"}, | |
], | |
}, | |
"neutral": { | |
"suggestions": ["Take a break", "Engage in a relaxing activity", "Spend time in nature"], | |
"articles": [ | |
{"title": "Importance of Self-Care", "url": "https://example.com/selfcare1"}, | |
{"title": "Stress Management Techniques", "url": "https://example.com/stress1"}, | |
], | |
"videos": [ | |
{"title": "Relaxation Techniques", "url": "https://www.youtube.com/watch?v=relaxvideo1"}, | |
{"title": "Mindfulness Exercises", "url": "https://www.youtube.com/watch?v=mindfulnessvideo1"}, | |
] | |
} | |
} | |
# Function to fetch relevant resources | |
def get_relevant_resources(emotion): | |
resources = suggestion_database.get(emotion, {}) | |
return resources.get("suggestions", []), resources.get("articles", []), resources.get("videos", []) | |
# Function to load the model with error handling and retries | |
def load_model(): | |
try: | |
st.write("Attempting to load the emotion analysis model...") | |
# Using a smaller model for quick load times | |
emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta", device=0 if torch.cuda.is_available() else -1) | |
st.write("Model loaded successfully!") | |
return emotion_analyzer | |
except Exception as e: | |
st.write(f"Error loading the model: {e}") | |
return None | |
# Function to predict emotion for a single response | |
def predict_emotion_single(response, emotion_analyzer): | |
if emotion_analyzer is None: | |
st.error("Model not loaded. Please try reloading the app.") | |
return {"Error": "Emotion analyzer model not initialized. Please check model loading."} | |
try: | |
result = emotion_analyzer([response]) | |
return {res["label"]: round(res["score"], 4) for res in result} | |
except Exception as e: | |
st.error(f"Prediction failed: {e}") | |
return {"Error": f"Prediction failed: {e}"} | |
# Streamlit App Layout | |
st.title("Emotion Prediction App: Your Personal Wellness Assistant") | |
st.write("**How it works:**") | |
st.write("- Enter your thoughts or feelings.") | |
st.write("- Our AI analyzes your text to predict your emotional state.") | |
st.write("- Receive personalized suggestions to improve your well-being.") | |
# Define questions for the user | |
questions = [ | |
"How are you feeling today?", | |
"Describe your mood in a few words.", | |
"What was the most significant emotion you felt this week?" | |
] | |
# Initialize a dictionary to store responses | |
responses = {} | |
# Initialize the emotion analysis model with retries | |
emotion_analyzer = None | |
max_retries = 3 | |
retry_delay = 5 # seconds | |
# Try loading the model with retries | |
for attempt in range(max_retries): | |
emotion_analyzer = load_model() | |
if emotion_analyzer: | |
break | |
if attempt < max_retries - 1: | |
st.warning(f"Retrying model load... Attempt {attempt + 2}/{max_retries}") | |
time.sleep(retry_delay) | |
else: | |
st.error("Model failed to load after multiple attempts. Please try again later.") | |
# Function to handle responses and emotion analysis | |
for i, question in enumerate(questions, start=1): | |
user_response = st.text_input(f"Question {i}: {question}") | |
if user_response: | |
analysis = predict_emotion_single(user_response, emotion_analyzer) | |
responses[question] = (user_response, analysis) | |
st.write(f"**Your Response**: {user_response}") | |
st.write(f"**Emotion Analysis**: {analysis}") | |
# Based on the emotion, suggest activities, articles, and videos | |
max_emotion = max(analysis, key=analysis.get) if analysis else "neutral" | |
suggestions, articles, videos = get_relevant_resources(max_emotion) | |
if suggestions: | |
st.write(f"### π§ Suggested Activity: {suggestions[0]}") | |
else: | |
st.write("### π§ No suggestions available at the moment.") | |
if articles: | |
st.write(f"### π Suggested Articles:") | |
for article in articles: | |
st.write(f"[{article['title']}]({article['url']})") | |
else: | |
st.write("### π No articles available at the moment.") | |
if videos: | |
st.write(f"### π₯ Suggested Videos:") | |
for video in videos: | |
st.write(f"[{video['title']}]({video['url']})") | |
else: | |
st.write("### π₯ No videos available at the moment.") | |
# Provide button to clear input fields | |
if st.button("Clear Responses"): | |
st.experimental_rerun() | |
# Display results once all responses are filled | |
if st.button("Submit Responses"): | |
if responses: | |
st.write("-- Emotion Analysis Results ---") | |
for i, (question, (response, analysis)) in enumerate(responses.items(), start=1): | |
st.write(f"**{question}**") | |
st.write(f"Response: {response}") | |
st.write(f"Emotion Analysis: {analysis}") | |