-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
401 lines (307 loc) · 12.2 KB
/
Copy pathutils.py
File metadata and controls
401 lines (307 loc) · 12.2 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
"""
Utility module for MultiAPI Dashboard.
Provides UI helpers including the ASCII banner, progress spinner,
ANSI color wrappers, input validation, number formatting, and
table display helpers.
"""
import itertools
import os
import sys
import threading
import time
from typing import Any, Dict, List, Optional
from config import Colors
# ============================================================
# ASCII Art Banner
# ============================================================
BANNER = f"""
{Colors.BRIGHT_CYAN}{Colors.BOLD}
╔══════════════════════════════════════════════════════════════╗
║ ║
║ ███╗ ███╗██╗ ██╗██╗ ████████╗██╗ █████╗ ██████╗ ║
║ ████╗ ████║██║ ██║██║ ╚══██╔══╝██║ ██╔══██╗██╔══██╗ ║
║ ██╔████╔██║██║ ██║██║ ██║ ██║ ███████║██████╔╝ ║
║ ██║╚██╔╝██║██║ ██║██║ ██║ ██║ ██╔══██║██╔═══╝ ║
║ ██║ ╚═╝ ██║╚██████╔╝███████╗██║ ██║ ██║ ██║██║ ║
║ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ║
║ ║
║ ██████╗ █████╗ ███████╗██╗ ██╗██████╗ ██████╗ ║
║ ██╔══██╗██╔══██╗██╔════╝██║ ██║██╔══██╗██╔═══██╗ ║
║ ██║ ██║███████║███████╗███████║██████╔╝██║ ██║ ║
║ ██║ ██║██╔══██║╚════██║██╔══██║██╔══██╗██║ ██║ ║
║ ██████╔╝██║ ██║███████║██║ ██║██████╔╝╚██████╔╝ ║
║ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ║
║ ║
║ {Colors.BRIGHT_YELLOW}⚡ Weather • Crypto • News • All in One ⚡{Colors.BRIGHT_CYAN} ║
║ ║
╚══════════════════════════════════════════════════════════════╝
{Colors.RESET}"""
def print_banner() -> None:
"""Display the application ASCII art banner."""
clear_screen()
print(BANNER)
# ============================================================
# Color Helpers
# ============================================================
def colorize(text: str, color: str) -> str:
"""
Wrap text with ANSI color codes.
Args:
text: The text to colorize.
color: ANSI color code from Colors class.
Returns:
Colorized string with reset appended.
"""
return f"{color}{text}{Colors.RESET}"
def success(text: str) -> str:
"""Return text in bright green."""
return colorize(text, Colors.BRIGHT_GREEN)
def error(text: str) -> str:
"""Return text in bright red."""
return colorize(text, Colors.BRIGHT_RED)
def warning(text: str) -> str:
"""Return text in bright yellow."""
return colorize(text, Colors.BRIGHT_YELLOW)
def info(text: str) -> str:
"""Return text in bright cyan."""
return colorize(text, Colors.BRIGHT_CYAN)
def highlight(text: str) -> str:
"""Return text in bold bright white."""
return colorize(text, f"{Colors.BOLD}{Colors.BRIGHT_WHITE}")
def dim(text: str) -> str:
"""Return text in dim gray."""
return colorize(text, Colors.DIM)
# ============================================================
# Screen Utilities
# ============================================================
def clear_screen() -> None:
"""Clear the terminal screen."""
os.system("cls" if os.name == "nt" else "clear")
def print_separator(char: str = "─", length: int = 60, color: str = Colors.DIM) -> None:
"""Print a decorative separator line."""
print(colorize(char * length, color))
def print_header(title: str) -> None:
"""Print a styled section header."""
print()
print_separator("═", 60, Colors.BRIGHT_CYAN)
print(colorize(f" {title}", f"{Colors.BOLD}{Colors.BRIGHT_CYAN}"))
print_separator("═", 60, Colors.BRIGHT_CYAN)
print()
def print_subheader(title: str) -> None:
"""Print a smaller section header."""
print()
print_separator("─", 50, Colors.CYAN)
print(colorize(f" {title}", f"{Colors.BOLD}{Colors.CYAN}"))
print_separator("─", 50, Colors.CYAN)
# ============================================================
# Progress Spinner
# ============================================================
class Spinner:
"""
Threaded progress spinner for long-running operations.
Usage:
with Spinner("Fetching data"):
# long operation here
result = api.get(...)
"""
FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
def __init__(self, message: str = "Loading", color: str = Colors.BRIGHT_CYAN):
self.message = message
self.color = color
self._running = False
self._thread: Optional[threading.Thread] = None
def _spin(self) -> None:
"""Internal spinner animation loop."""
spinner = itertools.cycle(self.FRAMES)
while self._running:
frame = next(spinner)
sys.stdout.write(
f"\r {self.color}{frame}{Colors.RESET} {self.message}..."
)
sys.stdout.flush()
time.sleep(0.08)
# Clear the spinner line
sys.stdout.write("\r" + " " * (len(self.message) + 10) + "\r")
sys.stdout.flush()
def start(self) -> None:
"""Start the spinner animation."""
self._running = True
self._thread = threading.Thread(target=self._spin, daemon=True)
self._thread.start()
def stop(self) -> None:
"""Stop the spinner animation."""
self._running = False
if self._thread:
self._thread.join()
def __enter__(self) -> "Spinner":
self.start()
return self
def __exit__(self, *args: Any) -> None:
self.stop()
# ============================================================
# Input Helpers
# ============================================================
def get_input(prompt: str, allow_empty: bool = False) -> str:
"""
Get validated user input with styled prompt.
Args:
prompt: The prompt message to display.
allow_empty: Whether to accept empty input.
Returns:
Stripped user input string.
"""
while True:
try:
user_input = input(
f" {Colors.BRIGHT_YELLOW}▶{Colors.RESET} {prompt}: "
).strip()
if not user_input and not allow_empty:
print(f" {error('⚠ Please enter a value.')}")
continue
return user_input
except EOFError:
return ""
def get_menu_choice(max_option: int) -> int:
"""
Get a valid numeric menu choice from the user.
Args:
max_option: Maximum valid menu option number.
Returns:
Selected option as integer, or -1 for invalid input.
"""
try:
choice_str = input(
f"\n {Colors.BRIGHT_YELLOW}▶{Colors.RESET} Enter your choice "
f"{dim(f'[1-{max_option}]')}: "
).strip()
choice = int(choice_str)
if 1 <= choice <= max_option:
return choice
print(f" {error(f'⚠ Please enter a number between 1 and {max_option}.')}")
return -1
except (ValueError, EOFError):
print(f" {error('⚠ Invalid input. Please enter a number.')}")
return -1
def confirm(prompt: str) -> bool:
"""
Ask user for yes/no confirmation.
Args:
prompt: Question to ask.
Returns:
True if user confirms, False otherwise.
"""
response = input(
f" {Colors.BRIGHT_YELLOW}?{Colors.RESET} {prompt} "
f"{dim('[y/N]')}: "
).strip().lower()
return response in ("y", "yes")
# ============================================================
# Formatting Helpers
# ============================================================
def format_number(num: float, decimals: int = 2) -> str:
"""
Format a number with commas and specified decimal places.
Args:
num: Number to format.
decimals: Number of decimal places.
Returns:
Formatted string (e.g., "1,234,567.89").
"""
if num is None:
return "N/A"
try:
return f"{num:,.{decimals}f}"
except (TypeError, ValueError):
return str(num)
def format_currency(amount: float, symbol: str = "$") -> str:
"""
Format a number as currency.
Args:
amount: Amount to format.
symbol: Currency symbol.
Returns:
Formatted currency string (e.g., "$1,234.56").
"""
if amount is None:
return "N/A"
return f"{symbol}{format_number(amount)}"
def format_percentage(value: float) -> str:
"""
Format a number as percentage with color (green/red).
Args:
value: Percentage value.
Returns:
Colored percentage string.
"""
if value is None:
return "N/A"
sign = "+" if value > 0 else ""
color = Colors.BRIGHT_GREEN if value >= 0 else Colors.BRIGHT_RED
return colorize(f"{sign}{value:.2f}%", color)
def format_large_number(num: float) -> str:
"""
Format large numbers with K/M/B/T suffixes.
Args:
num: Number to format.
Returns:
Abbreviated string (e.g., "1.23B").
"""
if num is None:
return "N/A"
try:
abs_num = abs(num)
if abs_num >= 1_000_000_000_000:
return f"${num / 1_000_000_000_000:.2f}T"
if abs_num >= 1_000_000_000:
return f"${num / 1_000_000_000:.2f}B"
if abs_num >= 1_000_000:
return f"${num / 1_000_000:.2f}M"
if abs_num >= 1_000:
return f"${num / 1_000:.2f}K"
return f"${num:.2f}"
except (TypeError, ValueError):
return str(num)
def truncate(text: str, max_length: int = 200) -> str:
"""
Truncate text to max length with ellipsis.
Args:
text: Text to truncate.
max_length: Maximum character length.
Returns:
Truncated text or original if shorter.
"""
if not text:
return "N/A"
if len(text) <= max_length:
return text
return text[:max_length - 3] + "..."
# ============================================================
# Table Display
# ============================================================
def print_key_value(key: str, value: str, key_width: int = 20) -> None:
"""
Print a styled key-value pair.
Args:
key: Label text.
value: Value text.
key_width: Width for the key column.
"""
print(
f" {Colors.BRIGHT_WHITE}{key:<{key_width}}{Colors.RESET}"
f" {Colors.DIM}│{Colors.RESET} {value}"
)
def print_table_row(columns: List[str], widths: List[int]) -> None:
"""
Print a table row with specified column widths.
Args:
columns: List of column values.
widths: List of column widths.
"""
row = " "
for col, width in zip(columns, widths):
row += f"{str(col):<{width}} "
print(row)
def press_enter_to_continue() -> None:
"""Pause and wait for user to press Enter."""
print()
input(f" {dim('Press Enter to continue...')}")