hbutils.logging.progress

This module provides a lightweight implementation of tqdm progress bar functionality.

It includes a SimpleTqdm class that mimics the basic behavior of the popular tqdm library, allowing for progress tracking in loops and iterable operations. If the actual tqdm library is available, it will be used; otherwise, this simplified version serves as a fallback.

The module supports:

  • Progress bars with percentage, elapsed time, and ETA

  • Unit scaling for better readability

  • Terminal width detection

  • Thread-safe multi-progress bar management

  • Context manager and iterator protocols

SimpleTqdm

class hbutils.logging.progress.SimpleTqdm(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, ascii=None, disable=False, unit='it', unit_scale=False, initial=0, position=None, unit_divisor=1000, **kwargs)[source]

A lightweight implementation of tqdm progress bar.

This class provides basic progress bar functionality similar to tqdm, with support for iteration tracking, time estimation, and customizable display.

Variables:
  • _instances (list) – Global list of all active SimpleTqdm instances

  • _lock (threading.Lock) – Thread lock for managing concurrent progress bar updates

  • _last_print_time (float) – Timestamp of the last global print operation

  • _update_interval (float) – Minimum interval between display updates

__enter__()[source]

Enter the context manager.

Returns:

Self instance

Return type:

SimpleTqdm

Example::
>>> with SimpleTqdm(range(10)) as pbar:
...     for item in pbar:
...         pass
__exit__(exc_type, exc_val, exc_tb)[source]

Exit the context manager.

Parameters:
  • exc_type (type, optional) – Exception type if an exception occurred

  • exc_val (Exception, optional) – Exception value if an exception occurred

  • exc_tb (traceback, optional) – Exception traceback if an exception occurred

Example::
>>> with SimpleTqdm(range(10)) as pbar:
...     for item in pbar:
...         pass
__init__(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, ascii=None, disable=False, unit='it', unit_scale=False, initial=0, position=None, unit_divisor=1000, **kwargs)[source]

Initialize a SimpleTqdm progress bar.

Parameters:
  • iterable (iterable, optional) – Iterable to decorate with a progress bar

  • desc (str, optional) – Prefix for the progress bar

  • total (int, optional) – The number of expected iterations

  • leave (bool) – If True, keep all traces of the progress bar upon termination

  • file (file-like object, optional) – Specifies where to output the progress messages

  • ncols (int, optional) – The width of the entire output message

  • mininterval (float) – Minimum progress display update interval in seconds

  • ascii (bool, optional) – If True, use ASCII characters for the progress bar

  • disable (bool) – Whether to disable the entire progress bar

  • unit (str) – String that will be used to define the unit of each iteration

  • unit_scale (bool) – If True, the number of iterations will be scaled automatically

  • initial (int) – The initial counter value

  • position (int, optional) – Specify the line offset to print this bar

  • unit_divisor (int) – Divisor for unit scaling (1000 or 1024)

  • kwargs – Additional keyword arguments (will trigger a warning if provided)

Example::
>>> with SimpleTqdm(range(100), desc="Processing") as pbar:
...     for item in pbar:
...         time.sleep(0.01)
Processing: 100.0% |====================>| 100/100 [00:01<00:00, 99.5it/s]
__iter__()[source]

Iterate over the wrapped iterable with progress tracking.

Returns:

Iterator yielding items from the wrapped iterable

Raises:

TypeError – If no iterable was provided during initialization

Example::
>>> for item in SimpleTqdm(range(5)):
...     print(item)
0
1
2
3
4
_create_activity_bar(speed: float = 3.0)[source]

Create an activity indicator for cases without a known total.

Parameters:

speed (float) – Speed of the animation (cycles per second)

Returns:

Current activity indicator character

Return type:

str

Example::
>>> pbar = SimpleTqdm()
>>> indicator = pbar._create_activity_bar()
>>> indicator in ['|', '/', '-', '\\']
True
_create_progress_bar(percentage, bar_width)[source]

Create a progress bar string.

Parameters:
  • percentage (float) – Completion percentage (0-100)

  • bar_width (int) – Width of the progress bar in characters

Returns:

Formatted progress bar string

Return type:

str

Example::
>>> pbar = SimpleTqdm()
>>> pbar._create_progress_bar(50, 20)
'|==========>---------|'
_display()[source]

Display the current progress bar state.

This internal method formats and outputs the progress bar to the file stream. It calculates the terminal width, builds the progress bar components including description, percentage, progress numbers, time information, ETA, and speed, then outputs the formatted string to the specified file.

Example::
>>> pbar = SimpleTqdm(total=100, desc="Processing")
>>> pbar.n = 50
>>> pbar._display()  # Outputs: Processing:  50.0% |=========>---------| 50/100 [00:05<00:05, 10.0it/s]
_format_sizeof(num, suffix='', divisor=None)[source]

Format number size with unit scaling support.

Parameters:
  • num (float) – The number to format

  • suffix (str) – Suffix to append to the formatted number

  • divisor (int, optional) – Divisor for unit scaling (1000 or 1024)

Returns:

Formatted string with appropriate unit

Return type:

str

Example::
>>> pbar = SimpleTqdm(total=1000, unit_scale=True)
>>> pbar._format_sizeof(1500, "B")
'1.5kB'
_format_time(seconds)[source]

