File size: 2,545 Bytes
308cf3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from colorama import Fore, init as colorama_init

import decimal
import platform
import sys

colorama_init()

class ProgressBarStyle:
    def __init__(self, advance_char='β–ˆ', empty_advance_char='β–“', progressbar_length=30):
        self.advance_char = advance_char
        self.empty_advance_char = empty_advance_char
        self.progressbar_length = progressbar_length

DEFAULT_STYLE = ProgressBarStyle()
DEFAULT_RICH_STYLE = ProgressBarStyle(f'{Fore.GREEN}━{Fore.RESET}', f'{Fore.LIGHTBLACK_EX}━{Fore.RESET}', 41)
CLASSIC_STYLE = ProgressBarStyle(f'{Fore.GREEN}β–ˆ{Fore.RESET}', f'{Fore.LIGHTBLACK_EX}β–“{Fore.RESET}')
DRACULA_STYLE = ProgressBarStyle(f'{Fore.RED}β–ˆ{Fore.RESET}', f'{Fore.LIGHTRED_EX}β–“{Fore.RESET}')
GIRL_STYLE    = ProgressBarStyle(f'{Fore.LIGHTMAGENTA_EX}β–ˆ{Fore.RESET}', f'{Fore.MAGENTA}β–“{Fore.RESET}')
DARK_STYLE    = ProgressBarStyle(f'{Fore.LIGHTBLACK_EX}β–ˆ{Fore.RESET}', ' ')
RAINBOW_STYLE = ProgressBarStyle(f'{Fore.RED}β–ˆ{Fore.CYAN}β–ˆ{Fore.YELLOW}β–ˆ{Fore.GREEN}β–ˆ{Fore.BLUE}β–ˆ{Fore.MAGENTA}β–ˆ{Fore.RESET}', '', 10)

class ProgressBar:
    def __init__(self, total, description: str, progress_bar_style=DEFAULT_STYLE):
        self.advance = 0
        self.total = total
        self.description = description
        self.progressbar_length = progress_bar_style.progressbar_length
        self.advance_char = progress_bar_style.advance_char
        self.empty_advance_char = progress_bar_style.empty_advance_char
        self.advance_char_coef = round(self.total/self.progressbar_length, 2)

    @property
    def is_finished(self):
        return self.advance == self.total
    
    def force_finish(self):
        self.advance = self.total

    def render(self):
        if self.is_finished:
            advance_char_count = self.progressbar_length
        else:
            advance_char_count = int(self.advance/self.advance_char_coef)
        advance_percent = round(decimal.Decimal(self.advance/self.total), 2)*100
        if platform.release() == '7' and sys.platform.startswith('win'): # disable rendering for windows 7 (cmd.exe does not support ASCII control characters)
            pass
        else:
            print(f'{self.description}{self.advance_char*advance_char_count}{self.empty_advance_char*(self.progressbar_length-advance_char_count)} {advance_percent}%')
            print('\033[F', end='')
            if self.is_finished:
                print()
            
    def update(self, count):
        self.advance += count