tarrasyed19472007 commited on
Commit
acd8491
·
verified ·
1 Parent(s): b394907

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -174
app.py CHANGED
@@ -1,198 +1,117 @@
1
  import streamlit as st
 
2
  from transformers import pipeline
3
 
4
- # Load emotion classification model
5
  @st.cache_resource
6
  def load_model():
7
- try:
8
- emotion_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
9
- return emotion_classifier
10
- except Exception as e:
11
- st.error(f"Error loading model: {str(e)}") # Error handling
12
- return None
13
 
14
- emotion_classifier = load_model()
15
 
16
- # Well-being suggestions based on emotions
17
- def get_well_being_suggestions(emotion):
18
- suggestions = {
19
- "joy": {
20
- "text": "You're feeling joyful! Keep the positivity going.",
21
- "links": [
22
- "https://www.nih.gov/health-information/emotional-wellness-toolkit",
23
- "https://www.health.harvard.edu/health-a-to-z",
24
- "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"
25
- ],
26
- "videos": [
27
- "https://youtu.be/m1vaUGtyo-A",
28
- "https://youtu.be/MIc299Flibs"
29
- ]
30
- },
31
- "anger": {
32
- "text": "You're feeling angry. Take a moment to calm down.",
33
- "links": [
34
- "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
35
- "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"
36
- ],
37
- "videos": [
38
- "https://youtu.be/m1vaUGtyo-A",
39
- "https://www.youtube.com/shorts/fwH8Ygb0K60?feature=share"
40
- ]
41
- },
42
- "sadness": {
43
- "text": "You're feeling sad. It's okay to take a break.",
44
- "links": [
45
- "https://www.nih.gov/health-information/emotional-wellness-toolkit",
46
- "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"
47
- ],
48
- "videos": [
49
- "https://youtu.be/-e-4Kx5px_I",
50
- "https://youtu.be/Y8HIFRPU6pM"
51
- ]
52
- },
53
- "fear": {
54
- "text": "You're feeling fearful. Try some relaxation techniques.",
55
- "links": [
56
- "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
57
- "https://www.health.harvard.edu/health-a-to-z"
58
- ],
59
- "videos": [
60
- "https://www.youtube.com/shorts/Tq49ajl7c8Q?feature=share",
61
- "https://youtu.be/yGKKz185M5o"
62
- ]
63
- },
64
- "disgust": {
65
- "text": "You're feeling disgusted. Take a deep breath and refocus.",
66
- "links": [
67
- "https://www.health.harvard.edu/health-a-to-z",
68
- "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"
69
- ],
70
- "videos": [
71
- "https://youtu.be/MIc299Flibs",
72
- "https://youtu.be/-e-4Kx5px_I"
73
- ]
74
- },
75
- # New addition for "Surprise"
76
- "surprise": {
77
- "text": "You're feeling surprised. Take a deep breath and ground yourself.",
78
- "links": [
79
- "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
80
- "https://www.health.harvard.edu/health-a-to-z",
81
- "https://www.psychologytoday.com/us/blog/mindful-anger/201908/5-ways-to-deal-with-unexpected-surprises"
82
- ],
83
- "videos": [
84
- "https://youtu.be/MIc299Flibs",
85
- "https://www.youtube.com/shorts/Tq49ajl7c8Q?feature=share",
86
- "https://youtu.be/m1vaUGtyo-A"
87
- ]
88
- },
89
- }
90
- return suggestions.get(emotion, {
91
- "text": "Feeling neutral? That's okay! Take care of your mental health.",
92
- "links": [],
93
- "videos": []
94
- })
95
 
96
- # Streamlit UI
97
- def main():
98
- # Add the background image
99
- st.markdown("""
100
  <style>
101
- .stApp {
102
  background-image: url('https://drive.google.com/uc?export=view&id=1TydbjDRL5fXLMxQgaPkIg9oGOJlU2IWt');
103
  background-size: cover;
104
- background-position: center;
105
- color: white; /* Set text color to white */
106
- }
107
-
108
- h1, h2, h3 {
109
  color: white;
110
- font-family: 'Arial', sans-serif;
111
  }
112
-
113
- .stTextArea textarea {
114
- background-color: #f2f2f2; /* Light grey text area */
115
- border-radius: 8px;
116
- color: #333333;
117
- }
118
-
119
  .stButton button {
120
- background-color: #9b4dca; /* Purple button */
121
  color: white;
122
- font-weight: bold;
123
- border-radius: 5px;
124
  }
 
 
 
 
125
 
126
- .stButton button:hover {
127
- background-color: #7a33a2; /* Darker purple on hover */
128
- }
129
 
130
- .stMarkdown, .stWrite {
131
- color: white !important;
132
- }
133
 
134
- /* Style for links to make them more visible */
135
- a {
136
- color: #ffffff;
137
- text-decoration: underline;
138
- }
139
- a:hover {
140
- color: #ffccff; /* Light purple hover effect */
141
- }
142
- </style>
143
- """, unsafe_allow_html=True)
144
-
145
- # Title of the app
146
- st.title("Emotion Prediction and Well-being Suggestions")
147
-
148
- # User input for emotional state
149
- st.header("Tell us how you're feeling today!")
150
-
151
- user_input = st.text_area("Enter a short sentence about your current mood:", "")
152
 
153
- if user_input:
154
- # Display Enter button only after user has entered input
155
- enter_button = st.button("Enter")
 
 
 
 
156
 
