-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
498 lines (372 loc) · 13.1 KB
/
utils.py
File metadata and controls
498 lines (372 loc) · 13.1 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
"""
Utility functions for the productivity tracker.
This module contains helper functions for time formatting, validation,
date operations, and other common utilities used throughout the application.
"""
import re
from datetime import datetime, date, timedelta
from typing import Optional, List, Tuple, Union
def validate_duration(duration_input: str) -> bool:
"""
Validate if a duration string is in a valid format.
Args:
duration_input: Duration string to validate (e.g., "2h 30m", "150m", "2.5h")
Returns:
bool: True if duration is valid, False otherwise
"""
if not duration_input or not duration_input.strip():
return False
# Remove extra spaces
duration = duration_input.strip().lower()
# Check for various formats
patterns = [
r'^\d+\.?\d*\s*h\s*\d*\.?\d*\s*m?$', # "2h 30m" or "2.5h"
r'^\d+\.?\d*\s*m$', # "150m"
r'^\d+\.?\d*\s*h$', # "2h"
r'^\d+$' # "150" (assumed minutes)
]
return any(re.match(pattern, duration) for pattern in patterns)
def parse_duration(duration_input: str) -> int:
"""
Parse a duration string and return total minutes.
Args:
duration_input: Duration string (e.g., "2h 30m", "150m", "2.5h")
Returns:
int: Total duration in minutes
Raises:
ValueError: If duration string is invalid
"""
if not duration_input or not duration_input.strip():
raise ValueError("Duration cannot be empty")
duration = duration_input.strip().lower()
total_minutes = 0
# Handle hours and minutes format (e.g., "2h 30m", "2.5h")
if 'h' in duration:
hour_match = re.search(r'(\d+\.?\d*)\s*h', duration)
if hour_match:
hours = float(hour_match.group(1))
total_minutes += int(hours * 60)
# Handle minutes format (e.g., "30m", "150m")
if 'm' in duration:
minute_match = re.search(r'(\d+\.?\d*)\s*m', duration)
if minute_match:
minutes = float(minute_match.group(1))
total_minutes += int(minutes)
# Handle pure number (assumed minutes)
if not ('h' in duration or 'm' in duration):
try:
total_minutes = int(float(duration))
except ValueError:
raise ValueError(f"Invalid duration format: {duration_input}")
if total_minutes <= 0:
raise ValueError("Duration must be positive")
return total_minutes
def format_duration(minutes: int) -> str:
"""
Format minutes into a human-readable duration string.
Args:
minutes: Duration in minutes
Returns:
str: Formatted duration string (e.g., "2h 30m", "45m")
"""
if minutes < 60:
return f"{minutes}m"
hours = minutes // 60
remaining_minutes = minutes % 60
if remaining_minutes == 0:
return f"{hours}h"
else:
return f"{hours}h {remaining_minutes}m"
def validate_focus_score(score: Union[int, str]) -> bool:
"""
Validate if a focus score is within the valid range (1-10).
Args:
score: Focus score to validate
Returns:
bool: True if score is valid, False otherwise
"""
try:
score_int = int(score)
return 1 <= score_int <= 10
except (ValueError, TypeError):
return False
def parse_focus_score(score_input: str) -> int:
"""
Parse a focus score string and return an integer.
Args:
score_input: Focus score string
Returns:
int: Parsed focus score
Raises:
ValueError: If score is invalid
"""
try:
score = int(score_input.strip())
if not validate_focus_score(score):
raise ValueError("Focus score must be between 1 and 10")
return score
except ValueError as e:
if "invalid literal" in str(e):
raise ValueError("Focus score must be a number between 1 and 10")
raise
def get_current_date_string() -> str:
"""
Get current date as a string in YYYY-MM-DD format.
Returns:
str: Current date string
"""
return date.today().strftime('%Y-%m-%d')
def validate_date(date_string: str) -> bool:
"""
Validate if a date string is in the correct format (YYYY-MM-DD).
Args:
date_string: Date string to validate
Returns:
bool: True if date is valid, False otherwise
"""
if not date_string:
return False
# Check format with regex
date_pattern = r'^\d{4}-\d{2}-\d{2}$'
if not re.match(date_pattern, date_string):
return False
try:
# Try to parse the date
datetime.strptime(date_string, '%Y-%m-%d')
return True
except ValueError:
return False
def format_date(date_string: str, input_format: str = '%Y-%m-%d', output_format: str = '%B %d, %Y') -> str:
"""
Format a date string from one format to another.
Args:
date_string: Date string to format
input_format: Format of the input date string
output_format: Desired output format
Returns:
str: Formatted date string
Raises:
ValueError: If date string is invalid
"""
try:
date_obj = datetime.strptime(date_string, input_format)
return date_obj.strftime(output_format)
except ValueError as e:
raise ValueError(f"Invalid date format: {e}")
def get_week_start_date(target_date: str) -> str:
"""
Get the start date of the week (Monday) for a given date.
Args:
target_date: Date in YYYY-MM-DD format
Returns:
str: Start date of the week in YYYY-MM-DD format
"""
if not validate_date(target_date):
raise ValueError("Invalid date format")
date_obj = datetime.strptime(target_date, '%Y-%m-%d').date()
# Get Monday of the week (weekday() returns 0 for Monday)
days_since_monday = date_obj.weekday()
monday = date_obj - timedelta(days=days_since_monday)
return monday.strftime('%Y-%m-%d')
def get_week_end_date(target_date: str) -> str:
"""
Get the end date of the week (Sunday) for a given date.
Args:
target_date: Date in YYYY-MM-DD format
Returns:
str: End date of the week in YYYY-MM-DD format
"""
if not validate_date(target_date):
raise ValueError("Invalid date format")
date_obj = datetime.strptime(target_date, '%Y-%m-%d').date()
# Get Sunday of the week (weekday() returns 6 for Sunday)
days_until_sunday = 6 - date_obj.weekday()
sunday = date_obj + timedelta(days=days_until_sunday)
return sunday.strftime('%Y-%m-%d')
def get_date_range_days(start_date: str, end_date: str) -> int:
"""
Calculate the number of days between two dates.
Args:
start_date: Start date in YYYY-MM-DD format
end_date: End date in YYYY-MM-DD format
Returns:
int: Number of days between dates
"""
if not validate_date(start_date) or not validate_date(end_date):
raise ValueError("Invalid date format")
start = datetime.strptime(start_date, '%Y-%m-%d').date()
end = datetime.strptime(end_date, '%Y-%m-%d').date()
return (end - start).days
def is_date_in_range(check_date: str, start_date: str, end_date: str) -> bool:
"""
Check if a date falls within a given range.
Args:
check_date: Date to check in YYYY-MM-DD format
start_date: Start of range in YYYY-MM-DD format
end_date: End of range in YYYY-MM-DD format
Returns:
bool: True if date is in range, False otherwise
"""
if not all(validate_date(d) for d in [check_date, start_date, end_date]):
raise ValueError("Invalid date format")
check = datetime.strptime(check_date, '%Y-%m-%d').date()
start = datetime.strptime(start_date, '%Y-%m-%d').date()
end = datetime.strptime(end_date, '%Y-%m-%d').date()
return start <= check <= end
def get_common_categories() -> List[str]:
"""
Get a list of common task categories.
Returns:
List[str]: List of common categories
"""
return [
"Work",
"Study",
"Exercise",
"Personal",
"Household",
"Creative",
"Learning",
"Health",
"Social",
"Hobby",
"Other"
]
def validate_task_name(name: str) -> bool:
"""
Validate task name.
Args:
name: Name to validate
Returns:
bool: True if name is valid, False otherwise
"""
if not name or not name.strip():
return False
# Check for reasonable length
if len(name.strip()) < 1 or len(name.strip()) > 200:
return False
return True
def validate_category(category: str) -> bool:
"""
Validate task category.
Args:
category: Category to validate
Returns:
bool: True if category is valid, False otherwise
"""
if not category or not category.strip():
return False
# Check for reasonable length
if len(category.strip()) < 1 or len(category.strip()) > 50:
return False
return True
def truncate_string(text: str, max_length: int = 30) -> str:
"""
Truncate a string to a maximum length with ellipsis.
Args:
text: Text to truncate
max_length: Maximum length of the result
Returns:
str: Truncated string with ellipsis if needed
"""
if len(text) <= max_length:
return text
return text[:max_length - 3] + "..."
def format_table_row(data: List[str], widths: List[int]) -> str:
"""
Format a row of data for table display.
Args:
data: List of strings to format
widths: List of column widths
Returns:
str: Formatted table row
"""
if len(data) != len(widths):
raise ValueError("Data and widths lists must have the same length")
formatted_cells = []
for i, (cell, width) in enumerate(zip(data, widths)):
# Truncate if too long
if len(cell) > width:
cell = truncate_string(cell, width)
# Pad with spaces
formatted_cells.append(cell.ljust(width))
return " | ".join(formatted_cells)
def calculate_productivity_score(duration_minutes: int, focus_score: int) -> float:
"""
Calculate a productivity score based on duration and focus.
Args:
duration_minutes: Duration of the task in minutes
focus_score: Focus score from 1-10
Returns:
float: Productivity score
"""
# Simple algorithm: duration (in hours) * focus_score
duration_hours = duration_minutes / 60
return duration_hours * focus_score
def get_time_of_day() -> str:
"""
Get current time of day as a string.
Returns:
str: Time of day (Morning, Afternoon, Evening, Night)
"""
current_hour = datetime.now().hour
if 5 <= current_hour < 12:
return "Morning"
elif 12 <= current_hour < 17:
return "Afternoon"
elif 17 <= current_hour < 21:
return "Evening"
else:
return "Night"
def format_time_elapsed(start_time: datetime, end_time: Optional[datetime] = None) -> str:
"""
Format elapsed time between two datetime objects.
Args:
start_time: Start datetime
end_time: End datetime (defaults to now)
Returns:
str: Formatted elapsed time
"""
if end_time is None:
end_time = datetime.now()
elapsed = end_time - start_time
total_seconds = int(elapsed.total_seconds())
if total_seconds < 60:
return f"{total_seconds}s"
elif total_seconds < 3600:
minutes = total_seconds // 60
seconds = total_seconds % 60
return f"{minutes}m {seconds}s"
else:
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
return f"{hours}h {minutes}m"
def get_weekday_name(date_string: str) -> str:
"""
Get the weekday name for a given date.
Args:
date_string: Date in YYYY-MM-DD format
Returns:
str: Weekday name
"""
if not validate_date(date_string):
raise ValueError("Invalid date format")
date_obj = datetime.strptime(date_string, '%Y-%m-%d').date()
return date_obj.strftime('%A')
def get_short_weekday_name(date_string: str) -> str:
"""
Get the short weekday name for a given date.
Args:
date_string: Date in YYYY-MM-DD format
Returns:
str: Short weekday name (Mon, Tue, etc.)
"""
if not validate_date(date_string):
raise ValueError("Invalid date format")
date_obj = datetime.strptime(date_string, '%Y-%m-%d').date()
return date_obj.strftime('%a')
# TODO: Fix occasional bug: chart not updating if data added after chart generation
# TODO: Add Export Reports to Excel or PDF feature
# TODO: Integrate Rich library for colored CLI output
# TODO: Add Daily Goal Tracker (target hours per day)
# TODO: Implement Unit Tests for utils.py functions