tarrasyed19472007 commited on
Commit
6325706
Β·
verified Β·
1 Parent(s): dfe4a9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -71
app.py CHANGED
@@ -3,103 +3,99 @@ 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}")
24
  return None
25
 
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.")
 
 
 
 
 
 
 
 
 
 
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
+ )