File size: 6,161 Bytes
72fce14
 
 
5f72fbb
dfe4a9e
5f72fbb
bebf7e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f72fbb
bebf7e5
 
 
5f72fbb
bebf7e5
 
 
 
 
 
 
 
 
5f72fbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df8106d
5f72fbb
dfe4a9e
5f72fbb
 
 
dfe4a9e
 
5f72fbb
dfe4a9e
72fce14
5f72fbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfe4a9e
5f72fbb
dfe4a9e
5f72fbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2fefd9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
@st.cache_resource
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}")