tarrasyed19472007 commited on
Commit
5f72fbb
Β·
verified Β·
1 Parent(s): bebf7e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -124
app.py CHANGED
@@ -1,55 +1,9 @@
1
  import streamlit as st
2
  from transformers import pipeline
3
  import torch
4
- import pandas as pd
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("Get emotional insights with tailored resources!")
17
-
18
- # ---- Function to Load Emotion Analysis Model ----
19
- @st.cache_resource
20
- def load_emotion_model():
21
- try:
22
- st.info("⏳ Loading the emotion analysis model, please wait...")
23
- # Using a publicly available model for emotion analysis
24
- emotion_analyzer = pipeline(
25
- "text-classification",
26
- model="bhadresh-savani/distilbert-base-uncased-emotion", # A valid public model
27
- device=0 if torch.cuda.is_available() else -1, # Use GPU if available
28
- )
29
- st.success("βœ… Model loaded successfully!")
30
- return emotion_analyzer
31
- except Exception as e:
32
- st.error(f"⚠️ Error loading model: {e}")
33
- return None
34
-
35
- # ---- Load the Model ----
36
- emotion_analyzer = load_emotion_model()
37
-
38
- # ---- Function for Predicting Emotion ----
39
- def predict_emotion(text):
40
- if emotion_analyzer is None:
41
- st.error("⚠️ Model not loaded. Please reload the app.")
42
- return {"Error": "Emotion analyzer model not initialized. Please try again later."}
43
-
44
- try:
45
- # Analyze emotions
46
- result = emotion_analyzer([text])
47
- return {res["label"]: round(res["score"], 4) for res in result}
48
- except Exception as e:
49
- st.error(f"⚠️ Prediction failed: {e}")
50
- return {"Error": f"Prediction failed: {e}"}
51
-
52
- # ---- Enhanced Suggestion Database ----
53
  suggestion_database = {
54
  "sadness": {
55
  "suggestions": ["Try a guided meditation", "Take a walk in nature", "Connect with a friend"],
@@ -77,11 +31,11 @@ suggestion_database = {
77
  "suggestions": ["Take a break", "Engage in a relaxing activity", "Spend time in nature"],
78
  "articles": [
79
  {"title": "Importance of Self-Care", "url": "https://example.com/selfcare1"},
80
- {"title": "Stress Management Techniques", "url": "https://example.com/stress1"}
81
  ],
82
  "videos": [
83
  {"title": "Relaxation Techniques", "url": "https://www.youtube.com/watch?v=relaxvideo1"},
84
- {"title": "Mindfulness Exercises", "url": "https://www.youtube.com/watch?v=mindfulnessvideo1"}
85
  ]
86
  }
87
  }
@@ -91,85 +45,107 @@ def get_relevant_resources(emotion):
91
  resources = suggestion_database.get(emotion, {})
92
  return resources.get("suggestions", []), resources.get("articles", []), resources.get("videos", [])
93
 
94
- # Enhanced Suggestion Function
95
- def suggest_activity(emotion_analysis):
96
- max_emotion = max(emotion_analysis, key=emotion_analysis.get) if emotion_analysis else "neutral"
97
- suggestions, articles, videos = get_relevant_resources(max_emotion)
98
- return {
99
- "suggestions": suggestions,
100
- "articles": articles,
101
- "videos": videos,
102
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- # ---- User Input Section ----
105
- st.write("### 🌺 Answer 3 Simple Questions!")
106
  questions = [
107
- "How are you feeling right now?",
108
- "What was the most significant emotion you experienced today?",
109
- "What helps you feel better when you’re stressed?"
110
  ]
111
 
 
112
  responses = {}
113
 
114
- # ---- Ask Questions and Analyze Responses ----
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  for i, question in enumerate(questions, start=1):
116
- st.write(f"#### ❓ Question {i}: {question}")
117
- user_response = st.text_input(f"Your answer to Q{i}:", key=f"q{i}")
118
-
119
  if user_response:
120
- with st.spinner("Analyzing emotion... 🎭"):
121
- analysis = predict_emotion(user_response)
122
- responses[question] = {"Response": user_response, "Analysis": analysis}
123
-
124
- # Display Emotion Analysis
125
- st.success(f"🎯 Emotion Analysis: {analysis}")
126
-
127
- # Display Activity Suggestion
128
- if analysis:
129
- max_emotion = max(analysis, key=analysis.get)
130
- activity_suggestion = suggest_activity(analysis)
131
- st.write(f"### 🧘 Suggested Activity: {activity_suggestion['suggestions'][0]}")
132
- st.write(f"πŸ“– Suggested Articles:")
133
- for article in activity_suggestion['articles']:
134
- st.markdown(f"- [{article['title']}]({article['url']})")
135
- st.write(f"πŸŽ₯ Suggested Videos:")
136
- for video in activity_suggestion['videos']:
137
- st.markdown(f"- [{video['title']}]({video['url']})")
138
-
139
- # ---- Display Summary Button ----
140
- if st.button("Get Summary"):
141
- st.write("### πŸ“Š Your Emotional Insights Summary")
142
-
143
- # Prepare the summary data
144
- summary_data = []
145
- for i, (question, details) in enumerate(responses.items(), start=1):
146
- max_emotion = max(details["Analysis"], key=details["Analysis"].get)
147
- activity_suggestion = suggest_activity(details["Analysis"])
148
-
149
- summary_data.append({
150
- "Question": question,
151
- "Your Response": details["Response"],
152
- "Emotion Analysis": max_emotion,
153
- "Suggested Activity": activity_suggestion["suggestions"][0],
154
- "Suggested Articles": ", ".join([article['title'] for article in activity_suggestion['articles']]),
155
- "Suggested Videos": ", ".join([video['title'] for video in activity_suggestion['videos']]),
156
- })
157
-
158
- # Create a DataFrame from the summary data
159
- df = pd.DataFrame(summary_data)
160
-
161
- # Display the summary table
162
- st.dataframe(df) # or use st.table(df) for a static table
163
-
164
- # Provide additional suggestions at the end of all questions
165
- st.write("### 🌟 Final Suggestions")
166
- st.write("Incorporating mindfulness, deep breathing, and spending time outdoors can help with emotional balance. Keep exploring activities that promote well-being! 🌱")
167
-
168
- # ---- Footer ----
169
- st.markdown(
170
- """
171
- ---
172
- **Developed using πŸ€— Transformers**
173
- Designed for a fun and intuitive experience! 🌟
174
- """
175
- )
 
1
  import streamlit as st
2
  from transformers import pipeline
3
  import torch
4
+ import time
5
 
6
+ # Enhanced Suggestion Database (Now includes resources)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  suggestion_database = {
8
  "sadness": {
9
  "suggestions": ["Try a guided meditation", "Take a walk in nature", "Connect with a friend"],
 
31
  "suggestions": ["Take a break", "Engage in a relaxing activity", "Spend time in nature"],
32
  "articles": [
33
  {"title": "Importance of Self-Care", "url": "https://example.com/selfcare1"},
34
+ {"title": "Stress Management Techniques", "url": "https://example.com/stress1"},
35
  ],
36
  "videos": [
37
  {"title": "Relaxation Techniques", "url": "https://www.youtube.com/watch?v=relaxvideo1"},
38
+ {"title": "Mindfulness Exercises", "url": "https://www.youtube.com/watch?v=mindfulnessvideo1"},
39
  ]
40
  }
41
  }
 
45
  resources = suggestion_database.get(emotion, {})
46
  return resources.get("suggestions", []), resources.get("articles", []), resources.get("videos", [])
47
 
48
+ # Function to load the model with error handling and retries
49
+ @st.cache_resource
50
+ def load_model():
51
+ try:
52
+ st.write("Attempting to load the emotion analysis model...")
53
+ # Using a smaller model for quick load times
54
+ emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta", device=0 if torch.cuda.is_available() else -1)
55
+ st.write("Model loaded successfully!")
56
+ return emotion_analyzer
57
+ except Exception as e:
58
+ st.write(f"Error loading the model: {e}")
59
+ return None
60
+
61
+ # Function to predict emotion for a single response
62
+ def predict_emotion_single(response, emotion_analyzer):
63
+ if emotion_analyzer is None:
64
+ st.error("Model not loaded. Please try reloading the app.")
65
+ return {"Error": "Emotion analyzer model not initialized. Please check model loading."}
66
+
67
+ try:
68
+ result = emotion_analyzer([response])
69
+ return {res["label"]: round(res["score"], 4) for res in result}
70
+ except Exception as e:
71
+ st.error(f"Prediction failed: {e}")
72
+ return {"Error": f"Prediction failed: {e}"}
73
+
74
+ # Streamlit App Layout
75
+ st.title("Emotion Prediction App: Your Personal Wellness Assistant")
76
+
77
+ st.write("**How it works:**")
78
+ st.write("- Enter your thoughts or feelings.")
79
+ st.write("- Our AI analyzes your text to predict your emotional state.")
80
+ st.write("- Receive personalized suggestions to improve your well-being.")
81
 
82
+ # Define questions for the user
 
83
  questions = [
84
+ "How are you feeling today?",
85
+ "Describe your mood in a few words.",
86
+ "What was the most significant emotion you felt this week?"
87
  ]
88
 
89
+ # Initialize a dictionary to store responses
90
  responses = {}
91
 
92
+ # Initialize the emotion analysis model with retries
93
+ emotion_analyzer = None
94
+ max_retries = 3
95
+ retry_delay = 5 # seconds
96
+
97
+ # Try loading the model with retries
98
+ for attempt in range(max_retries):
99
+ emotion_analyzer = load_model()
100
+ if emotion_analyzer:
101
+ break
102
+ if attempt < max_retries - 1:
103
+ st.warning(f"Retrying model load... Attempt {attempt + 2}/{max_retries}")
104
+ time.sleep(retry_delay)
105
+ else:
106
+ st.error("Model failed to load after multiple attempts. Please try again later.")
107
+
108
+ # Function to handle responses and emotion analysis
109
  for i, question in enumerate(questions, start=1):
110
+ user_response = st.text_input(f"Question {i}: {question}")
 
 
111
  if user_response:
112
+ analysis = predict_emotion_single(user_response, emotion_analyzer)
113
+ responses[question] = (user_response, analysis)
114
+ st.write(f"**Your Response**: {user_response}")
115
+ st.write(f"**Emotion Analysis**: {analysis}")
116
+
117
+ # Based on the emotion, suggest activities, articles, and videos
118
+ max_emotion = max(analysis, key=analysis.get) if analysis else "neutral"
119
+ suggestions, articles, videos = get_relevant_resources(max_emotion)
120
+
121
+ if suggestions:
122
+ st.write(f"### 🧘 Suggested Activity: {suggestions[0]}")
123
+ else:
124
+ st.write("### 🧘 No suggestions available at the moment.")
125
+
126
+ if articles:
127
+ st.write(f"### πŸ“š Suggested Articles:")
128
+ for article in articles:
129
+ st.write(f"[{article['title']}]({article['url']})")
130
+ else:
131
+ st.write("### πŸ“š No articles available at the moment.")
132
+
133
+ if videos:
134
+ st.write(f"### πŸŽ₯ Suggested Videos:")
135
+ for video in videos:
136
+ st.write(f"[{video['title']}]({video['url']})")
137
+ else:
138
+ st.write("### πŸŽ₯ No videos available at the moment.")
139
+
140
+ # Provide button to clear input fields
141
+ if st.button("Clear Responses"):
142
+ st.experimental_rerun()
143
+
144
+ # Display results once all responses are filled
145
+ if st.button("Submit Responses"):
146
+ if responses:
147
+ st.write("-- Emotion Analysis Results ---")
148
+ for i, (question, (response, analysis)) in enumerate(responses.items(), start=1):
149
+ st.write(f"**{question}**")
150
+ st.write(f"Response: {response}")
151
+ st.write(f"Emotion Analysis: {analysis}")