tarrasyed19472007 commited on
Commit
dfe4a9e
ยท
verified ยท
1 Parent(s): 4e84761

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -105
app.py CHANGED
@@ -2,20 +2,22 @@ import streamlit as st
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}")
@@ -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("๐ŸŒง 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
- )
 
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.")