Skip to content

Commit

Permalink
port functionality from tqdm
Browse files Browse the repository at this point in the history
preparations for dropping tqdm
shrink prgressbars on close if using it only for a message
  • Loading branch information
TheHardew committed Feb 14, 2024
1 parent 6c94b66 commit e13ee81
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 18 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "compress_comics_TheHardew"
version = "v0.4.7"
version = "v0.4.8"
authors = [
{ name="TheHardew" },
]
Expand Down
110 changes: 93 additions & 17 deletions src/compress_comics_TheHardew/text_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,45 @@
"""
import shutil
from tqdm import tqdm
import time


class TextBar(tqdm):
"""
A class which puts text in the middle of the tqdm progress bar
Manages updates to set the bar format correctly
"""

@staticmethod
def __colors_from_rgb_hex(hex_color):
"""
Parse a hex string int
:param hex_color: a hex color string, e.g. #ABCDEF
:return: the shell escape code
"""
return tuple(int(hex_color[i:i+2], 16) for i in (1, 3, 5))

def __get_background_color_string(self):
"""
Create a shell escape code to change the background color
:return: the shell escape code
"""
red = int(self.colour[1:3], 16)
green = int(self.colour[3:5], 16)
blue = int(self.colour[5:], 16)
hex_string = f'{red};{green};{blue}'
return f'\x1b[97;48;2;{hex_string}m'
colours = TextBar.__colors_from_rgb_hex(self.colour)
return '\x1b[48;2;' + ';'.join(map(str, colours)) + 'm'


@staticmethod
def reset_line():
print("\033[0m")


def __get_foreground_color_string(self):
"""
Create a shell escape code to change the foreground color
:return: the shell escape code
"""
colours = TextBar.__colors_from_rgb_hex(self.colour)
return '\x1b[38;2;' + ';'.join(map(str, colours)) + 'm'


def __get_base_bar_length(self, bar_format):
Expand Down Expand Up @@ -54,33 +76,78 @@ def __get_custom_progress_bar(self, bar_format, filled=False):
return background_color + custom_bar[:filled_in] + reset_color + custom_bar[filled_in:]


@staticmethod
def __format_time(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)

R = f'{int(minutes):02d}:{int(seconds):02d}'
if hours > 0:
return f'{int(hours):02d}' + R
return R


def __calculate_remaining(self):
avg_rate = self.__calculate_rate()
if avg_rate == 0:
return TextBar.__format_time(0)
return TextBar.__format_time((self.total - self.n) / avg_rate)


def __calculate_percentage(self):
if self.total == 0:
return 100
return round(100 * self.n / self.total)


def __format_elapsed(self):
if self.n == 0:
return TextBar.__format_time(0)

elapsed = time.time() - self.start_time
return TextBar.__format_time(elapsed)


def __calculate_rate(self):
return self.n / (time.time() - self.start_time)


def __custom_bar_format(self, filled=False):
"""
Retrun a custom bar format encoding text in the middle of the progress bar
:return: the custom bar format
"""
# sets width for the number of current items to match the width of total items
width = len(str(self.total))
if self.total == 0:
l_bar = '100%|'
remaining = '00:00'
else:
l_bar = '{l_bar}'
remaining = '{remaining}'

r_bar = f'| {self.n: >{width}}/' '{total_fmt} [{elapsed}<' \
f'{remaining}' ', {rate_fmt}{postfix}]'
l_bar = f'{self.__calculate_percentage():3d}%' + '|'
remaining = self.__calculate_remaining()
elapsed = self.__format_elapsed()
rate = self.__calculate_rate()
rate_unit = f'{self.unit}/s'
if rate < 1 and rate != 0:
rate = 1 / rate
rate_unit = f's/{self.unit}'

rate = f'{rate:5.2f}'

r_bar = f'| {self.n: >{width}}/{self.total} [{elapsed}<{remaining} {rate}{rate_unit}]'
bar_format = l_bar + r_bar

return l_bar + self.__get_custom_progress_bar(bar_format, filled=filled) + r_bar

def __init__(self, *, text='', **kwargs):
def __init__(self, *args, text='', **kwargs):
"""
Initiazlise the text progress bar
:param text: text to use
"""
self.text = text
super().__init__(**kwargs)
self.start_time = time.time()
self.running_times = [0]
self.n = 0
self.closed = False
#self.position = 0
super().__init__(*args, **kwargs)
self.bar_format = self.__custom_bar_format()
self.refresh()

Expand All @@ -98,14 +165,23 @@ def close(self, text=None, filled=False):
Close the bar while keeping the custom text or applying new one
:param text: new text to apply. if None, use the old one
"""
if self.closed:
return

if text:
self.text = text

if filled:
self.bar_format = self.__custom_bar_format(filled)
tqdm.close(self)
else:
self.bar_format = '{elapsed}| ' + self.text
tqdm.close(self)
self.display('')
self.bar_format = ''
tqdm.close(self)
print('\033[F\r\033[K', end='')
print(f'{self.__format_elapsed()}|', self.text)

self.closed = True


def update(self, n=1, text=None):
Expand Down

0 comments on commit e13ee81

Please sign in to comment.