-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.py
More file actions
663 lines (548 loc) · 22.8 KB
/
Copy pathtracker.py
File metadata and controls
663 lines (548 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import streamlit as st
import pandas as pd
from datetime import datetime, timedelta
import json
import os
import time
# Default themes
default_themes = {
"Default": {
"primary_color": "#FF5722",
"secondary_color": "#1E88E5",
"background_color": "#FFFFFF",
"text_color": "#212121"
},
"Dark Mode": {
"primary_color": "#FF9800",
"secondary_color": "#03A9F4",
"background_color": "#121212",
"text_color": "#E0E0E0"
},
"Nature": {
"primary_color": "#4CAF50",
"secondary_color": "#8BC34A",
"background_color": "#F1F8E9",
"text_color": "#33691E"
},
"Ocean": {
"primary_color": "#0288D1",
"secondary_color": "#26C6DA",
"background_color": "#E1F5FE",
"text_color": "#01579B"
}
}
def apply_theme(theme_name):
"""Apply the selected theme to the UI."""
all_themes = {**default_themes, **st.session_state.data['custom_themes']}
# Get the theme colors
theme = all_themes.get(theme_name, default_themes["Default"])
# Return the theme colors
return theme
def save_data():
"""Save session state data to a JSON file."""
try:
with open('tracker_data.json', 'w') as f:
json.dump(st.session_state.data, f)
return True
except Exception as e:
st.error(f"Error saving data: {e}")
return False
def load_data():
"""Load data from JSON file into session state."""
try:
if os.path.exists('tracker_data.json'):
with open('tracker_data.json', 'r') as f:
return json.load(f)
return {
'morning_checkins': {},
'evening_checkins': {},
'streak': 0,
'streak_freezes': 2,
'custom_themes': {}
}
except Exception as e:
st.error(f"Error loading data: {e}")
return {
'morning_checkins': {},
'evening_checkins': {},
'streak': 0,
'streak_freezes': 2,
'custom_themes': {}
}
# Modify your session state initialization to use the loaded data:
if 'data' not in st.session_state:
st.session_state.data = load_data()
# Page config and basic theme
st.set_page_config(
page_title="Daily Tracker",
layout="wide"
)
# Initialize session state for our data and form visibility
if 'data' not in st.session_state:
st.session_state.data = {
'morning_checkins': {},
'evening_checkins': {},
'streak': 0,
'streak_freezes': 2,
'custom_themes': {}
}
if 'show_morning_form' not in st.session_state:
st.session_state.show_morning_form = False
if 'show_evening_form' not in st.session_state:
st.session_state.show_evening_form = False
if 'streak_animation' not in st.session_state:
st.session_state.streak_animation = False
# Function to toggle morning form visibility
def toggle_morning_form():
st.session_state.show_morning_form = not st.session_state.show_morning_form
# Function to toggle evening form visibility
def toggle_evening_form():
st.session_state.show_evening_form = not st.session_state.show_evening_form
# Function to check if both check-ins are completed for today
def check_day_completion():
today = datetime.now().strftime("%Y-%m-%d")
if (today in st.session_state.data['morning_checkins'] and
today in st.session_state.data['evening_checkins'] and
not st.session_state.streak_animation):
# Set flag to show animation
st.session_state.streak_animation = True
return True
return False
# Function to update streak with animation
def update_streak():
# Save the old streak for comparison
old_streak = st.session_state.data['streak']
# Increment streak
st.session_state.data['streak'] += 1
new_streak = st.session_state.data['streak']
# Show celebration
st.balloons() # or st.snow() for a different effect
# Create a placeholder for the animation
streak_placeholder = st.empty()
# Show animation
with streak_placeholder.container():
st.write(f"🔥 Streak increasing from {old_streak} to {new_streak}!")
# Show progress bar filling up
progress_bar = st.progress(0)
for i in range(101):
progress_bar.progress(i)
time.sleep(0.01) # Adjust speed of animation
# Show milestone messages for certain streak values
if new_streak in [7, 14, 30, 50, 100]:
st.success(f"🎉 Amazing! You've reached a {new_streak} day streak!")
# If we reached 3 days in a row and have less than 2 freezes, award one
if new_streak % 3 == 0 and st.session_state.data['streak_freezes'] < 2:
st.session_state.data['streak_freezes'] += 1
st.info(f"❄️ You earned a streak freeze! You now have {st.session_state.data['streak_freezes']} freezes.")
# Reset animation flag for next day
st.session_state.streak_animation = False
# Top bar with three columns
col1, col2, col3, col4 = st.columns([1, 1, 2, 1])
with col2:
# Theme selector
themes = list({**default_themes, **st.session_state.data['custom_themes']}.keys())
selected_theme = st.selectbox("Theme:", options=themes, index=0, key="theme_selector",on_change=lambda: st.rerun())
theme = apply_theme(selected_theme)
with col3:
st.title("Daily Tracker")
with col4:
current_time = datetime.now()
st.write("Current time:", current_time.strftime("%I:%M %p"))
st.write("Current date:", current_time.strftime("%B %d, %Y"))
# Apply theme to streak display and other elements
# Replace your streak display code with:
with col1:
# Get theme colors
theme = apply_theme(st.session_state.theme_selector)
# Enhanced streak display with theme colors
st.markdown(
f"""
<div style='background-color: {theme['primary_color']}22; padding: 10px; border-radius: 10px; text-align: center;'>
<h2 style='margin:0; color: {theme['primary_color']};'>🔥 {st.session_state.data['streak']}</h2>
<p style='margin:0; color: {theme['text_color']};'>day streak</p>
</div>
""",
unsafe_allow_html=True
)
st.markdown(
f"""
<div style='background-color: {theme['secondary_color']}22; padding: 10px; border-radius: 10px; text-align: center; margin-top: 10px;'>
<h3 style='margin:0; color: {theme['secondary_color']};'>❄️ {st.session_state.data['streak_freezes']}</h3>
<p style='margin:0; color: {theme['text_color']};'>freezes</p>
</div>
""",
unsafe_allow_html=True
)
# Check if we need to show streak animation
if check_day_completion():
update_streak()
# Create tabs for different sections
tab1, tab2, tab3 = st.tabs(["Check-ins", "Calendar", "Settings"])
with tab1:
# Morning check-in section
st.subheader("Morning Check-in")
# Check if within grace period (before 1 PM)
if datetime.now().hour < 13:
if st.button("Open Morning Check-in", on_click=toggle_morning_form):
pass
# Show form if button was clicked
if st.session_state.show_morning_form:
with st.form("morning_checkin"):
st.write("How did you sleep?")
# Sleep duration input
col1, col2 = st.columns(2)
with col1:
hours = st.number_input("Hours:", min_value=0, max_value=12, value=7)
with col2:
minutes = st.number_input("Minutes:", min_value=0, max_value=59, value=0)
# Sleep quality rating
sleep_quality = st.slider(
"Rate your sleep quality:",
min_value=1,
max_value=10,
value=5,
help="1 = Terrible, 10 = Amazing"
)
# Submit button
submitted = st.form_submit_button("Save Morning Check-in")
if submitted:
# Get today's date as string
today = datetime.now().strftime("%Y-%m-%d")
# Save the data
st.session_state.data['morning_checkins'][today] = {
'sleep_hours': hours,
'sleep_minutes': minutes,
'sleep_quality': sleep_quality,
'timestamp': datetime.now().strftime("%H:%M")
}
st.success("Morning check-in saved!")
st.session_state.show_morning_form = False # Hide the form
# Check if day is complete after saving
check_day_completion()
#save data to file
save_data()
else:
st.error("Morning check-in is only available until 1 PM")
# Evening check-in section
st.subheader("Evening Check-in")
# Check if within grace period (after 5 PM or before 10 AM next day)
if datetime.now().hour >= 17 or datetime.now().hour < 10:
if st.button("Open Evening Check-in", on_click=toggle_evening_form):
pass
# Show form if button was clicked
if st.session_state.show_evening_form:
with st.form("evening_checkin"):
st.write("How was your day?")
# Productivity rating (thumbs up/down)
productivity = st.radio(
"Rate your productivity:",
options=["👍 Good", "👎 Bad"],
horizontal=True
)
# Happiness rating
happiness = st.slider(
"Rate your happiness/mood today:",
min_value=1,
max_value=10,
value=5,
help="1 = Very unhappy, 10 = Very happy"
)
# Submit button
submitted = st.form_submit_button("Save Evening Check-in")
if submitted:
# Get today's date as string
today = datetime.now().strftime("%Y-%m-%d")
# Save the data
st.session_state.data['evening_checkins'][today] = {
'productivity': "good" if productivity == "👍 Good" else "bad",
'happiness': happiness,
'timestamp': datetime.now().strftime("%H:%M")
}
st.success("Evening check-in saved!")
st.session_state.show_evening_form = False # Hide the form
# Check if day is complete after saving
check_day_completion()
#save data to file
save_data()
else:
st.error("Evening check-in is only available after 5 PM")
# Show saved data for testing
with tab2:
st.subheader("Calendar View")
# Get current month and year for default view
today = datetime.now()
default_month = today.month
default_year = today.year
# Month/year selector with improved layout
col1, col2, spacer = st.columns([1, 1, 2])
with col1:
month = st.selectbox(
"Month:",
options=range(1, 13),
format_func=lambda x: datetime(2000, x, 1).strftime("%B"),
index=default_month-1
)
with col2:
year = st.selectbox(
"Year:",
options=range(today.year-1, today.year+2),
index=1
)
# Generate calendar for selected month/year
cal_start_date = datetime(year, month, 1)
month_name = cal_start_date.strftime("%B")
# Display month and year as a header
st.markdown(f"<h3 style='text-align:center; margin-bottom:15px;'>{month_name} {year}</h3>", unsafe_allow_html=True)
# Determine the number of days in the month
if month == 12:
next_month = datetime(year+1, 1, 1)
else:
next_month = datetime(year, month+1, 1)
days_in_month = (next_month - timedelta(days=1)).day
# Determine the day of the week of the first day (0 = Monday, 6 = Sunday)
first_day_weekday = cal_start_date.weekday()
# Adjust for Sunday as the first day of the week
if first_day_weekday == 6:
first_day_weekday = 0
else:
first_day_weekday += 1
# Generate weekly rows for the calendar
weeks = []
current_week = [None] * first_day_weekday + list(range(1, min(8-first_day_weekday, days_in_month+1)))
day = len(current_week)
while day <= days_in_month:
if len(current_week) == 7:
weeks.append(current_week)
current_week = []
current_week.append(day)
day += 1
# Pad the last week
if current_week:
current_week += [None] * (7 - len(current_week))
weeks.append(current_week)
# Function to determine check-in status color
def get_day_color(day):
if day is None:
return "transparent"
date_str = f"{year}-{month:02d}-{day:02d}"
morning_completed = date_str in st.session_state.data['morning_checkins']
evening_completed = date_str in st.session_state.data['evening_checkins']
# Today's date should be highlighted differently
is_today = date_str == datetime.now().strftime("%Y-%m-%d")
if is_today:
# Highlight today with a border
if morning_completed and evening_completed:
return "#C8E6C9", "#388E3C", "2px solid #388E3C" # Green with darker border
elif morning_completed:
return "#FFF9C4", "#FBC02D", "2px solid #FBC02D" # Yellow with darker border
elif evening_completed:
return "#BBDEFB", "#1976D2", "2px solid #1976D2" # Blue with darker border
else:
return "#F5F5F5", "#616161", "2px solid #616161" # Gray with darker border
else:
# Regular coloring for other days
if morning_completed and evening_completed:
return "#C8E6C9", "black", "none" # Green
elif morning_completed:
return "#FFF9C4", "black", "none" # Yellow
elif evening_completed:
return "#BBDEFB", "black", "none" # Blue
else:
return "#F5F5F5", "black", "none" # Gray
# Function to generate day content
def get_day_content(day):
if day is None:
return ""
date_str = f"{year}-{month:02d}-{day:02d}"
morning_data = st.session_state.data['morning_checkins'].get(date_str, {})
evening_data = st.session_state.data['evening_checkins'].get(date_str, {})
content_parts = [f"""
<div class="day-content">
<div class="day-number">{day}</div>
<div class="day-data">
"""]
# Morning data
if morning_data:
sleep_hours = morning_data.get('sleep_hours', 0)
sleep_minutes = morning_data.get('sleep_minutes', 0)
sleep_quality = morning_data.get('sleep_quality', 0)
total_sleep = sleep_hours + (sleep_minutes / 60)
content_parts.append(f"""
<div class="morning-data">
<div>🛌 {sleep_hours}h {sleep_minutes}m</div>
<div>✨ {sleep_quality}/10</div>
</div>
""")
# Evening data
if evening_data:
productivity = evening_data.get('productivity', '')
happiness = evening_data.get('happiness', 0)
prod_icon = "👍" if productivity == "good" else "👎"
content_parts.append(f"""
<div class="evening-data">
<div>{prod_icon} Prod</div>
<div>😊 {happiness}/10</div>
</div>
""")
content_parts.append("</div></div>")
return ''.join(content_parts)
# Add custom CSS for better calendar styling
st.markdown("""
<style>
.calendar-day {
min-height: 90px;
border-radius: 5px;
padding: 5px;
margin: 2px;
position: relative;
}
.day-content {
height: 100%;
display: flex;
flex-direction: column;
}
.day-number {
text-align: right;
font-size: 1.2em;
font-weight: bold;
padding: 2px;
margin-bottom: 3px;
}
.day-data {
display: flex;
flex-direction: column;
flex-grow: 1;
font-size: 0.8em;
}
.morning-data {
border-bottom: 1px solid rgba(0,0,0,0.1);
padding: 2px 0;
}
.evening-data {
padding: 2px 0;
}
.calendar-header {
text-align: center;
font-weight: bold;
padding: 5px;
background-color: #f0f0f0;
border-radius: 5px;
margin: 2px;
}
</style>
""", unsafe_allow_html=True)
# Display the weekday headers
weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
cols = st.columns(7)
for i, col in enumerate(cols):
with col:
st.markdown(f'<div class="calendar-header">{weekdays[i]}</div>', unsafe_allow_html=True)
# Display the calendar
for week in weeks:
cols = st.columns(7)
for i, day in enumerate(week):
with cols[i]:
if day is not None:
color, text_color, border = get_day_color(day)
content = get_day_content(day)
st.markdown(
f"""
<div class="calendar-day" style="background-color:{color}; border:{border}; color:{text_color};">
{content}
</div>
""",
unsafe_allow_html=True
)
else:
# Empty cell
st.markdown('<div class="calendar-day" style="background-color:transparent;"></div>', unsafe_allow_html=True)
# Add a color legend
st.write("---")
legend_col1, legend_col2, legend_col3, legend_col4 = st.columns(4)
with legend_col1:
st.markdown(
"""
<div style='display:flex; align-items:center;'>
<div style='background-color:#F5F5F5; width:20px; height:20px; margin-right:10px; border-radius:3px;'></div>
<span>No Data</span>
</div>
""",
unsafe_allow_html=True
)
with legend_col2:
st.markdown(
"""
<div style='display:flex; align-items:center;'>
<div style='background-color:#FFF9C4; width:20px; height:20px; margin-right:10px; border-radius:3px;'></div>
<span>Morning Only</span>
</div>
""",
unsafe_allow_html=True
)
with legend_col3:
st.markdown(
"""
<div style='display:flex; align-items:center;'>
<div style='background-color:#BBDEFB; width:20px; height:20px; margin-right:10px; border-radius:3px;'></div>
<span>Evening Only</span>
</div>
""",
unsafe_allow_html=True
)
with legend_col4:
st.markdown(
"""
<div style='display:flex; align-items:center;'>
<div style='background-color:#C8E6C9; width:20px; height:20px; margin-right:10px; border-radius:3px;'></div>
<span>Complete Day</span>
</div>
""",
unsafe_allow_html=True
)
with tab3:
st.subheader("Settings")
# Theme settings
st.subheader("Custom Themes")
# Merge default and custom themes
all_themes = {**default_themes, **st.session_state.data['custom_themes']}
# Select theme
selected_theme = st.selectbox(
"Select Theme:",
options=list(all_themes.keys()),
index=0
)
# Show selected theme details
st.write("Current Theme Colors:")
theme_data = all_themes[selected_theme]
cols = st.columns(4)
with cols[0]:
st.color_picker("Primary Color", theme_data["primary_color"], key="primary_color_view", disabled=True)
with cols[1]:
st.color_picker("Secondary Color", theme_data["secondary_color"], key="secondary_color_view", disabled=True)
with cols[2]:
st.color_picker("Background Color", theme_data["background_color"], key="background_color_view", disabled=True)
with cols[3]:
st.color_picker("Text Color", theme_data["text_color"], key="text_color_view", disabled=True)
# Create new theme
st.subheader("Create New Theme")
with st.form("new_theme_form"):
theme_name = st.text_input("Theme Name:")
col1, col2 = st.columns(2)
with col1:
primary_color = st.color_picker("Primary Color (Streak, Buttons)", "#FF5722")
background_color = st.color_picker("Background Color", "#FFFFFF")
with col2:
secondary_color = st.color_picker("Secondary Color (Freezes)", "#1E88E5")
text_color = st.color_picker("Text Color", "#212121")
submitted = st.form_submit_button("Save New Theme")
if submitted and theme_name:
# Save new theme
st.session_state.data['custom_themes'][theme_name] = {
"primary_color": primary_color,
"secondary_color": secondary_color,
"background_color": background_color,
"text_color": text_color
}
# Save data
save_data()
st.success(f"Theme '{theme_name}' saved!")