Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,20 +2,22 @@ import streamlit as st
|
|
| 2 |
from transformers import pipeline
|
| 3 |
import torch
|
| 4 |
import time
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Function to load the model with error handling and retries
|
| 9 |
@st.cache_resource
|
| 10 |
def load_model():
|
| 11 |
try:
|
| 12 |
-
st.
|
| 13 |
-
emotion_analyzer = pipeline(
|
| 14 |
-
|
| 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}")
|
|
@@ -24,116 +26,80 @@ def load_model():
|
|
| 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("
|
| 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.
|
|
|
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
""",
|
| 61 |
-
unsafe_allow_html=True
|
| 62 |
-
)
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# Initialize the emotion analysis model with retries
|
| 70 |
-
emotion_analyzer =
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
"
|
| 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 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
st.write("Please answer all the questions before submitting.")
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 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 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
"""
|
| 139 |
-
)
|
|
|
|
| 2 |
from transformers import pipeline
|
| 3 |
import torch
|
| 4 |
import time
|
| 5 |
+
|
| 6 |
+
# App configuration
|
| 7 |
+
st.set_page_config(
|
| 8 |
+
page_title="Aloha Emotion App ๐ด",
|
| 9 |
+
page_icon="๐บ",
|
| 10 |
+
layout="centered",
|
| 11 |
+
initial_sidebar_state="expanded"
|
| 12 |
+
)
|
| 13 |
|
| 14 |
# Function to load the model with error handling and retries
|
| 15 |
@st.cache_resource
|
| 16 |
def load_model():
|
| 17 |
try:
|
| 18 |
+
st.info("๐บ Loading the emotion analysis model...")
|
| 19 |
+
emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta", device=0 if torch.cuda.is_available() else -1)
|
| 20 |
+
st.success("โ
Model loaded successfully!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
return emotion_analyzer
|
| 22 |
except Exception as e:
|
| 23 |
st.error(f"Error loading the model: {e}")
|
|
|
|
| 26 |
# Function to predict emotion for a single response
|
| 27 |
def predict_emotion_single(response, emotion_analyzer):
|
| 28 |
if emotion_analyzer is None:
|
| 29 |
+
st.error("โ Model not loaded. Please try reloading the app.")
|
| 30 |
return {"Error": "Emotion analyzer model not initialized. Please check model loading."}
|
| 31 |
+
|
| 32 |
try:
|
| 33 |
+
# Analyze the emotion of the response
|
| 34 |
result = emotion_analyzer([response])
|
| 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 |
# Streamlit App Layout
|
| 41 |
+
st.markdown("<h1 style='text-align: center; color: #2E8B57;'>Aloha Emotion Analyzer ๐บ</h1>", unsafe_allow_html=True)
|
| 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 |
+
"๐ How are you feeling today?",
|
| 59 |
+
"๐ด Describe your mood in a few words.",
|
| 60 |
+
"๐ What was the most significant emotion you felt this week?",
|
| 61 |
+
"๐บ How do you handle stress or challenges?",
|
| 62 |
+
"๐ What motivates you the most right now?"
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
# Initialize a dictionary to store responses
|
| 66 |
+
responses = {}
|
| 67 |
|
| 68 |
# Initialize the emotion analysis model with retries
|
| 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 |
+
user_response = st.text_input(f"Question {i}: {question}")
|
| 87 |
+
if user_response:
|
| 88 |
+
analysis = predict_emotion_single(user_response, emotion_analyzer)
|
| 89 |
+
responses[question] = (user_response, analysis)
|
| 90 |
+
st.write(f"**Your Response:** {user_response}")
|
| 91 |
+
st.write(f"**Emotion Analysis:** {analysis}")
|
|
|
|
| 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 |
+
st.markdown("<h3 style='color: #2E8B57;'>๐ Final Emotion Analysis Results:</h3>", unsafe_allow_html=True)
|
| 100 |
+
for i, (question, (response, analysis)) in enumerate(responses.items(), start=1):
|
| 101 |
+
st.write(f"**Question {i}:** {question}")
|
| 102 |
+
st.write(f"**Your Response:** {response}")
|
| 103 |
+
st.write(f"**Emotion Analysis:** {analysis}")
|
| 104 |
+
else:
|
| 105 |
+
st.write("โ Please answer all the questions before submitting.")
|
|
|
|
|
|