Source code for torchmate.utils.color_text

 1from typing import Optional, Tuple
 2
 3
[docs] 4def colorize_text( 5 text: str, 6 fore_tuple: Tuple[int, int, int] = (0, 0, 0), 7 back_tuple: Optional[Tuple[int, int, int]] = None, 8 bold_text: bool = False, 9) -> str: 10 """Return text formatted with specified foreground color, background color, and optional bold formatting. 11 12 Args: 13 text (str): The text to be colorized. 14 fore_tuple (tuple, optional): A tuple of RGB values (0-255) for the foreground color. Defaults to ``(0, 0, 0)``. 15 back_tuple (tuple, optional): A tuple of RGB values (0-255) for the background color. Defaults to ``(255, 255, 255)``. 16 bold_text (bool, optional): Whether to apply bold formatting to the text. Defaults to ``False``. 17 18 Raises: 19 ValueError: If RGB values in fore_tuple or back_tuple are outside the valid range of 0-255. 20 21 Returns: 22 Str: The formatted text with ANSI color codes embedded. 23 24 25 """ 26 27 if back_tuple is not None: 28 for value in fore_tuple + back_tuple: 29 if value not in range(0, 256): 30 raise ValueError(f"Invalid RGB value: {value}. RGB values must be between 0 and 255.") 31 else: 32 for value in fore_tuple: 33 if value not in range(0, 256): 34 raise ValueError(f"Invalid RGB value: {value}. RGB values must be between 0 and 255.") 35 36 bold_code = "\033[1m" 37 reset_code = "\033[0m" 38 start_command = "\033[" 39 change_fg = "38;2;" 40 change_bg = "48;2;" 41 end_command = "m" 42 43 if back_tuple is not None: 44 rf, gf, bf = fore_tuple 45 rb, gb, bb = back_tuple 46 foreground = change_fg + str(rf) + ";" + str(gf) + ";" + str(bf) 47 background = change_bg + str(rb) + ";" + str(gb) + ";" + str(bb) 48 ansi_color = start_command + foreground + ";" + background + end_command 49 else: 50 rf, gf, bf = fore_tuple 51 foreground = change_fg + str(rf) + ";" + str(gf) + ";" + str(bf) 52 ansi_color = start_command + foreground + end_command 53 54 if bold_text: 55 text = bold_code + ansi_color + text + reset_code 56 else: 57 text = ansi_color + text + reset_code 58 59 return text
60 61
[docs] 62class COLOR: 63 """ 64 BG = Background 65 66 Reference: 67 https://web.archive.org/web/20201214113226/http://ascii-table.com/ansi-escape-sequences.php 68 """ 69 70 BLACK = "\033[30m" 71 RED = "\033[31m" 72 GREEN = "\033[32m" 73 YELLOW = "\033[33m" 74 BLUE = "\033[34m" 75 MAGENTA = "\033[35m" 76 CYAN = "\033[36m" 77 WHITE = "\033[37m" 78 PURPLE = "\033[95m" 79 80 BOLD = "\033[1m" 81 UNDERLINE = "\033[4m" 82 INVERSE = "\033[7m" 83 END = "\033[0m" 84 85 DEFAULT_BG = "\033[41m" 86 BLACK_BG = "\033[40m" 87 RED_BG = "\033[41m" 88 GREEN_BG = "\033[42m" 89 YELLOW_BG = "\033[43m" 90 BLUE_BG = "\033[44m" 91 MAGENTA_BG = "\033[45m" 92 CYAN_BG = "\033[46m" 93 WHITE_BG = "\033[47m"