Spaces:
Sleeping
Sleeping
File size: 6,210 Bytes
72fce14 9f5d8a9 dfe4a9e 6325706 dfe4a9e 6325706 abc0dd5 dfe4a9e 6325706 dfe4a9e 72fce14 6325706 1985126 6325706 72fce14 6325706 72fce14 6325706 5966f7d 1985126 6325706 5966f7d 1985126 6325706 dfe4a9e 1985126 72fce14 6325706 72fce14 6325706 8988fb4 5966f7d dfe4a9e 72fce14 6325706 72fce14 5966f7d 986d689 72fce14 5a49ede df8106d 6325706 1985126 dfe4a9e 6325706 dfe4a9e 72fce14 6325706 dfe4a9e 1985126 6325706 dfe4a9e 6325706 5a49ede df8106d 5a49ede 6325706 5a49ede 72fce14 6325706 dfe4a9e 6325706 9f5d8a9 6325706 1985126 6325706 5966f7d |
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 |
import streamlit as st
from transformers import pipeline
import torch
import pandas as pd
# ---- Page Configuration ----
st.set_page_config(
page_title="Emotion Prediction App",
page_icon="๐",
layout="centered",
initial_sidebar_state="expanded",
)
# ---- App Title ----
st.title("๐ Emotion Prediction App ๐")
st.subheader("Understand your emotions better with AI-powered predictions!")
# ---- Function to Load Emotion Analysis Model ----
@st.cache_resource
def load_emotion_model():
try:
st.info("โณ Loading the emotion analysis model, please wait...")
# Using a publicly available model for emotion analysis
emotion_analyzer = pipeline(
"text-classification",
model="bhadresh-savani/distilbert-base-uncased-emotion", # A valid public model
device=0 if torch.cuda.is_available() else -1, # Use GPU if available
)
st.success("โ
Model loaded successfully!")
return emotion_analyzer
except Exception as e:
st.error(f"โ ๏ธ Error loading model: {e}")
return None
# ---- Load the Model ----
emotion_analyzer = load_emotion_model()
# ---- Function for Predicting Emotion ----
def predict_emotion(text):
if emotion_analyzer is None:
st.error("โ ๏ธ Model not loaded. Please reload the app.")
return {"Error": "Emotion analyzer model not initialized. Please try again later."}
try:
# Analyze emotions
result = emotion_analyzer([text])
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}"}
# ---- Suggesting Activities Based on Emotional State ----
def suggest_activity(emotion_analysis):
# Suggest activities based on emotional state
max_emotion = max(emotion_analysis, key=emotion_analysis.get) if emotion_analysis else None
if max_emotion == 'sadness':
return "It's okay to feel sad sometimes. Try taking a 5-minute mindfulness break or a short walk outside to clear your mind."
elif max_emotion == 'joy':
return "Youโre feeling happy! Keep that positive energy going. How about practicing some deep breathing exercises to maintain your balance?"
elif max_emotion == 'fear':
return "Feeling anxious? It might help to do a quick breathing exercise or take a walk to ease your mind."
elif max_emotion == 'anger':
return "It seems like you're angry. Try taking a few deep breaths, or engage in a relaxing mindfulness exercise to calm your nerves."
elif max_emotion == 'surprise':
return "Youโre surprised! Take a moment to breathe deeply and reflect. A walk might help clear your thoughts."
elif max_emotion == 'disgust':
return "If youโre feeling disgusted, a change of environment might help. Go for a walk or try a mindfulness technique to relax."
elif max_emotion == 'sadness':
return "Itโs okay to feel sad. Try grounding yourself with some mindfulness or a breathing exercise."
else:
return "Keep doing great! If you feel overwhelmed, consider taking a deep breath or going for a short walk."
# ---- User Input Section ----
st.write("### ๐บ Let's Get Started!")
questions = [
"How are you feeling today?",
"Describe your mood in a few words.",
"What was the most significant emotion you felt this week?",
"How do you handle stress or challenges?",
"What motivates you the most right now?",
]
responses = {}
# ---- Ask Questions and Analyze Responses ----
for i, question in enumerate(questions, start=1):
st.write(f"#### โ Question {i}: {question}")
user_response = st.text_input(f"Your answer to Q{i}:", key=f"q{i}")
if user_response:
with st.spinner("Analyzing emotion... ๐ญ"):
analysis = predict_emotion(user_response)
responses[question] = {"Response": user_response, "Analysis": analysis}
# Display Emotion Analysis
st.success(f"๐ฏ Emotion Analysis: {analysis}")
# Display Activity Suggestion
if analysis:
max_emotion = max(analysis, key=analysis.get)
activity_suggestion = suggest_activity(analysis)
st.write(f"### ๐ง Suggested Activity: {activity_suggestion}")
# ---- Display Results ----
if st.button("Submit Responses"):
st.write("### ๐ Emotion Analysis Results")
# Prepare the data for the summary table
summary_data = []
for i, (question, details) in enumerate(responses.items(), start=1):
# Activity suggestion for each response
activity_suggestion = suggest_activity(details["Analysis"])
# Add data to the summary list
summary_data.append({
"Question": question,
"Your Response": details["Response"],
"Emotion Analysis": details["Analysis"],
"Suggested Activity": activity_suggestion
})
# Create a DataFrame from the summary data
df = pd.DataFrame(summary_data)
# Display the summary table
st.dataframe(df) # or use st.table(df) for a static table
# Provide additional suggestions at the end of all questions
st.write("### ๐ Final Suggestions")
st.write("Itโs great that you're exploring your emotions! Regular mindfulness practices, deep breathing exercises, and physical activities like walking can help keep your emotions in balance and improve overall well-being. ๐ฑ")
# ---- Footer ----
st.markdown(
"""
---
**Developed using ๐ค Transformers**
Designed for a fun and intuitive experience! ๐
"""
)
# ---- Error Handling and User Suggestions ----
if emotion_analyzer is None:
st.error("โ ๏ธ We couldn't load the emotion analysis model. Please check your internet connection or try again later.")
st.markdown("๐ง **Troubleshooting Steps:**")
st.markdown("1. Ensure you have a stable internet connection.")
st.markdown("2. If the issue persists, please refresh the page and try again.")
st.markdown("3. Check if the model has been updated or is temporarily unavailable.")
|