-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbar.py
More file actions
180 lines (156 loc) · 6.17 KB
/
bar.py
File metadata and controls
180 lines (156 loc) · 6.17 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
import sys
import asyncio
import numpy as np
import numpy.core.defchararray as chars
import traceback
from typing import Dict, Optional, Union
import warnings
class Bar:
"""
Terminal progress bar for tracking long-running operations.
Displays completion percentage, processing speed, and estimated time
remaining for iterative tasks. Supports additional metric display
and integrates with async workflows.
"""
def __init__(
self, iterations: int, title: str = "Loading", steps: int = 40
) -> None:
"""
Initialize progress bar with task parameters.
Args:
iterations: Total number of items to process
title: Display label for the operation
steps: Character width of the progress bar
"""
# Total work to be completed
self.iterations: int = iterations
# Operation display name
self.title: str = title
# Visual bar width in characters
self.steps: int = steps
# Storage for additional metrics
self.items: Dict[str, str] = {}
async def update(self, batch: int, time: float, final: bool = False) -> None:
"""
Refresh progress display with current completion status.
Args:
batch: Number of items completed so far
time: Operation start timestamp for speed calculation
final: Whether this is the final update (adds newline)
"""
# Calculate elapsed processing time
elapsed: float = np.subtract(asyncio.get_event_loop().time(), time)
# Determine completion percentage
percentage: float = np.divide(batch, self.iterations)
# Calculate processing throughput (items per second)
throughput: np.array = np.where(
np.greater(elapsed, 0), # Avoid division by zero
np.floor_divide(batch, elapsed),
0,
)
# Estimate remaining time based on current progress
eta: np.array = np.where(
np.greater(batch, 0), # Require progress for estimation
np.divide(
np.multiply(
elapsed, np.subtract(self.iterations, batch)
),
batch,
),
0, # Cannot estimate without initial progress
)
# Construct visual progress bar representation
bar: str = chars.add(
"|",
chars.add(
# Filled portion using hash characters
"".join(np.repeat("#", np.ceil(np.multiply(percentage, self.steps)))),
chars.add(
# Empty portion using spaces
"".join(
np.repeat(
" ",
np.subtract(
self.steps, np.ceil(np.multiply(percentage, self.steps))
),
)
),
# Progress counter display
f"| {batch:03d}/{self.iterations:03d}",
),
),
)
# Output complete progress line to terminal
sys.stdout.write(
chars.add(
chars.add(
chars.add(
# Core progress information
f"\r{self.title}: {bar} [{np.multiply(percentage, 100):.2f}%] in {elapsed:.1f}s "
f"({throughput:.1f}/s, ETA: {eta:.1f}s)",
# Additional metrics if available
np.where(
np.greater(np.size(self.items), 0),
chars.add(
" (",
chars.add(
", ".join(
[
f"{name}: {value}"
for name, value in self.items.items()
]
),
")",
),
),
"", # No additional metrics to display
),
),
"",
),
"",
)
)
# Add newline for final update
if final:
sys.stdout.write("\n")
# Force immediate terminal output
sys.stdout.flush()
async def postfix(self, **kwargs: Union[str, int, float]) -> None:
"""
Update supplementary metrics displayed alongside progress.
Accepts arbitrary key-value pairs for displaying additional
information such as loss values, accuracy, or other metrics.
Examples:
await pbar.postfix(loss=0.5, accuracy=0.95)
await pbar.postfix(lr=0.001, batch_size=32)
"""
# Update metrics dictionary with new values
self.items.update(kwargs)
async def __aenter__(self) -> "Bar":
"""
Enable usage as async context manager.
Returns:
Bar instance for use within async context block
"""
return self
async def __aexit__(
self,
exc_type: Optional[type],
exc_val: Optional[BaseException],
exc_tb: Optional[traceback.TracebackException],
) -> None:
"""
Handle cleanup when exiting async context manager.
Shows completion status on normal exit or error message on exception.
"""
if exc_type is None:
# Normal completion - display final status
await self.update(
self.iterations, # Mark all work as complete
asyncio.get_event_loop().time(), # Current timestamp
final=True, # Add newline for clean exit
)
else:
# Exception occurred - display error notification
warnings.warn(f"\n{self.title} encountered error: {exc_val}")