hackmebro commited on
Commit
87b5e15
Β·
verified Β·
1 Parent(s): e61f017

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +329 -54
app.py CHANGED
@@ -1,76 +1,351 @@
1
  import streamlit as st
2
- from transformers import pipeline
 
 
 
 
 
3
 
4
- st.set_page_config(page_title="Mental Wellness Diary Analyzer", page_icon="🧠")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  st.title("🧠 Mental Wellness Diary Analyzer")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Load a lightweight language model
8
- @st.cache_resource
9
- def load_model():
10
- return pipeline("text-generation", model="distilgpt2", max_new_tokens=200)
 
 
 
 
 
 
 
 
 
 
11
 
12
- generator = load_model()
13
 
14
- def analyze_journal(entry):
15
- prompt = f"""
16
- Analyze the following journal entry:
17
- "{entry}"
18
- Determine the following:
19
- 1. Emotional tone: [Identify the primary emotions]
20
- 2. Recurring themes: [Identify key themes]
21
- 3. Advice: [Provide encouraging advice]
22
  """
23
- output = generator(prompt)[0]["generated_text"]
24
 
25
- # Extract the analysis part
26
- analysis = output.split("Analyze the following journal entry:")[-1].strip()
 
 
 
 
 
 
 
27
 
28
- # Format the output in a cleaner way without JSON
29
- formatted_analysis = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  if "Emotional tone:" in analysis:
31
- emotional_tone = analysis.split("Emotional tone:")[1].split("Recurring themes:")[0].strip()
32
- formatted_analysis += f"😊 **Emotional tone:** {emotional_tone}\n\n"
 
 
 
 
 
 
 
33
 
34
- if "Recurring themes:" in analysis:
35
- themes = analysis.split("Recurring themes:")[1].split("Advice:")[0].strip()
36
- formatted_analysis += f"πŸ” **Recurring themes:** {themes}\n\n"
 
 
 
 
37
 
38
- if "Advice:" in analysis:
39
- advice = analysis.split("Advice:")[1].strip()
40
- formatted_analysis += f"πŸ’‘ **Advice:** {advice}"
41
 
42
- return formatted_analysis if formatted_analysis else analysis
43
-
44
- # User interface
45
- st.markdown("### Share what's on your mind today")
46
- journal_entry = st.text_area("✍️ Write your journal entry here:", height=150)
 
47
 
