-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.py
More file actions
213 lines (169 loc) · 5.83 KB
/
tracker.py
File metadata and controls
213 lines (169 loc) · 5.83 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
#!/usr/bin/env python3
"""
study-tracker — A CLI tool to track my 90-day coding journey.
Usage:
python tracker.py log <topic> <minutes>
python tracker.py streak
python tracker.py today
python tracker.py stats
python tracker.py countdown
Built by Maya. Day 14 of 90.
San Francisco, CA.
"""
import json
import sys
import os
from datetime import datetime, timedelta
from pathlib import Path
# ─── Config ───────────────────────────────────────────────────────
JOURNEY_START = datetime(2026, 1, 16)
JOURNEY_DAYS = 90
DATA_FILE = Path(__file__).parent / "sessions.json"
def load_sessions():
"""Load all logged sessions from the JSON file."""
if not DATA_FILE.exists():
return []
with open(DATA_FILE, "r") as f:
return json.load(f)
def save_sessions(sessions):
"""Save sessions back to the JSON file."""
with open(DATA_FILE, "w") as f:
json.dump(sessions, f, indent=2)
def log_session(topic, mins):
"""Log a study session with topic and duration."""
sessions = load_sessions()
today = datetime.now().strftime("%Y-%m-%d")
entry = {
"date": today,
"topic": topic,
"duration": mins
}
sessions.append(entry)
save_sessions(sessions)
print(f" ✓ Logged: {topic} ({mins} min)")
def get_streak():
"""Calculate the current daily streak."""
sessions = load_sessions()
if not sessions:
return 0
# Get unique dates, sorted descending
dates = sorted(set(s["date"] for s in sessions), reverse=True)
today = datetime.now().strftime("%Y-%m-%d")
# Streak must include today or yesterday
if dates[0] != today:
yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
if dates[0] != yesterday:
return 0
streak = 1
for i in range(len(dates) - 1):
current = datetime.strptime(dates[i], "%Y-%m-%d")
prev = datetime.strptime(dates[i + 1], "%Y-%m-%d")
if (current - prev).days == 1:
streak += 1
else:
break
return streak
def show_streak():
"""Display the current streak."""
streak = get_streak()
fire = "🔥" * min(streak, 10)
print(f"\n Streak: {streak} day{'s' if streak != 1 else ''} {fire}")
if streak >= 7:
print(" Achievement: Week Warrior 🏆")
if streak >= 14:
print(" Achievement: Two-Week Titan 💪")
print()
def show_today():
"""Show what was studied today."""
sessions = load_sessions()
today = datetime.now().strftime("%Y-%m-%d")
today_sessions = [s for s in sessions if s["date"] == today]
if not today_sessions:
print("\n No sessions logged today. Get to work! ☕\n")
return
total_mins = sum(s["duration"] for s in today_sessions)
print(f"\n Today ({today}):")
print(f" {'─' * 40}")
for s in today_sessions:
print(f" • {s['topic']} — {s['duration']} min")
print(f" {'─' * 40}")
print(f" Total: {total_mins} min\n")
def show_stats():
"""Show overall journey statistics."""
sessions = load_sessions()
if not sessions:
print("\n No sessions yet. Start with: python tracker.py log <topic> <minutes>\n")
return
total_sessions = len(sessions)
total_mins = sum(s["duration"] for s in sessions)
total_hours = total_mins / 60
unique_days = len(set(s["date"] for s in sessions))
unique_topics = len(set(s["topic"] for s in sessions))
# Topic breakdown
topic_mins = {}
for s in sessions:
topic_mins[s["topic"]] = topic_mins.get(s["topic"], 0) + s["duration"]
print(f"\n 📊 Journey Stats")
print(f" {'─' * 40}")
print(f" Sessions: {total_sessions}")
print(f" Study time: {total_hours:.1f} hours ({total_mins} min)")
print(f" Active days: {unique_days}")
print(f" Topics: {unique_topics}")
print(f" Streak: {get_streak()} days 🔥")
print(f" {'─' * 40}")
print(f" Top topics:")
sorted_topics = sorted(topic_mins.items(), key=lambda x: x[1], reverse=True)
for topic, mins in sorted_topics[:5]:
bar = "█" * (mins // 10)
print(f" {topic:<20} {mins:>4} min {bar}")
print()
def show_countdown():
"""Show days remaining in the 90-day challenge."""
today = datetime.now()
elapsed = (today - JOURNEY_START).days
remaining = JOURNEY_DAYS - elapsed
pct = min(elapsed / JOURNEY_DAYS * 100, 100)
# Progress bar
bar_len = 30
filled = int(bar_len * pct / 100)
bar = "█" * filled + "░" * (bar_len - filled)
print(f"\n 🎯 90-Day Challenge")
print(f" {'─' * 40}")
print(f" Day: {elapsed} of {JOURNEY_DAYS}")
print(f" Remaining: {max(remaining, 0)} days")
print(f" Progress: [{bar}] {pct:.0f}%")
if remaining > 0:
end_date = JOURNEY_START + timedelta(days=JOURNEY_DAYS)
print(f" Finish: {end_date.strftime('%B %d, %Y')}")
else:
print(f" 🏆 CHALLENGE COMPLETE!")
print()
def main():
if len(sys.argv) < 2:
print(__doc__)
return
command = sys.argv[1].lower()
if command == "log":
if len(sys.argv) < 4:
print(" Usage: python tracker.py log <topic> <minutes>")
return
topic = sys.argv[2]
try:
mins = int(sys.argv[3])
except ValueError:
print(" Error: minutes must be a number")
return
log_session(topic, mins)
elif command == "streak":
show_streak()
elif command == "today":
show_today()
elif command == "stats":
show_stats()
elif command == "countdown":
show_countdown()
else:
print(f" Unknown command: {command}")
print(__doc__)
if __name__ == "__main__":
main()