tarrasyed19472007 commited on
Commit
4e84761
·
verified ·
1 Parent(s): 2226c2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -49
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("Attempting to load the emotion analysis model...")
11
- # Using a smaller model for quick load times
12
- emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta", device=0 if torch.cuda.is_available() else -1)
13
- st.write("Model loaded successfully!")
 
 
 
14
  return emotion_analyzer
15
  except Exception as e:
16
- st.write(f"Error loading the model: {e}")
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.title("Behavior Prediction App")
35
- st.write("Enter your thoughts or feelings, and let the app predict your emotional states.")
36
 
37
- # Define questions for the user
38
- questions = [
39
- "How are you feeling today?",
40
- "Describe your mood in a few words.",
41
- "What was the most significant emotion you felt this week?",
42
- "How do you handle stress or challenges?",
43
- "What motivates you the most right now?"
44
- ]
 
 
 
 
 
 
45
 
46
- # Initialize a dictionary to store responses
47
- responses = {}
 
 
48
 
49
  # Initialize the emotion analysis model with retries
50
- emotion_analyzer = None
51
- max_retries = 3
52
- retry_delay = 5 # seconds
53
 
54
- # Try loading the model with retries
55
- for attempt in range(max_retries):
56
- emotion_analyzer = load_model()
57
- if emotion_analyzer:
58
- break
59
- if attempt < max_retries - 1:
60
- st.warning(f"Retrying model load... Attempt {attempt + 2}/{max_retries}")
61
- time.sleep(retry_delay)
62
- else:
63
- st.error("Model failed to load after multiple attempts. Please try again later.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # Function to handle responses and emotion analysis
66
- for i, question in enumerate(questions, start=1):
67
- user_response = st.text_input(f"Question {i}: {question}")
68
- if user_response:
69
- analysis = predict_emotion_single(user_response, emotion_analyzer)
70
- responses[question] = (user_response, analysis)
71
- st.write(f"**Your Response**: {user_response}")
72
- st.write(f"**Emotion Analysis**: {analysis}")
 
73
 
74
- # Provide button to clear input fields
75
- if st.button("Clear Responses"):
76
- st.experimental_rerun()
 
 
 
 
 
 
 
 
 
77
 
78
- # Display results once all responses are filled
79
- if st.button("Submit Responses"):
80
- if responses:
81
- st.write("-- Emotion Analysis Results ---")
82
- for i, (question, (response
 
 
 
 
 
 
 
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
+ )