48
- col1, col2, col3 = st.columns([1, 1, 1])
49
- with col2:
50
- analyze_button = st.button("🧠 Analyze My Entry", use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- if analyze_button:
53
- if journal_entry.strip():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  with st.spinner("Analyzing your thoughts..."):
55
- result = analyze_journal(journal_entry)
56
-
57
  st.markdown("### πŸ’­ Your Wellness Insights")
58
- st.markdown(result)
 
 
 
 
 
59
 
60
- # Add some supportive message
61
  st.markdown("---")
62
  st.markdown("πŸ’ͺ **Remember**: Writing about your feelings is already a positive step for your mental wellness!")
63
- else:
64
- st.warning("Please share your thoughts in the journal entry box first.")
 
65
 
66
- # Add a sample entry option
67
- with st.expander("Need inspiration? Try a sample entry"):
68
- if st.button("Use sample entry"):
69
- sample_text = "I feel really stressed and anxious about my work. I haven't been sleeping well, and I'm worried about meeting deadlines."
70
- st.session_state["sample_text"] = sample_text
71
- st.experimental_rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- # Use sample if available in session state
74
- if "sample_text" in st.session_state:
75
- journal_entry = st.session_state["sample_text"]
76
- del st.session_state["sample_text"]
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ from datetime import datetime
4
+ import pandas as pd
5
+ import os
6
+ import uuid
7
+ import json
8
 
9
+ # Page configuration
10
+ st.set_page_config(
11
+ page_title="Mental Wellness Diary Analyzer",
12
+ page_icon="🧠",
13
+ layout="wide",
14
+ initial_sidebar_state="expanded"
15
+ )
16
+
17
+ # Custom CSS for better appearance
18
+ st.markdown("""
19
+ <style>
20
+ .main .block-container {
21
+ padding-top: 2rem;
22
+ padding-bottom: 2rem;
23
+ }
24
+ .stTextArea textarea {
25
+ font-size: 16px;
26
+ }
27
+ .journal-history {
28
+ border-left: 2px solid #f0f2f6;
29
+ padding-left: 20px;
30
+ }
31
+ .css-1v3fvcr {
32
+ background-color: #fcfcff;
33
+ }
34
+ .stButton button {
35
+ background-color: #4e89ae;
36
+ color: white;
37
+ border-radius: 5px;
38
+ padding: 0.5rem 1rem;
39
+ font-weight: bold;
40
+ }
41
+ .stButton button:hover {
42
+ background-color: #3d7092;
43
+ }
44
+ </style>
45
+ """, unsafe_allow_html=True)
46
+
47
+ # App title and description
48
  st.title("🧠 Mental Wellness Diary Analyzer")
49
+ st.markdown("""
50
+ Track your mental wellness journey with AI-powered insights. Write your daily thoughts,
51
+ and receive personalized analysis to help you understand your emotional patterns.
52
+ """)
53
+
54
+ # Initialize session state for journal entries
55
+ if 'journal_entries' not in st.session_state:
56
+ # Try to load from file if it exists
57
+ if os.path.exists('journal_entries.json'):
58
+ try:
59
+ with open('journal_entries.json', 'r') as f:
60
+ st.session_state.journal_entries = json.load(f)
61
+ except:
62
+ st.session_state.journal_entries = []
63
+ else:
64
+ st.session_state.journal_entries = []
65
+
66
+ # Hugging Face API setup
67
+ def get_hf_api_token():
68
+ # First check if token exists in secrets
69
+ if hasattr(st, 'secrets') and 'huggingface' in st.secrets:
70
+ return st.secrets["huggingface"]["api_token"]
71
+
72
+ # For local development, check environment variable
73
+ return os.environ.get("HF_API_TOKEN")
74
 
75
+ # Function to analyze journal entries
76
+ def analyze_journal(entry, model_name="deepseek-ai/deepseek-v1"):
77
+ api_token = get_hf_api_token()
78
+ if not api_token:
79
+ return "Error: No API token found. Please configure your Hugging Face API token in the Spaces secrets."
80
+
81
+ API_URL = f"https://api-inference.huggingface.co/models/{model_name}"
82
+
83
+ headers = {
84
+ "Authorization": f"Bearer {api_token}",
85
+ "Content-Type": "application/json",
86
+ }
87
+
88
+ prompt = f"""You are a compassionate mental wellness assistant. Analyze the following journal entry with empathy and provide helpful insights.
89
 
90
+ Journal entry: "{entry}"
91
 
92
+ Please provide:
93
+ 1. Emotional tone: Identify the primary emotions expressed in the entry (like anxious, happy, stressed, etc.)
94
+ 2. Recurring themes: Note any patterns or important topics mentioned
95
+ 3. Advice: Offer kind, supportive guidance tailored to what was shared
96
+
97
+ Format your response clearly with these exact headings (Emotional tone, Recurring themes, Advice) but without using JSON.
 
 
98
  """
 
99
 
100
+ payload = {
101
+ "inputs": prompt,
102
+ "parameters": {
103
+ "max_new_tokens": 300,
104
+ "temperature": 0.7,
105
+ "top_p": 0.95,
106
+ "do_sample": True
107
+ }
108
+ }
109
 
110
+ try:
111
+ response = requests.post(API_URL, headers=headers, json=payload)
112
+ response.raise_for_status()
113
+ result = response.json()
114
+
115
+ # Extract the text from the response
116
+ if isinstance(result, list) and len(result) > 0:
117
+ output = result[0].get("generated_text", "")
118
+ else:
119
+ output = str(result)
120
+
121
+ # Format the output nicely
122
+ formatted_output = ""
123
+
124
+ if "Emotional tone:" in output:
125
+ emotional_tone = output.split("Emotional tone:")[1].split("Recurring themes:")[0].strip()
126
+ formatted_output += f"😊 **Emotional tone:** {emotional_tone}\n\n"
127
+
128
+ if "Recurring themes:" in output:
129
+ themes = output.split("Recurring themes:")[1].split("Advice:")[0].strip()
130
+ formatted_output += f"πŸ” **Recurring themes:** {themes}\n\n"
131
+
132
+ if "Advice:" in output:
133
+ advice = output.split("Advice:")[1].strip()
134
+ formatted_output += f"πŸ’‘ **Advice:** {advice}"
135
+
136
+ return formatted_output if formatted_output else output
137
+
138
+ except requests.exceptions.RequestException as e:
139
+ st.error(f"API Error: {str(e)}")
140
+ if hasattr(e, 'response') and e.response is not None:
141
+ st.error(f"Response: {e.response.text}")
142
+ return f"Error connecting to the language model: {str(e)}"
143
+ except Exception as e:
144
+ return f"An unexpected error occurred: {str(e)}"
145
+
146
+ # Function to save an entry
147
+ def save_entry(entry, analysis):
148
+ entry_id = str(uuid.uuid4())
149
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
150
+
151
+ # Extract emotional tone for tagging (simplified)
152
+ emotional_tone = "neutral"
153
  if "Emotional tone:" in analysis:
154
+ tone_text = analysis.split("Emotional tone:")[1].split("\n\n")[0].strip()
155
+ if "anxious" in tone_text.lower() or "stress" in tone_text.lower():
156
+ emotional_tone = "anxious"
157
+ elif "happy" in tone_text.lower() or "joy" in tone_text.lower():
158
+ emotional_tone = "happy"
159
+ elif "sad" in tone_text.lower() or "depress" in tone_text.lower():
160
+ emotional_tone = "sad"
161
+ elif "angry" in tone_text.lower() or "frustrat" in tone_text.lower():
162
+ emotional_tone = "angry"
163
 
164
+ new_entry = {
165
+ "id": entry_id,
166
+ "date": timestamp,
167
+ "entry": entry,
168
+ "analysis": analysis,
169
+ "emotion": emotional_tone
170
+ }
171
 
172
+ st.session_state.journal_entries.append(new_entry)
 
 
173
 
174
+ # Save to file (for spaces persistence)
175
+ try:
176
+ with open('journal_entries.json', 'w') as f:
177
+ json.dump(st.session_state.journal_entries, f)
178
+ except Exception as e:
179
+ st.warning(f"Could not save entries to file: {str(e)}")
180
 
181
+ # Sidebar for navigation and settings
182
+ with st.sidebar:
183
+ st.header("Navigation")
184
+ page = st.radio("", ["Write New Entry", "View Journal History"])
185
+
186
+ st.header("Settings")
187
+ model_choice = st.selectbox(
188
+ "Language Model",
189
+ ["deepseek-ai/deepseek-v1", "meta-llama/Llama-2-13b-chat-hf", "google/flan-t5-xxl"],
190
+ index=0,
191
+ help="Select which AI model to use for analysis"
192
+ )
193
+
194
+ st.markdown("---")
195
+ st.markdown("### About")
196
+ st.info("""
197
+ This Mental Wellness Diary Analyzer helps you track your emotional wellbeing.
198
+ All entries are stored locally in your browser session.
199
+
200
+ **Disclaimer**: This app is not a substitute for professional mental health support.
201
+ """)
202
 
203
+ # Main content based on selected page
204
+ if page == "Write New Entry":
205
+ st.header("πŸ“ New Journal Entry")
206
+
207
+ # Current date display
208
+ st.markdown(f"**Today**: {datetime.now().strftime('%A, %B %d, %Y')}")
209
+
210
+ # Journal input
211
+ journal_entry = st.text_area(
212
+ "How are you feeling today?",
213
+ height=200,
214
+ placeholder="Write about your day, feelings, thoughts, or anything on your mind..."
215
+ )
216
+
217
+ # Mood tracker (optional quick selection)
218
+ cols = st.columns(5)
219
+ with cols[0]:
220
+ mood_happy = st.button("😊 Happy")
221
+ with cols[1]:
222
+ mood_calm = st.button("😌 Calm")
223
+ with cols[2]:
224
+ mood_anxious = st.button("😰 Anxious")
225
+ with cols[3]:
226
+ mood_sad = st.button("😒 Sad")
227
+ with cols[4]:
228
+ mood_angry = st.button("😠 Angry")
229
+
230
+ # Handle mood button clicks
231
+ mood_prefix = ""
232
+ if mood_happy:
233
+ mood_prefix = "I'm feeling happy today. "
234
+ elif mood_calm:
235
+ mood_prefix = "I'm feeling calm and relaxed today. "
236
+ elif mood_anxious:
237
+ mood_prefix = "I'm feeling anxious today. "
238
+ elif mood_sad:
239
+ mood_prefix = "I'm feeling sad today. "
240
+ elif mood_angry:
241
+ mood_prefix = "I'm feeling angry and frustrated today. "
242
+
243
+ if mood_prefix and not journal_entry.startswith(mood_prefix):
244
+ journal_entry = mood_prefix + journal_entry
245
+
246
+ # Analyze button
247
+ col1, col2, col3 = st.columns([1, 1, 1])
248
+ with col2:
249
+ analyze_button = st.button("🧠 Analyze My Entry", use_container_width=True)
250
+
251
+ # Sample entries
252
+ with st.expander("Need inspiration? Try a sample entry"):
253
+ sample_1 = st.button("Sample: Stressed at work")
254
+ sample_2 = st.button("Sample: Good day")
255
+ sample_3 = st.button("Sample: Relationship issues")
256
+
257
+ if sample_1:
258
+ journal_entry = "I feel really stressed and anxious about my work. I haven't been sleeping well, and I'm worried about meeting deadlines. My boss keeps adding more tasks, and I don't know how to say no."
259
+ elif sample_2:
260
+ journal_entry = "Today was a great day! I finished a project I've been working on for weeks, and my team was really impressed. I feel proud of myself and motivated to keep up the good work."
261
+ elif sample_3:
262
+ journal_entry = "I had an argument with my partner today. We've been fighting a lot lately about small things. I'm not sure if it's just stress or if there's a bigger issue we need to address."
263
+
264
+ # Analysis section
265
+ if analyze_button and journal_entry.strip():
266
  with st.spinner("Analyzing your thoughts..."):
267
+ analysis = analyze_journal(journal_entry, model_choice)
268
+
269
  st.markdown("### πŸ’­ Your Wellness Insights")
270
+ st.markdown(analysis)
271
+
272
+ # Save option
273
+ if st.button("πŸ“‹ Save this entry to your journal"):
274
+ save_entry(journal_entry, analysis)
275
+ st.success("Entry saved successfully!")
276
 
277
+ # Supportive message
278
  st.markdown("---")
279
  st.markdown("πŸ’ͺ **Remember**: Writing about your feelings is already a positive step for your mental wellness!")
280
+
281
+ elif analyze_button:
282
+ st.warning("Please write in your journal entry first.")
283
 
284
+ else: # View Journal History page
285
+ st.header("πŸ“š Your Journal History")
286
+
287
+ if not st.session_state.journal_entries:
288
+ st.info("You haven't saved any journal entries yet. Head to 'Write New Entry' to get started!")
289
+ else:
290
+ # Filter options
291
+ col1, col2 = st.columns(2)
292
+ with col1:
293
+ filter_option = st.selectbox(
294
+ "Filter by emotion:",
295
+ ["All", "happy", "anxious", "sad", "angry", "neutral"]
296
+ )
297
+ with col2:
298
+ sort_option = st.selectbox(
299
+ "Sort by:",
300
+ ["Newest first", "Oldest first"]
301
+ )
302
+
303
+ # Filter and sort entries
304
+ filtered_entries = st.session_state.journal_entries
305
+ if filter_option != "All":
306
+ filtered_entries = [e for e in filtered_entries if e.get("emotion") == filter_option]
307
+
308
+ if sort_option == "Newest first":
309
+ filtered_entries = sorted(filtered_entries, key=lambda x: x.get("date", ""), reverse=True)
310
+ else:
311
+ filtered_entries = sorted(filtered_entries, key=lambda x: x.get("date", ""))
312
+
313
+ # Display entries
314
+ for i, entry in enumerate(filtered_entries):
315
+ with st.expander(f"πŸ“ {entry.get('date', 'Unknown date')}"):
316
+ st.markdown("#### Journal Entry")
317
+ st.write(entry.get("entry", ""))
318
+
319
+ st.markdown("#### Analysis")
320
+ st.markdown(entry.get("analysis", "No analysis available"))
321
+
322
+ # Delete option
323
+ if st.button(f"πŸ—‘οΈ Delete this entry", key=f"delete_{i}"):
324
+ st.session_state.journal_entries.remove(entry)
325
+ with open('journal_entries.json', 'w') as f:
326
+ json.dump(st.session_state.journal_entries, f)
327
+ st.experimental_rerun()
328
+
329
+ # Add insights section if there are enough entries
330
+ if len(st.session_state.journal_entries) >= 3:
331
+ st.markdown("---")
332
+ st.header("πŸ“Š Emotional Trends")
333
+
334
+ # Create a dataframe for visualization
335
+ entries_df = pd.DataFrame(st.session_state.journal_entries)
336
+ entries_df['date'] = pd.to_datetime(entries_df['date'])
337
+
338
+ # Count emotions
339
+ emotion_counts = entries_df['emotion'].value_counts()
340
+ st.bar_chart(emotion_counts)
341
+
342
+ # Most common themes - this would require more sophisticated analysis
343
+ st.markdown("### Common Themes")
344
+ st.info("This feature will analyze common themes across your entries in a future update.")
345
 
346
+ # Footer
347
+ st.markdown("---")
348
+ st.caption("""
349
+ **Disclaimer**: This app is for educational purposes only and is not a substitute for professional mental health advice, diagnosis, or treatment.
350
+ Always seek the advice of your physician or other qualified health provider with any questions regarding a medical condition.
351
+ """)