Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,81 +2,138 @@ import streamlit as st
|
|
2 |
from transformers import pipeline
|
3 |
import torch
|
4 |
import time
|
|
|
|
|
5 |
|
6 |
# Function to load the model with error handling and retries
|
7 |
@st.cache_resource
|
8 |
def load_model():
|
9 |
try:
|
10 |
-
st.write("
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
14 |
return emotion_analyzer
|
15 |
except Exception as e:
|
16 |
-
st.
|
17 |
return None
|
18 |
|
19 |
# Function to predict emotion for a single response
|
20 |
def predict_emotion_single(response, emotion_analyzer):
|
21 |
if emotion_analyzer is None:
|
22 |
-
st.error("Model not loaded. Please try reloading the app.")
|
23 |
return {"Error": "Emotion analyzer model not initialized. Please check model loading."}
|
24 |
-
|
25 |
try:
|
26 |
-
# Analyze the emotion of the response
|
27 |
result = emotion_analyzer([response])
|
28 |
return {res["label"]: round(res["score"], 4) for res in result}
|
29 |
except Exception as e:
|
30 |
st.error(f"Prediction failed: {e}")
|
31 |
return {"Error": f"Prediction failed: {e}"}
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
# Streamlit App Layout
|
34 |
-
st.
|
35 |
-
st.write("Enter your thoughts or feelings, and let the app predict your emotional states.")
|
36 |
|
37 |
-
#
|
38 |
-
|
39 |
-
"
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
-
#
|
47 |
-
|
|
|
|
|
48 |
|
49 |
# Initialize the emotion analysis model with retries
|
50 |
-
emotion_analyzer =
|
51 |
-
max_retries = 3
|
52 |
-
retry_delay = 5 # seconds
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from transformers import pipeline
|
3 |
import torch
|
4 |
import time
|
5 |
+
from datetime import datetime
|
6 |
+
import random
|
7 |
|
8 |
# Function to load the model with error handling and retries
|
9 |
@st.cache_resource
|
10 |
def load_model():
|
11 |
try:
|
12 |
+
st.write("🌺 Loading the emotion analysis model...")
|
13 |
+
emotion_analyzer = pipeline(
|
14 |
+
"text-classification",
|
15 |
+
model="j-hartmann/emotion-english-distilroberta",
|
16 |
+
device=0 if torch.cuda.is_available() else -1
|
17 |
+
)
|
18 |
+
st.success("🤙 Model loaded successfully!")
|
19 |
return emotion_analyzer
|
20 |
except Exception as e:
|
21 |
+
st.error(f"Error loading the model: {e}")
|
22 |
return None
|
23 |
|
24 |
# Function to predict emotion for a single response
|
25 |
def predict_emotion_single(response, emotion_analyzer):
|
26 |
if emotion_analyzer is None:
|
27 |
+
st.error("🌧 Model not loaded. Please try reloading the app.")
|
28 |
return {"Error": "Emotion analyzer model not initialized. Please check model loading."}
|
|
|
29 |
try:
|
|
|
30 |
result = emotion_analyzer([response])
|
31 |
return {res["label"]: round(res["score"], 4) for res in result}
|
32 |
except Exception as e:
|
33 |
st.error(f"Prediction failed: {e}")
|
34 |
return {"Error": f"Prediction failed: {e}"}
|
35 |
|
36 |
+
# Function to get a Hawaiian motivational quote
|
37 |
+
def get_hawaiian_quote():
|
38 |
+
quotes = [
|
39 |
+
"Aloha is the way to joy and peace.",
|
40 |
+
"No rain, no rainbows.",
|
41 |
+
"Happiness is a choice, and today is a great day to smile.",
|
42 |
+
"He pōmaikaʻi ke ola – Life is a blessing.",
|
43 |
+
]
|
44 |
+
return random.choice(quotes)
|
45 |
+
|
46 |
# Streamlit App Layout
|
47 |
+
st.set_page_config(page_title="Emotion Prediction App 🌈", page_icon="🌺", layout="wide")
|
|
|
48 |
|
49 |
+
# Add a Hawaiian-themed background
|
50 |
+
st.markdown(
|
51 |
+
"""
|
52 |
+
<style>
|
53 |
+
body {
|
54 |
+
background-image: url('https://cdn.pixabay.com/photo/2016/02/18/22/16/palm-trees-1209540_1280.jpg');
|
55 |
+
background-size: cover;
|
56 |
+
color: white;
|
57 |
+
}
|
58 |
+
.stTextInput, .stButton { background-color: rgba(255, 255, 255, 0.8); border-radius: 10px; }
|
59 |
+
</style>
|
60 |
+
""",
|
61 |
+
unsafe_allow_html=True
|
62 |
+
)
|
63 |
|
64 |
+
# Sidebar for Navigation
|
65 |
+
st.sidebar.title("Navigate 🌴")
|
66 |
+
st.sidebar.markdown("Choose an option:")
|
67 |
+
options = st.sidebar.radio("", ["Home", "History", "Tips"])
|
68 |
|
69 |
# Initialize the emotion analysis model with retries
|
70 |
+
emotion_analyzer = load_model()
|
|
|
|
|
71 |
|
72 |
+
if options == "Home":
|
73 |
+
st.title("🌈 Aloha! Welcome to the Behavior Prediction App 🌺")
|
74 |
+
st.write("Enter your thoughts or feelings, and let the app predict your emotional states.")
|
75 |
+
|
76 |
+
# Define questions for the user
|
77 |
+
questions = [
|
78 |
+
"How are you feeling today?",
|
79 |
+
"Describe your mood in a few words.",
|
80 |
+
"What was the most significant emotion you felt this week?",
|
81 |
+
"How do you handle stress or challenges?",
|
82 |
+
"What motivates you the most right now?",
|
83 |
+
]
|
84 |
+
|
85 |
+
# Initialize a dictionary to store responses
|
86 |
+
responses = {}
|
87 |
+
for i, question in enumerate(questions, start=1):
|
88 |
+
user_response = st.text_input(f"Question {i}: {question}")
|
89 |
+
if user_response:
|
90 |
+
analysis = predict_emotion_single(user_response, emotion_analyzer)
|
91 |
+
responses[question] = (user_response, analysis)
|
92 |
+
st.write(f"**Your Response**: {user_response}")
|
93 |
+
st.write(f"**Emotion Analysis**: {analysis}")
|
94 |
+
|
95 |
+
# Show motivational quote
|
96 |
+
st.markdown(f"💡 Hawaiian Wisdom: *{get_hawaiian_quote()}*")
|
97 |
+
|
98 |
+
# Save results (timestamped)
|
99 |
+
with open("emotion_history.txt", "a") as file:
|
100 |
+
file.write(f"{datetime.now()} | {question}: {user_response} | Analysis: {analysis}\n")
|
101 |
+
|
102 |
+
# Buttons for clearing or submitting responses
|
103 |
+
if st.button("Clear Responses"):
|
104 |
+
st.experimental_rerun()
|
105 |
|
106 |
+
if st.button("Submit Responses"):
|
107 |
+
if responses:
|
108 |
+
st.write("-- 🌟 Final Emotion Analysis Results ---")
|
109 |
+
for i, (question, (response, analysis)) in enumerate(responses.items(), start=1):
|
110 |
+
st.write(f"\n**Question {i}:** {question}")
|
111 |
+
st.write(f"**Your Response:** {response}")
|
112 |
+
st.write(f"**Emotion Analysis:** {analysis}")
|
113 |
+
else:
|
114 |
+
st.write("Please answer all the questions before submitting.")
|
115 |
|
116 |
+
elif options == "History":
|
117 |
+
st.title("📜 Your Emotional History")
|
118 |
+
try:
|
119 |
+
with open("emotion_history.txt", "r") as file:
|
120 |
+
history = file.readlines()
|
121 |
+
if history:
|
122 |
+
for line in history:
|
123 |
+
st.write(line.strip())
|
124 |
+
else:
|
125 |
+
st.write("No history found. Start analyzing your emotions today!")
|
126 |
+
except FileNotFoundError:
|
127 |
+
st.write("No history file found. Start analyzing your emotions today!")
|
128 |
|
129 |
+
elif options == "Tips":
|
130 |
+
st.title("🌟 Hawaiian Emotional Wellness Tips")
|
131 |
+
st.markdown(
|
132 |
+
"""
|
133 |
+
- **Spend Time in Nature**: Hawaii’s natural beauty can help ground you emotionally.
|
134 |
+
- **Practice Aloha**: Show love and respect to yourself and others.
|
135 |
+
- **Embrace ‘Ohana**: Stay connected with family and friends during emotional highs and lows.
|
136 |
+
- **Enjoy Hula or Surfing**: Engaging in cultural or physical activities can boost your mood.
|
137 |
+
- **Live by 'Pono'**: Strive for balance and righteousness in life.
|
138 |
+
"""
|
139 |
+
)
|