logbar 0.0.1.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ include requirements.txt
2
+ prune tests/
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.2
2
+ Name: logbar
3
+ Version: 0.0.1.dev0
4
+ Summary: A unified Logger and ProgressBar util with zero dependencies.
5
+ Home-page: https://github.com/ModelCloud/LogBar
6
+ Author: ModelCloud
7
+ Author-email: qubitium@modelcloud.ai
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: author
15
+ Dynamic: author-email
16
+ Dynamic: classifier
17
+ Dynamic: description
18
+ Dynamic: description-content-type
19
+ Dynamic: home-page
20
+ Dynamic: requires-python
21
+ Dynamic: summary
22
+
23
+ # LogBar
24
+ A unified Logger and ProgressBar util with zero dependencies.
@@ -0,0 +1,2 @@
1
+ # LogBar
2
+ A unified Logger and ProgressBar util with zero dependencies.
@@ -0,0 +1,3 @@
1
+ from . import logbar
2
+
3
+ __all__ = ["logbar"]
@@ -0,0 +1,231 @@
1
+ # Copyright 2024-2025 ModelCloud.ai
2
+ # Copyright 2024-2025 qubitium@modelcloud.ai
3
+ # Contact: qubitium@modelcloud.ai, x.com/qubitium
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ from enum import Enum
19
+ from typing import Optional, Iterable
20
+
21
+ from logbar.terminal import terminal_size
22
+
23
+ # global static/shared logger instance
24
+ logger = None
25
+ last_pb_instance = None # one for logger, 2 for progressbar
26
+
27
+ def update_last_pb_instance(src) -> None:
28
+ global last_pb_instance
29
+ last_pb_instance = src
30
+
31
+ # ANSI color codes
32
+ COLORS = {
33
+ "DEBUG": "\033[36m", # Cyan
34
+ "INFO": "\033[32m", # Green
35
+ "WARN": "\033[33m", # Yellow
36
+ "ERROR": "\033[31m", # Red
37
+ "CRIT": "\033[31m", # Red
38
+ "RESET": "\033[0m", # Reset to default
39
+ }
40
+
41
+ class LEVEL(str, Enum):
42
+ DEBUG = "DEBUG"
43
+ WARN = "WARN"
44
+ INFO = "INFO"
45
+ ERROR = "ERROR"
46
+ CRITICAL = "CRIT"
47
+
48
+ class LogBar(logging.Logger):
49
+ history = set()
50
+ history_limit = 1000
51
+
52
+ @classmethod
53
+ # return a shared global/singleton logger
54
+ def shared(cls, override_logger: Optional[bool] = False):
55
+ global logger
56
+ if logger is not None:
57
+ return logger
58
+
59
+ # save logger class
60
+ if not override_logger:
61
+ original_logger_cls = logging.getLoggerClass()
62
+
63
+ logging.setLoggerClass(LogBar)
64
+
65
+ logger = logging.getLogger("logbar")
66
+
67
+ # restore logger cls
68
+ if not override_logger:
69
+ logging.setLoggerClass(original_logger_cls)
70
+
71
+ logger.propagate = False
72
+ logger.setLevel(logging.INFO)
73
+
74
+ # handler = logging.StreamHandler(sys.stdout)
75
+ # handler.setFormatter(formatter)
76
+ # handler.flush = sys.stdout.flush
77
+ # logger.addHandler(handler)
78
+
79
+ # clear space from previous logs
80
+ print("", end='\n', flush=True)
81
+
82
+ return logger
83
+
84
+
85
+ def pb(self, iterable: Iterable):
86
+ from logbar.progress import ProgressBar
87
+
88
+ return ProgressBar(iterable)
89
+
90
+ def history_add(self, msg) -> bool:
91
+ h = hash(msg) # TODO only msg is checked not level + msg
92
+ if h in self.history:
93
+ return False # add failed since it already exists
94
+
95
+ if len(self.history) > self.history_limit:
96
+ self.history.clear()
97
+
98
+ self.history.add(h)
99
+
100
+ return True
101
+
102
+ class critical_cls:
103
+ def __init__(self, logger):
104
+ self.logger = logger
105
+
106
+ def once(self, msg, *args, **kwargs):
107
+ if self.logger.history_add(msg):
108
+ self(msg, *args, **kwargs)
109
+
110
+ def __call__(self, msg, *args, **kwargs):
111
+ self.logger._process(LEVEL.CRITICAL, msg, *args, **kwargs)
112
+
113
+ class warn_cls:
114
+ def __init__(self, logger):
115
+ self.logger = logger
116
+
117
+ def once(self, msg, *args, **kwargs):
118
+ if self.logger.history_add(msg):
119
+ self(msg, *args, **kwargs)
120
+
121
+ def __call__(self, msg, *args, **kwargs):
122
+ self.logger._process(LEVEL.WARN, msg, *args, **kwargs)
123
+
124
+ class debug_cls:
125
+ def __init__(self, logger):
126
+ self.logger = logger
127
+
128
+ def once(self, msg, *args, **kwargs):
129
+ if self.logger.history_add(msg):
130
+ self(msg, *args, **kwargs)
131
+
132
+ def __call__(self, msg, *args, **kwargs):
133
+ self.logger._process(LEVEL.DEBUG, msg, *args, **kwargs)
134
+
135
+ class info_cls:
136
+ def __init__(self, logger):
137
+ self.logger = logger
138
+
139
+ def once(self, msg, *args, **kwargs):
140
+ if self.logger.history_add(msg):
141
+ self(msg, *args, **kwargs)
142
+
143
+ def __call__(self, msg, *args, **kwargs):
144
+ self.logger._process(LEVEL.INFO, msg, *args, **kwargs)
145
+
146
+ class error_cls:
147
+ def __init__(self, logger):
148
+ self.logger = logger
149
+
150
+ def once(self, msg, *args, **kwargs):
151
+ if self.logger.history_add(msg):
152
+ self(msg, *args, **kwargs)
153
+
154
+ def __call__(self, msg, *args, **kwargs):
155
+ self.logger._process(LEVEL.ERROR, msg, *args, **kwargs)
156
+
157
+ def __init__(self, name):
158
+ super().__init__(name)
159
+ self._warning = self.warning
160
+ self._debug = self.debug
161
+ self._info = self.info
162
+ self._error = self.error
163
+ self._critical = self.critical
164
+
165
+ self.warn = self.warn_cls(logger=self)
166
+ self.debug = self.debug_cls(logger=self)
167
+ self.info = self.info_cls(logger=self)
168
+ self.error = self.error_cls(logger=self)
169
+ self.critical = self.critical_cls(logger=self)
170
+
171
+ def _process(self, level: LEVEL, msg, *args, **kwargs):
172
+ from logbar.progress import ProgressBar
173
+
174
+ columns, _ = terminal_size()
175
+ str_msg = str(msg)
176
+
177
+ global last_pb_instance
178
+ if isinstance(last_pb_instance, ProgressBar) and not last_pb_instance.closed:
179
+ buf = f'\r'
180
+ if columns > 0:
181
+ str_msg += " " * columns
182
+
183
+ print(buf,end='',flush=True)
184
+
185
+ # Get the color for the log level
186
+
187
+ reset = COLORS["RESET"]
188
+ color = COLORS.get(level.value, reset)
189
+
190
+ out_len = 5 + 1 + len(str_msg)
191
+ paddding_end = " " * (columns - out_len)
192
+
193
+ padding = " " * (5 - len(level.value)) # 5 is max enum string length
194
+ print(f"{color}{level.value}{reset}{padding} {str_msg}", end='\n', flush=True)
195
+ # if level == LEVEL.INFO:
196
+ # print(f"INFO: {str_msg}", end='',flush=True)
197
+ # elif level == LEVEL.WARN:
198
+ # print(f"WARN: {str_msg}", end='',flush=True)
199
+ # elif level == LEVEL.ERROR:
200
+ # print(f"ERROR: {str_msg}", end='',flush=True)
201
+ # elif level == LEVEL.DEBUG:
202
+ # print(f"DEBUG: {str_msg}", end='',flush=True)
203
+ # else:
204
+ # raise RuntimeError(f"Unknown logging level {level}")
205
+
206
+ # Print the message with the appropriate color
207
+ #print(f"{color}{level.value}{reset}{padding} {str_msg}")
208
+
209
+ # if level == LEVEL.INFO:
210
+ # self._info(str_msg, *args, **kwargs)
211
+ #
212
+ # elif level == LEVEL.WARN:
213
+ # self._warning(str_msg, *args, **kwargs)
214
+ # elif level == LEVEL.ERROR:
215
+ # self._error(str_msg, *args, **kwargs)
216
+ # elif level == LEVEL.DEBUG:
217
+ # self._debug(str_msg, *args, **kwargs)
218
+ # else:
219
+ # raise RuntimeError(f"Unknown logging level {level}")
220
+
221
+ if isinstance(last_pb_instance, ProgressBar):
222
+ if not last_pb_instance.closed:
223
+ # only do this for our instance
224
+ if self == logger:
225
+ last_pb_instance.draw()
226
+ else:
227
+ last_pb_instance = None
228
+
229
+
230
+
231
+
@@ -0,0 +1,266 @@
1
+ # Copyright 2024-2025 ModelCloud.ai
2
+ # Copyright 2024-2025 qubitium@modelcloud.ai
3
+ # Contact: qubitium@modelcloud.ai, x.com/qubitium
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import datetime
18
+ import time
19
+ from enum import Enum
20
+ from typing import Iterable, Optional
21
+ from warnings import warn
22
+
23
+ from logbar.logbar import update_last_pb_instance, LogBar
24
+ from logbar.terminal import terminal_size
25
+
26
+ logger = LogBar.shared()
27
+
28
+ # TODO FIXME: what does this do exactly?
29
+ class ProgressBarWarning(Warning):
30
+ def __init__(self, msg, fp_write=None, *a, **k):
31
+ if fp_write is not None:
32
+ fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
33
+ else:
34
+ super().__init__(msg, *a, **k)
35
+
36
+ class RenderMode(str, Enum):
37
+ AUTO = "AUTO" # pb will auto draw() at the START of each itereation
38
+ MANUAL = "MANUAL" # pb will not call draw() in each iteration and user must call draw()
39
+
40
+
41
+ class ProgressBar:
42
+ def __init__(self, iterable: Iterable):
43
+ self._iterating = False # state: in init or active iteration
44
+ self._skip_next_draw = False
45
+
46
+ self._render_mode = RenderMode.AUTO
47
+
48
+ self._title = ""
49
+ self._subtitle = ""
50
+ self._fill = '█'
51
+ self.closed = False # active state
52
+
53
+ # max info length over the life ot the pb
54
+ self.max_title_len = 0
55
+ self.max_subtitle_len = 0
56
+
57
+ self.iterable = iterable
58
+
59
+ self.bar_length = 0
60
+ self.current_iter_step = 0
61
+ self.time = time.time()
62
+
63
+ self.ui_show_left_steps = True # show [1 of 100] on left side
64
+ self.ui_show_left_steps_offset = 0
65
+
66
+ def set(self,
67
+ show_left_steps: Optional[bool] = None,
68
+ left_steps_offset: Optional[int] = None,
69
+ ):
70
+ if show_left_steps is not None:
71
+ self.ui_show_left_steps = show_left_steps
72
+
73
+ if left_steps_offset is not None:
74
+ self.ui_show_left_steps_offset = left_steps_offset
75
+ return self
76
+
77
+ def fill(self, fill = '█'):
78
+ self._fill = fill
79
+ return self
80
+
81
+ def title(self, title:str):
82
+ if self._iterating and self._render_mode != RenderMode.MANUAL:
83
+ logger.warn("ProgressBar: Title should not be updated after iteration has started unless in `manual` render mode.")
84
+
85
+ if len(title) > self.max_title_len:
86
+ self.max_title_len = len(title)
87
+
88
+ self._title = title
89
+ return self
90
+
91
+ def subtitle(self, subtitle: str):
92
+ if self._iterating and self._render_mode != RenderMode.MANUAL:
93
+ logger.warn("ProgressBar: Sub-title should not be updated after iteration has started unless in `manual` render mode.")
94
+
95
+ if len(subtitle) > self.max_subtitle_len:
96
+ self.max_subtitle_len = len(subtitle)
97
+
98
+ self._subtitle = subtitle
99
+ return self
100
+
101
+ # set render mode
102
+ def mode(self, mode: RenderMode):
103
+ self._render_mode = mode
104
+
105
+ def auto(self):
106
+ self._render_mode = RenderMode.AUTO
107
+ return self
108
+
109
+ def manual(self ):
110
+ self._render_mode = RenderMode.MANUAL
111
+ return self
112
+
113
+ def skip_next_draw(self):
114
+ if not self._skip_next_draw:
115
+ self._skip_next_draw = True
116
+
117
+ def draw(self):
118
+ columns, _ = terminal_size()
119
+
120
+ pre_bar_size = 0 # char length of content before progress bar
121
+
122
+ percent_num = self.step() / float(len(self))
123
+ percent = ("{0:.1f}").format(100 * (percent_num))
124
+ log = f"{self.calc_time(self.step())} [{self.step()}/{len(self)}] {percent}%"
125
+
126
+ if self._title:
127
+ pre_bar_size += self.max_title_len + 1 # title_ (_ == space)
128
+ if self._subtitle:
129
+ pre_bar_size += self.max_subtitle_len + 1 # subtitle_ (_ == space)
130
+
131
+ # generate: ui_left_steps
132
+ if self.ui_show_left_steps:
133
+ self.ui_show_left_steps_text = f"[{self.step()-self.ui_show_left_steps_offset} of {len(self)-self.ui_show_left_steps_offset}] "
134
+ self.ui_show_left_steps_text_max_len = len(self.ui_show_left_steps_text)
135
+ pre_bar_size += self.ui_show_left_steps_text_max_len
136
+
137
+ padding = ""
138
+
139
+ # calculate padding
140
+ if self._title and len(self._title) < self.max_title_len:
141
+ padding += " " * (self.max_title_len - len(self._title))
142
+
143
+ # calculate padding
144
+ if self._subtitle and len(self._subtitle) < self.max_subtitle_len:
145
+ padding += " " * (self.max_subtitle_len - len(self._subtitle))
146
+
147
+ bar_length = columns - pre_bar_size - len(log) - 2 # bar|_ == 2 chars
148
+
149
+ filled_length = int(bar_length * self.step() // len(self))
150
+ bar = self._fill * filled_length + '-' * (bar_length - filled_length)
151
+ self.log(bar=bar, log=log, padding=padding, end='') # '\n' if percent_num >= 1.0 else ''
152
+
153
+ def calc_time(self, iteration):
154
+ used_time = int(time.time() - self.time)
155
+ formatted_time = str(datetime.timedelta(seconds=used_time))
156
+ remaining = str(datetime.timedelta(seconds=int((used_time / max(iteration, 1)) * len(self))))
157
+ return f"{formatted_time} / {remaining}"
158
+
159
+ def log(self, bar:str, log:str, padding:str = "", end: str = ""):
160
+ # print(f'\r{self.prefix} {self.info_text} |{bar}| {log}', end='', flush=True)
161
+ out = ""
162
+ if self._title:
163
+ out += self._title + " "
164
+
165
+ if self._subtitle:
166
+ out += self._subtitle + " "
167
+
168
+ out += padding
169
+
170
+ if self.ui_show_left_steps:
171
+ out += self.ui_show_left_steps_text
172
+
173
+ out += f"{bar}| {log}"
174
+
175
+ print(f'\r{out}', end=end, flush=True)
176
+
177
+ update_last_pb_instance(src=self) # let logger now we logged
178
+
179
+ def __bool__(self):
180
+ if self.iterable is None:
181
+ raise TypeError('bool() undefined when iterable == total == None')
182
+ return bool(self.iterable)
183
+
184
+ def __len__(self):
185
+ return (
186
+ self.iterable.shape[0] if hasattr(self.iterable, "shape")
187
+ else len(self.iterable) if hasattr(self.iterable, "__len__")
188
+ else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__")
189
+ else getattr(self, "total", None))
190
+
191
+ # TODO FIXME: I have no cluse why the try/catch is catching nothing here
192
+ def __reversed__(self):
193
+ try:
194
+ original = self.iterable
195
+ except AttributeError:
196
+ raise TypeError("'progress' object is not reversible")
197
+ else:
198
+ self.iterable = reversed(self.iterable)
199
+ return self.__iter__()
200
+ finally:
201
+ self.iterable = original
202
+
203
+ def __contains__(self, item):
204
+ contains = getattr(self.iterable, '__contains__', None)
205
+ return contains(item) if contains is not None else item in self.__iter__()
206
+
207
+ def __enter__(self):
208
+ return self
209
+
210
+ # TODO FIXME: I don't understand the exception here. What are we catching? yield error?
211
+ def __exit__(self, exc_type, exc_value, traceback):
212
+ try:
213
+ self.close()
214
+ except AttributeError:
215
+ # maybe eager thread cleanup upon external error
216
+ if (exc_type, exc_value, traceback) == (None, None, None):
217
+ raise
218
+
219
+ # TODO FIXME: what does this do exactly?
220
+ warn("AttributeError ignored", ProgressBarWarning, stacklevel=2)
221
+
222
+ def __del__(self):
223
+ self.close()
224
+
225
+ # TODO FIXME: what does this do exactly? where is this `pos` attr magically coming from? I don't see it anywhere
226
+ @property
227
+ def _comparable(self):
228
+ return abs(getattr(self, "pos", 1 << 31))
229
+
230
+ def __hash__(self):
231
+ return id(self)
232
+
233
+ def step(self) -> int:
234
+ return self.current_iter_step
235
+
236
+ def next(self):
237
+ self.current_iter_step += 1
238
+ return self
239
+
240
+ def __iter__(self):
241
+ iterable = self.iterable
242
+
243
+ for obj in iterable:
244
+ # updat running state
245
+ if not self._iterating:
246
+ self.iterating = True
247
+
248
+ self.next()
249
+
250
+ if self._render_mode == RenderMode.AUTO:
251
+ self.draw()
252
+
253
+ # if not self._skip_next_draw:
254
+ # if self._render_mode == RenderMode.AUTO:
255
+ # self.draw()
256
+ # else:
257
+ # self._skip_next_draw = False
258
+ yield obj
259
+
260
+ # self.progress()
261
+ self.close()
262
+ return
263
+
264
+ def close(self):
265
+ self.closed = True
266
+ #self.log(f"{self.fill * self.bar_length}", "100.0%", end="\n")
@@ -0,0 +1,49 @@
1
+ # adapted from github.com/onsim/shutils
2
+ import os
3
+ import sys
4
+
5
+
6
+ def terminal_size(fallback=(80, 24)):
7
+ """Get the size of the terminal window.
8
+
9
+ For each of the two dimensions, the environment variable, COLUMNS
10
+ and LINES respectively, is checked. If the variable is defined and
11
+ the value is a positive integer, it is used.
12
+
13
+ When COLUMNS or LINES is not defined, which is the common case,
14
+ the terminal connected to sys.__stdout__ is queried
15
+ by invoking os.get_terminal_size.
16
+
17
+ If the terminal size cannot be successfully queried, either because
18
+ the system doesn't support querying, or because we are not
19
+ connected to a terminal, the value given in fallback parameter
20
+ is used. Fallback defaults to (80, 24) which is the default
21
+ size used by many terminal emulators.
22
+
23
+ The value returned is a named tuple of type os.terminal_size.
24
+ """
25
+ # columns, lines are the working values
26
+ try:
27
+ columns = int(os.environ['COLUMNS'])
28
+ except (KeyError, ValueError):
29
+ columns = 0
30
+
31
+ try:
32
+ lines = int(os.environ['LINES'])
33
+ except (KeyError, ValueError):
34
+ lines = 0
35
+
36
+ # only query if necessary
37
+ if columns <= 0 or lines <= 0:
38
+ try:
39
+ size = os.get_terminal_size(sys.__stdout__.fileno())
40
+ except (AttributeError, ValueError, OSError):
41
+ # stdout is None, closed, detached, or not a terminal, or
42
+ # os.get_terminal_size() is unsupported
43
+ size = os.terminal_size(fallback)
44
+ if columns <= 0:
45
+ columns = size.columns or fallback[0]
46
+ if lines <= 0:
47
+ lines = size.lines or fallback[1]
48
+
49
+ return (columns, lines)
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.2
2
+ Name: logbar
3
+ Version: 0.0.1.dev0
4
+ Summary: A unified Logger and ProgressBar util with zero dependencies.
5
+ Home-page: https://github.com/ModelCloud/LogBar
6
+ Author: ModelCloud
7
+ Author-email: qubitium@modelcloud.ai
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: author
15
+ Dynamic: author-email
16
+ Dynamic: classifier
17
+ Dynamic: description
18
+ Dynamic: description-content-type
19
+ Dynamic: home-page
20
+ Dynamic: requires-python
21
+ Dynamic: summary
22
+
23
+ # LogBar
24
+ A unified Logger and ProgressBar util with zero dependencies.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ requirements.txt
5
+ setup.py
6
+ logbar/__init__.py
7
+ logbar/logbar.py
8
+ logbar/progress.py
9
+ logbar/terminal.py
10
+ logbar.egg-info/PKG-INFO
11
+ logbar.egg-info/SOURCES.txt
12
+ logbar.egg-info/dependency_links.txt
13
+ logbar.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ logbar
File without changes
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,44 @@
1
+ # Copyright 2025 ModelCloud.ai
2
+ # Copyright 2025 qubitium@modelcloud.ai
3
+ # Contact: qubitium@modelcloud.ai, x.com/qubitium
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from pathlib import Path
18
+
19
+ from setuptools import find_packages, setup
20
+
21
+ __version__ = "0.0.1-dev"
22
+
23
+ with open("requirements.txt") as f:
24
+ requirements = f.read().splitlines()
25
+
26
+ setup(
27
+ name="logbar",
28
+ version=__version__,
29
+ author="ModelCloud",
30
+ author_email="qubitium@modelcloud.ai",
31
+ description="A unified Logger and ProgressBar util with zero dependencies. ",
32
+ long_description=(Path(__file__).parent / "README.md").read_text(encoding="UTF-8"),
33
+ long_description_content_type="text/markdown",
34
+ url="https://github.com/ModelCloud/LogBar",
35
+ packages=find_packages(),
36
+ install_requires=requirements,
37
+ platform=["linux", "windows", "darwin"],
38
+ classifiers=[
39
+ "Programming Language :: Python :: 3",
40
+ "License :: OSI Approved :: Apache Software License",
41
+ "Operating System :: OS Independent",
42
+ ],
43
+ python_requires=">=3",
44
+ )