Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,55 +1,9 @@
|
|
1 |
import streamlit as st
|
2 |
from transformers import pipeline
|
3 |
import torch
|
4 |
-
import
|
5 |
|
6 |
-
#
|
7 |
-
st.set_page_config(
|
8 |
-
page_title="Emotion Prediction App",
|
9 |
-
page_icon="π",
|
10 |
-
layout="centered",
|
11 |
-
initial_sidebar_state="expanded",
|
12 |
-
)
|
13 |
-
|
14 |
-
# ---- App Title ----
|
15 |
-
st.title("π Emotion Prediction App π")
|
16 |
-
st.subheader("Get emotional insights with tailored resources!")
|
17 |
-
|
18 |
-
# ---- Function to Load Emotion Analysis Model ----
|
19 |
-
@st.cache_resource
|
20 |
-
def load_emotion_model():
|
21 |
-
try:
|
22 |
-
st.info("β³ Loading the emotion analysis model, please wait...")
|
23 |
-
# Using a publicly available model for emotion analysis
|
24 |
-
emotion_analyzer = pipeline(
|
25 |
-
"text-classification",
|
26 |
-
model="bhadresh-savani/distilbert-base-uncased-emotion", # A valid public model
|
27 |
-
device=0 if torch.cuda.is_available() else -1, # Use GPU if available
|
28 |
-
)
|
29 |
-
st.success("β
Model loaded successfully!")
|
30 |
-
return emotion_analyzer
|
31 |
-
except Exception as e:
|
32 |
-
st.error(f"β οΈ Error loading model: {e}")
|
33 |
-
return None
|
34 |
-
|
35 |
-
# ---- Load the Model ----
|
36 |
-
emotion_analyzer = load_emotion_model()
|
37 |
-
|
38 |
-
# ---- Function for Predicting Emotion ----
|
39 |
-
def predict_emotion(text):
|
40 |
-
if emotion_analyzer is None:
|
41 |
-
st.error("β οΈ Model not loaded. Please reload the app.")
|
42 |
-
return {"Error": "Emotion analyzer model not initialized. Please try again later."}
|
43 |
-
|
44 |
-
try:
|
45 |
-
# Analyze emotions
|
46 |
-
result = emotion_analyzer([text])
|
47 |
-
return {res["label"]: round(res["score"], 4) for res in result}
|
48 |
-
except Exception as e:
|
49 |
-
st.error(f"β οΈ Prediction failed: {e}")
|
50 |
-
return {"Error": f"Prediction failed: {e}"}
|
51 |
-
|
52 |
-
# ---- Enhanced Suggestion Database ----
|
53 |
suggestion_database = {
|
54 |
"sadness": {
|
55 |
"suggestions": ["Try a guided meditation", "Take a walk in nature", "Connect with a friend"],
|
@@ -77,11 +31,11 @@ suggestion_database = {
|
|
77 |
"suggestions": ["Take a break", "Engage in a relaxing activity", "Spend time in nature"],
|
78 |
"articles": [
|
79 |
{"title": "Importance of Self-Care", "url": "https://example.com/selfcare1"},
|
80 |
-
{"title": "Stress Management Techniques", "url": "https://example.com/stress1"}
|
81 |
],
|
82 |
"videos": [
|
83 |
{"title": "Relaxation Techniques", "url": "https://www.youtube.com/watch?v=relaxvideo1"},
|
84 |
-
{"title": "Mindfulness Exercises", "url": "https://www.youtube.com/watch?v=mindfulnessvideo1"}
|
85 |
]
|
86 |
}
|
87 |
}
|
@@ -91,85 +45,107 @@ def get_relevant_resources(emotion):
|
|
91 |
resources = suggestion_database.get(emotion, {})
|
92 |
return resources.get("suggestions", []), resources.get("articles", []), resources.get("videos", [])
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
"
|
101 |
-
"
|
102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
-
#
|
105 |
-
st.write("### πΊ Answer 3 Simple Questions!")
|
106 |
questions = [
|
107 |
-
"How are you feeling
|
108 |
-
"
|
109 |
-
"What
|
110 |
]
|
111 |
|
|
|
112 |
responses = {}
|
113 |
|
114 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
for i, question in enumerate(questions, start=1):
|
116 |
-
st.
|
117 |
-
user_response = st.text_input(f"Your answer to Q{i}:", key=f"q{i}")
|
118 |
-
|
119 |
if user_response:
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
st.write(
|
133 |
-
|
134 |
-
|
135 |
-
st.write(f"
|
136 |
-
for
|
137 |
-
st.
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
# Display the summary table
|
162 |
-
st.dataframe(df) # or use st.table(df) for a static table
|
163 |
-
|
164 |
-
# Provide additional suggestions at the end of all questions
|
165 |
-
st.write("### π Final Suggestions")
|
166 |
-
st.write("Incorporating mindfulness, deep breathing, and spending time outdoors can help with emotional balance. Keep exploring activities that promote well-being! π±")
|
167 |
-
|
168 |
-
# ---- Footer ----
|
169 |
-
st.markdown(
|
170 |
-
"""
|
171 |
-
---
|
172 |
-
**Developed using π€ Transformers**
|
173 |
-
Designed for a fun and intuitive experience! π
|
174 |
-
"""
|
175 |
-
)
|
|
|
1 |
import streamlit as st
|
2 |
from transformers import pipeline
|
3 |
import torch
|
4 |
+
import time
|
5 |
|
6 |
+
# Enhanced Suggestion Database (Now includes resources)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
suggestion_database = {
|
8 |
"sadness": {
|
9 |
"suggestions": ["Try a guided meditation", "Take a walk in nature", "Connect with a friend"],
|
|
|
31 |
"suggestions": ["Take a break", "Engage in a relaxing activity", "Spend time in nature"],
|
32 |
"articles": [
|
33 |
{"title": "Importance of Self-Care", "url": "https://example.com/selfcare1"},
|
34 |
+
{"title": "Stress Management Techniques", "url": "https://example.com/stress1"},
|
35 |
],
|
36 |
"videos": [
|
37 |
{"title": "Relaxation Techniques", "url": "https://www.youtube.com/watch?v=relaxvideo1"},
|
38 |
+
{"title": "Mindfulness Exercises", "url": "https://www.youtube.com/watch?v=mindfulnessvideo1"},
|
39 |
]
|
40 |
}
|
41 |
}
|
|
|
45 |
resources = suggestion_database.get(emotion, {})
|
46 |
return resources.get("suggestions", []), resources.get("articles", []), resources.get("videos", [])
|
47 |
|
48 |
+
# Function to load the model with error handling and retries
|
49 |
+
@st.cache_resource
|
50 |
+
def load_model():
|
51 |
+
try:
|
52 |
+
st.write("Attempting to load the emotion analysis model...")
|
53 |
+
# Using a smaller model for quick load times
|
54 |
+
emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta", device=0 if torch.cuda.is_available() else -1)
|
55 |
+
st.write("Model loaded successfully!")
|
56 |
+
return emotion_analyzer
|
57 |
+
except Exception as e:
|
58 |
+
st.write(f"Error loading the model: {e}")
|
59 |
+
return None
|
60 |
+
|
61 |
+
# Function to predict emotion for a single response
|
62 |
+
def predict_emotion_single(response, emotion_analyzer):
|
63 |
+
if emotion_analyzer is None:
|
64 |
+
st.error("Model not loaded. Please try reloading the app.")
|
65 |
+
return {"Error": "Emotion analyzer model not initialized. Please check model loading."}
|
66 |
+
|
67 |
+
try:
|
68 |
+
result = emotion_analyzer([response])
|
69 |
+
return {res["label"]: round(res["score"], 4) for res in result}
|
70 |
+
except Exception as e:
|
71 |
+
st.error(f"Prediction failed: {e}")
|
72 |
+
return {"Error": f"Prediction failed: {e}"}
|
73 |
+
|
74 |
+
# Streamlit App Layout
|
75 |
+
st.title("Emotion Prediction App: Your Personal Wellness Assistant")
|
76 |
+
|
77 |
+
st.write("**How it works:**")
|
78 |
+
st.write("- Enter your thoughts or feelings.")
|
79 |
+
st.write("- Our AI analyzes your text to predict your emotional state.")
|
80 |
+
st.write("- Receive personalized suggestions to improve your well-being.")
|
81 |
|
82 |
+
# Define questions for the user
|
|
|
83 |
questions = [
|
84 |
+
"How are you feeling today?",
|
85 |
+
"Describe your mood in a few words.",
|
86 |
+
"What was the most significant emotion you felt this week?"
|
87 |
]
|
88 |
|
89 |
+
# Initialize a dictionary to store responses
|
90 |
responses = {}
|
91 |
|
92 |
+
# Initialize the emotion analysis model with retries
|
93 |
+
emotion_analyzer = None
|
94 |
+
max_retries = 3
|
95 |
+
retry_delay = 5 # seconds
|
96 |
+
|
97 |
+
# Try loading the model with retries
|
98 |
+
for attempt in range(max_retries):
|
99 |
+
emotion_analyzer = load_model()
|
100 |
+
if emotion_analyzer:
|
101 |
+
break
|
102 |
+
if attempt < max_retries - 1:
|
103 |
+
st.warning(f"Retrying model load... Attempt {attempt + 2}/{max_retries}")
|
104 |
+
time.sleep(retry_delay)
|
105 |
+
else:
|
106 |
+
st.error("Model failed to load after multiple attempts. Please try again later.")
|
107 |
+
|
108 |
+
# Function to handle responses and emotion analysis
|
109 |
for i, question in enumerate(questions, start=1):
|
110 |
+
user_response = st.text_input(f"Question {i}: {question}")
|
|
|
|
|
111 |
if user_response:
|
112 |
+
analysis = predict_emotion_single(user_response, emotion_analyzer)
|
113 |
+
responses[question] = (user_response, analysis)
|
114 |
+
st.write(f"**Your Response**: {user_response}")
|
115 |
+
st.write(f"**Emotion Analysis**: {analysis}")
|
116 |
+
|
117 |
+
# Based on the emotion, suggest activities, articles, and videos
|
118 |
+
max_emotion = max(analysis, key=analysis.get) if analysis else "neutral"
|
119 |
+
suggestions, articles, videos = get_relevant_resources(max_emotion)
|
120 |
+
|
121 |
+
if suggestions:
|
122 |
+
st.write(f"### π§ Suggested Activity: {suggestions[0]}")
|
123 |
+
else:
|
124 |
+
st.write("### π§ No suggestions available at the moment.")
|
125 |
+
|
126 |
+
if articles:
|
127 |
+
st.write(f"### π Suggested Articles:")
|
128 |
+
for article in articles:
|
129 |
+
st.write(f"[{article['title']}]({article['url']})")
|
130 |
+
else:
|
131 |
+
st.write("### π No articles available at the moment.")
|
132 |
+
|
133 |
+
if videos:
|
134 |
+
st.write(f"### π₯ Suggested Videos:")
|
135 |
+
for video in videos:
|
136 |
+
st.write(f"[{video['title']}]({video['url']})")
|
137 |
+
else:
|
138 |
+
st.write("### π₯ No videos available at the moment.")
|
139 |
+
|
140 |
+
# Provide button to clear input fields
|
141 |
+
if st.button("Clear Responses"):
|
142 |
+
st.experimental_rerun()
|
143 |
+
|
144 |
+
# Display results once all responses are filled
|
145 |
+
if st.button("Submit Responses"):
|
146 |
+
if responses:
|
147 |
+
st.write("-- Emotion Analysis Results ---")
|
148 |
+
for i, (question, (response, analysis)) in enumerate(responses.items(), start=1):
|
149 |
+
st.write(f"**{question}**")
|
150 |
+
st.write(f"Response: {response}")
|
151 |
+
st.write(f"Emotion Analysis: {analysis}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|