import shutil import sys import time from .misc import format_time begin_time = 0 recent_times = [] def progress_bar(current, total, msg=None, premsg=None, barmsg=None): global begin_time, recent_times current_time = time.time() if current == 0: begin_time = time.time() # Reset for new bar. recent_times = [begin_time] total_time = 0 estimated_time = 0 step_time = 0 else: recent_elapse = current_time - recent_times[0] step_time = recent_elapse / len(recent_times) total_time = current_time - begin_time estimated_time = (total - current) * step_time recent_times = (recent_times + [current_time])[-100:] show_opt = int(current_time) % 6 >= 3 and current < total show_barmsg = barmsg is not None and show_opt str0 = f"{premsg} [" if premsg else '[' str1 = f"] {current:d}/{total:d} | Step: {format_time(step_time)} | " + ( f"Eta: {format_time(estimated_time)}" if show_opt else f"Tot: {format_time(total_time)}" ) if msg: str1 += f" | {msg}" tot_cols = shutil.get_terminal_size().columns - 10 bar_length = tot_cols - len(str0) - len(str1) if show_barmsg and bar_length < len(barmsg): sys.stdout.write(str0[:-1] + barmsg) elif bar_length <= 0: sys.stdout.write(str0[:-1] + str1[2:]) else: current_len = int(bar_length * current / total) rest_len = int(bar_length - current_len) str_bar = '' if current_len > 0: str_bar += '=' * (current_len - 1) + '>' str_bar += '.' * rest_len if show_barmsg: str_bar = barmsg + str_bar[len(barmsg):] sys.stdout.write(str0 + str_bar + str1) sys.stdout.write('\r' if current < total else '\n') sys.stdout.flush()