Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,103 +3,99 @@ from transformers import pipeline
|
|
3 |
import torch
|
4 |
import time
|
5 |
|
6 |
-
#
|
7 |
st.set_page_config(
|
8 |
-
page_title="
|
9 |
-
page_icon="
|
10 |
layout="centered",
|
11 |
-
initial_sidebar_state="expanded"
|
12 |
)
|
13 |
|
14 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
@st.cache_resource
|
16 |
-
def
|
17 |
try:
|
18 |
-
st.info("
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
20 |
st.success("β
Model loaded successfully!")
|
21 |
-
return
|
22 |
except Exception as e:
|
23 |
-
st.error(f"Error loading
|
24 |
return None
|
25 |
|
26 |
-
#
|
27 |
-
|
|
|
|
|
|
|
28 |
if emotion_analyzer is None:
|
29 |
-
|
30 |
-
return {"Error": "Emotion analyzer model not initialized. Please check model loading."}
|
31 |
|
32 |
try:
|
33 |
-
# Analyze
|
34 |
-
result = emotion_analyzer([
|
35 |
return {res["label"]: round(res["score"], 4) for res in result}
|
36 |
except Exception as e:
|
37 |
-
st.error(f"Prediction failed: {e}")
|
38 |
return {"Error": f"Prediction failed: {e}"}
|
39 |
|
40 |
-
#
|
41 |
-
st.
|
42 |
-
st.write("**Welcome to the Emotion Analyzer!** Feel the tropical vibes and explore your emotions.")
|
43 |
-
|
44 |
-
# Custom background
|
45 |
-
page_bg_img = '''
|
46 |
-
<style>
|
47 |
-
body {
|
48 |
-
background-color: #F5F5DC;
|
49 |
-
background-image: url("https://www.hawaiimagazine.com/wp-content/uploads/2022/06/aloha-background.jpg");
|
50 |
-
background-size: cover;
|
51 |
-
}
|
52 |
-
</style>
|
53 |
-
'''
|
54 |
-
st.markdown(page_bg_img, unsafe_allow_html=True)
|
55 |
|
56 |
-
# Define questions for the user
|
57 |
questions = [
|
58 |
-
"
|
59 |
-
"
|
60 |
-
"
|
61 |
-
"
|
62 |
-
"
|
63 |
]
|
64 |
|
65 |
-
# Initialize a dictionary to store responses
|
66 |
responses = {}
|
67 |
|
68 |
-
#
|
69 |
-
emotion_analyzer = None
|
70 |
-
max_retries = 3
|
71 |
-
retry_delay = 5 # seconds
|
72 |
-
|
73 |
-
# Try loading the model with retries
|
74 |
-
for attempt in range(max_retries):
|
75 |
-
emotion_analyzer = load_model()
|
76 |
-
if emotion_analyzer:
|
77 |
-
break
|
78 |
-
if attempt < max_retries - 1:
|
79 |
-
st.warning(f"β οΈ Retrying model load... Attempt {attempt + 2}/{max_retries}")
|
80 |
-
time.sleep(retry_delay)
|
81 |
-
else:
|
82 |
-
st.error("β Model failed to load after multiple attempts. Please try again later.")
|
83 |
-
|
84 |
-
# Function to handle responses and emotion analysis
|
85 |
for i, question in enumerate(questions, start=1):
|
86 |
-
|
|
|
|
|
87 |
if user_response:
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
st.
|
92 |
-
|
93 |
-
# Buttons for clearing or submitting responses
|
94 |
-
if st.button("Clear Responses"):
|
95 |
-
st.experimental_rerun()
|
96 |
|
|
|
97 |
if st.button("Submit Responses"):
|
|
|
98 |
if responses:
|
99 |
-
|
100 |
-
|
101 |
-
st.write(f"**
|
102 |
-
st.write(f"**
|
103 |
-
st.write(f"**Emotion Analysis:** {analysis}")
|
104 |
else:
|
105 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import torch
|
4 |
import time
|
5 |
|
6 |
+
# ---- Page Configuration ----
|
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("Aloha! Enter your thoughts and let me predict your emotions. π§ π‘")
|
17 |
+
|
18 |
+
# ---- Background Information ----
|
19 |
+
st.markdown(
|
20 |
+
"""
|
21 |
+
Welcome to the Emotion Prediction App!
|
22 |
+
This tool uses a state-of-the-art natural language processing (NLP) model to analyze your responses and predict your emotions.
|
23 |
+
Perfect for everyone in Hawaii or anywhere looking for a simple, fun way to understand feelings better! π΄β¨
|
24 |
+
"""
|
25 |
+
)
|
26 |
+
|
27 |
+
# ---- Function to Load Emotion Analysis Model ----
|
28 |
@st.cache_resource
|
29 |
+
def load_emotion_model():
|
30 |
try:
|
31 |
+
st.info("β³ Loading the emotion analysis model, please wait...")
|
32 |
+
# Using a public model for emotion classification
|
33 |
+
model = pipeline(
|
34 |
+
"text-classification",
|
35 |
+
model="bhadresh-savani/distilbert-base-uncased-emotion",
|
36 |
+
device=0 if torch.cuda.is_available() else -1, # Automatically use GPU if available
|
37 |
+
)
|
38 |
st.success("β
Model loaded successfully!")
|
39 |
+
return model
|
40 |
except Exception as e:
|
41 |
+
st.error(f"β οΈ Error loading model: {e}")
|
42 |
return None
|
43 |
|
44 |
+
# ---- Load the Model ----
|
45 |
+
emotion_analyzer = load_emotion_model()
|
46 |
+
|
47 |
+
# ---- Function for Predicting Emotion ----
|
48 |
+
def predict_emotion(text):
|
49 |
if emotion_analyzer is None:
|
50 |
+
return {"Error": "Emotion analyzer model not initialized. Please reload the app."}
|
|
|
51 |
|
52 |
try:
|
53 |
+
# Analyze emotions
|
54 |
+
result = emotion_analyzer([text])
|
55 |
return {res["label"]: round(res["score"], 4) for res in result}
|
56 |
except Exception as e:
|
|
|
57 |
return {"Error": f"Prediction failed: {e}"}
|
58 |
|
59 |
+
# ---- User Input Section ----
|
60 |
+
st.write("### π Let's Get Started!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
|
|
62 |
questions = [
|
63 |
+
"How are you feeling today?",
|
64 |
+
"Describe your mood in a few words.",
|
65 |
+
"What was the most significant emotion you felt this week?",
|
66 |
+
"How do you handle stress or challenges?",
|
67 |
+
"What motivates you the most right now?",
|
68 |
]
|
69 |
|
|
|
70 |
responses = {}
|
71 |
|
72 |
+
# ---- Ask Questions and Analyze Responses ----
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
for i, question in enumerate(questions, start=1):
|
74 |
+
st.write(f"#### π§ Question {i}: {question}")
|
75 |
+
user_response = st.text_input(f"Your answer to Q{i}:", key=f"q{i}")
|
76 |
+
|
77 |
if user_response:
|
78 |
+
with st.spinner("Analyzing emotion... π"):
|
79 |
+
analysis = predict_emotion(user_response)
|
80 |
+
responses[question] = {"Response": user_response, "Analysis": analysis}
|
81 |
+
st.success(f"π― Emotion Analysis: {analysis}")
|
|
|
|
|
|
|
|
|
82 |
|
83 |
+
# ---- Display Results ----
|
84 |
if st.button("Submit Responses"):
|
85 |
+
st.write("### π Emotion Analysis Results")
|
86 |
if responses:
|
87 |
+
for i, (question, details) in enumerate(responses.items(), start=1):
|
88 |
+
st.write(f"#### Question {i}: {question}")
|
89 |
+
st.write(f"**Your Response:** {details['Response']}")
|
90 |
+
st.write(f"**Emotion Analysis:** {details['Analysis']}")
|
|
|
91 |
else:
|
92 |
+
st.warning("Please answer at least one question before submitting!")
|
93 |
+
|
94 |
+
# ---- Footer ----
|
95 |
+
st.markdown(
|
96 |
+
"""
|
97 |
+
---
|
98 |
+
**Developed with π€ Transformers by OpenAI**
|
99 |
+
Designed for an intuitive and aesthetic experience. πΊ
|
100 |
+
"""
|
101 |
+
)
|