Format time display.

Parameters:

seconds (float) – Time in seconds

Returns:

Formatted time string in format HH:MM:SS or MM:SS or SS.SSs

Return type:

str

Example::
>>> pbar = SimpleTqdm()
>>> pbar._format_time(65)
'01:05'
>>> pbar._format_time(3665)
'01:01:05'
_get_terminal_width()[source]

Get the terminal width.

Returns:

Terminal width in characters

Return type:

int

Example::
>>> pbar = SimpleTqdm()
>>> width = pbar._get_terminal_width()
>>> width >= 80
True
clear()[source]

Clear the current display.

This method clears the progress bar from the terminal by overwriting the current line with spaces.

Example::
>>> pbar = SimpleTqdm(range(100))
>>> pbar.clear()  # Clear the progress bar from terminal
close()[source]

Close the progress bar and clean up resources.

This method performs a final refresh of the progress bar, adds a newline if leave is True, or clears the line if leave is False, and removes the instance from the global manager.

Example::
>>> pbar = SimpleTqdm(range(100))
>>> for item in pbar:
...     pass
>>> pbar.close()
refresh()[source]

Force refresh of the progress bar display.

Example::
>>> pbar = SimpleTqdm(total=100)
>>> pbar.n = 50
>>> pbar.refresh()  # Force display update
set_description(desc=None, refresh=True)[source]

Set the progress bar description.

Parameters:
  • desc (str, optional) – New description text

  • refresh (bool) – Whether to refresh the display immediately

Example::
>>> pbar = SimpleTqdm(range(100))
>>> pbar.set_description("Processing files")
set_postfix(ordered_dict=None, refresh=True, **kwargs)[source]

Set postfix information (simplified implementation, not actually displayed).

This method exists for API compatibility with tqdm but does not display the postfix information in SimpleTqdm.

Parameters:
  • ordered_dict (dict, optional) – Dictionary of postfix key-value pairs

  • refresh (bool) – Whether to refresh the display immediately

  • kwargs – Additional postfix key-value pairs

Example::
>>> pbar = SimpleTqdm(range(100))
>>> pbar.set_postfix(loss=0.5, accuracy=0.95)
update(n=1)[source]

Update the progress bar by incrementing the counter.

Parameters:

n (int) – Increment to add to the internal counter

Example::
>>> pbar = SimpleTqdm(total=100)
>>> pbar.update(10)
>>> pbar.n
10
write(s, file=None, end='\n', nolock=False)[source]

Write text without disrupting the progress bar display.

This method allows writing messages to the output stream without interfering with the progress bar. It temporarily clears the progress bar, writes the message, and then refreshes the progress bar.

Parameters:
  • s (str) – String to write

  • file (file-like object, optional) – File object to write to

  • end (str) – String appended after the last value

  • nolock (bool) – If True, don’t use the global lock

Example::
>>> pbar = SimpleTqdm(range(100))
>>> pbar.write("Processing complete")

tqdm

hbutils.logging.progress.tqdm(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, ascii=None, disable=False, unit='it', unit_scale=False, initial=0, position=None, unit_divisor=1000, **kwargs)[source]

tqdm-compatible interface for creating progress bars.

This function provides a unified interface that uses the real tqdm library if available, otherwise falls back to SimpleTqdm. It maintains API compatibility with the standard tqdm library while providing a lightweight alternative when tqdm is not installed.

Parameters:
  • iterable (iterable, optional) – Iterable to decorate with a progress bar

  • desc (str, optional) – Prefix for the progress bar

  • total (int, optional) – The number of expected iterations

  • leave (bool) – If True, keep all traces of the progress bar upon termination

  • file (file-like object, optional) – Specifies where to output the progress messages

  • ncols (int, optional) – The width of the entire output message

  • mininterval (float) – Minimum progress display update interval in seconds

  • ascii (bool, optional) – If True, use ASCII characters for the progress bar

  • disable (bool) – Whether to disable the entire progress bar

  • unit (str) – String that will be used to define the unit of each iteration

  • unit_scale (bool) – If True, the number of iterations will be scaled automatically

  • initial (int) – The initial counter value

  • position (int, optional) – Specify the line offset to print this bar

  • unit_divisor (int) – Divisor for unit scaling (1000 or 1024)

  • kwargs – Additional keyword arguments passed to the underlying implementation

Returns:

Progress bar instance (either real tqdm or SimpleTqdm)

Return type:

tqdm or SimpleTqdm

Example::
>>> for i in tqdm(range(100), desc="Processing"):
...     time.sleep(0.01)
Processing: 100.0% |====================>| 100/100 [00:01<00:00, 99.5it/s]

trange

hbutils.logging.progress.trange(*args, **kwargs)[source]

Shortcut for tqdm(range(*args), **kwargs).

This is a convenience function that creates a progress bar for a range iterator. It’s equivalent to calling tqdm(range(*args), **kwargs).

Parameters:
  • args (int) – Positional arguments passed to range()

  • kwargs – Keyword arguments passed to tqdm()

Returns:

Progress bar instance wrapping a range iterator

Return type:

tqdm or SimpleTqdm

Example::
>>> for i in trange(100, desc="Counting"):
...     time.sleep(0.01)
Counting: 100.0% |====================>| 100/100 [00:01<00:00, 99.5it/s]