157
- if enter_button:
158
- # Clean the input text (stripping unnecessary spaces, lowercasing)
159
- clean_input = user_input.strip().lower()
160
-
161
- # Use the model to predict emotion
162
- try:
163
- result = emotion_classifier(clean_input)
164
- st.write(f"Raw Model Result: {result}") # Debug output to see raw result
165
-
166
- emotion = result[0]['label'].lower()
167
-
168
- st.subheader(f"Emotion Detected: {emotion.capitalize()}")
169
-
170
- # Get well-being suggestions based on emotion
171
- suggestions = get_well_being_suggestions(emotion)
172
-
173
- # Display text suggestions
174
- st.write(suggestions["text"])
175
 
176
- # Display links
177
- if suggestions["links"]:
178
- st.write("Useful Resources:")
179
- for link in suggestions["links"]:
180
- st.markdown(f"[{link}]({link})", unsafe_allow_html=True)
 
 
 
 
181
 
182
- # Display video links
183
- if suggestions["videos"]:
184
- st.write("Relaxation Videos:")
185
- for video in suggestions["videos"]:
186
- st.markdown(f"[Watch here]({video})", unsafe_allow_html=True)
187
-
188
- # Add a button for a summary
189
- if st.button('Summary'):
190
- st.write(f"Emotion detected: {emotion.capitalize()}. Here are your well-being suggestions to enhance your mood.")
191
- st.write("Explore the links and videos to improve your emotional health!")
192
-
193
- except Exception as e:
194
- st.error(f"Error predicting emotion: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
- # Run the Streamlit app
197
- if __name__ == "__main__":
198
- main()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  from transformers import pipeline
4
 
5
+ # Load pre-trained model and tokenizer
6
  @st.cache_resource
7
  def load_model():
8
+ tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
9
+ model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
10
+ return tokenizer, model
 
 
 
11
 
12
+ tokenizer, model = load_model()
13
 
14
+ # Set page configuration
15
+ st.set_page_config(page_title="Emotion Detection and Well-Being Suggestions", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Add a background image (use your own URL or file path here)
18
+ st.markdown(
19
+ """
 
20
  <style>
21
+ body {
22
  background-image: url('https://drive.google.com/uc?export=view&id=1TydbjDRL5fXLMxQgaPkIg9oGOJlU2IWt');
23
  background-size: cover;
24
+ background-repeat: no-repeat;
25
+ background-attachment: fixed;
 
 
 
26
  color: white;
 
27
  }
 
 
 
 
 
 
 
28
  .stButton button {
29
+ background-color: #6c63ff;
30
  color: white;
31
+ font-size: 20px;
 
32
  }
33
+ </style>
34
+ """,
35
+ unsafe_allow_html=True,
36
+ )
37
 
38
+ # Display header
39
+ st.title("Emotion Detection and Well-Being Suggestions")
 
40
 
41
+ # User input for text (emotion detection)
42
+ user_input = st.text_area("How are you feeling today?", "Enter your thoughts here...")
 
43
 
44
+ # Model prediction
45
+ if user_input:
46
+ pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
47
+ result = pipe(user_input)
48
+
49
+ # Extracting the emotion from the model's result
50
+ emotion = result[0]['label']
51
+
52
+ # Display emotion
53
+ st.write(f"**Emotion Detected:** {emotion}")
 
 
 
 
 
 
 
 
54
 
55
+ # Provide suggestions based on the detected emotion
56
+ if emotion == 'joy':
57
+ st.write("You're feeling happy! Keep up the great mood!")
58
+ st.write("Useful Resources:")
59
+ st.markdown("[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
60
+ st.write("[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
61
+ st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
62
 
63
+ st.write("Relaxation Videos:")
64
+ st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ elif emotion == 'anger':
67
+ st.write("You're feeling angry. It's okay to feel this way. Let's try to calm down.")
68
+ st.write("Useful Resources:")
69
+ st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
70
+ st.write("[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)")
71
+ st.write("[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
72
+
73
+ st.write("Relaxation Videos:")
74
+ st.markdown("[Watch on YouTube](https://youtu.be/MIc299Flibs)")
75
 
76
+ elif emotion == 'fear':
77
+ st.write("You're feeling fearful. Take a moment to breathe and relax.")
78
+ st.write("Useful Resources:")
79
+ st.markdown("[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
80
+ st.write("[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
81
+ st.write("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
82
+
83
+ st.write("Relaxation Videos:")
84
+ st.markdown("[Watch on YouTube](https://youtu.be/yGKKz185M5o)")
85
+
86
+ elif emotion == 'sadness':
87
+ st.write("You're feeling sad. It's okay to take a break.")
88
+ st.write("Useful Resources:")
89
+ st.markdown("[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)")
90
+ st.write("[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
91
+
92
+ st.write("Relaxation Videos:")
93
+ st.markdown("[Watch on YouTube](https://youtu.be/-e-4Kx5px_I)")
94
+
95
+ elif emotion == 'surprise':
96
+ st.write("You're feeling surprised. It's okay to feel neutral!")
97
+ st.write("Useful Resources:")
98
+ st.markdown("[Managing Stress](https://www.health.harvard.edu/health-a-to-z)")
99
+ st.write("[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
100
+
101
+ st.write("Relaxation Videos:")
102
+ st.markdown("[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)")
103
 
104
+ # Add a button for summary
105
+ if st.button("Show Summary"):
106
+ st.write(f"Emotion Detected: {emotion}")
107
+ st.write("Useful Resources based on your mood:")
108
+ if emotion == 'joy':
109
+ st.write("[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
110
+ elif emotion == 'anger':
111
+ st.write("[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)")
112
+ elif emotion == 'fear':
113
+ st.write("[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)")
114
+ elif emotion == 'sadness':
115
+ st.write("[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)")
116
+ elif emotion == 'surprise':
117
+ st.write("[Managing Stress](https://www.health.harvard.edu/health-a-to-z)")