color_util.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import colorsys
  2. from typing import NamedTuple, Literal
  3. AnsiMode = Literal['default', 'ansi', '8bit', 'rgb']
  4. def redistribute_rgb(r: int, g: int, b: int) -> tuple[int, int, int]:
  5. """
  6. Redistribute RGB after lightening
  7. Credit: https://stackoverflow.com/a/141943/7346633
  8. """
  9. threshold = 255.999
  10. m = max(r, g, b)
  11. if m <= threshold:
  12. return int(r), int(g), int(b)
  13. total = r + g + b
  14. if total >= 3 * threshold:
  15. return int(threshold), int(threshold), int(threshold)
  16. x = (3 * threshold - total) / (3 * m - total)
  17. gray = threshold - x * m
  18. return int(gray + x * r), int(gray + x * g), int(gray + x * b)
  19. class RGB(NamedTuple):
  20. r: int
  21. g: int
  22. b: int
  23. @classmethod
  24. def from_hex(cls, hex: str) -> "RGB":
  25. """
  26. Create color from hex code
  27. >>> RGB.from_hex('#FFAAB7')
  28. RGB(r=255, g=170, b=183)
  29. :param hex: Hex color code
  30. :return: RGB object
  31. """
  32. while hex.startswith('#'):
  33. hex = hex[1:]
  34. r = int(hex[0:2], 16)
  35. g = int(hex[2:4], 16)
  36. b = int(hex[4:6], 16)
  37. return cls(r, g, b)
  38. def to_ansi_rgb(self, foreground: bool = True) -> str:
  39. """
  40. Convert RGB to ANSI TrueColor (RGB) Escape Code.
  41. This uses the 24-bit color encoding (an uint8 for each color value), and supports 16 million
  42. colors. However, not all terminal emulators support this escape code. (For example, IntelliJ
  43. debug console doesn't support it).
  44. Currently, we do not know how to detect whether a terminal environment supports ANSI RGB. If
  45. you have any thoughts, feel free to submit an issue on our Github page!
  46. :param foreground: Whether the color is for foreground text or background color
  47. :return: ANSI RGB escape code like \033[38;2;255;100;0m
  48. """
  49. c = '38' if foreground else '48'
  50. return f'\033[{c};2;{self.r};{self.g};{self.b}m'
  51. def to_ansi_8bit(self, foreground: bool = True) -> str:
  52. """
  53. Convert RGB to ANSI 8bit 256 Color Escape Code.
  54. This encoding supports 256 colors in total.
  55. :return: ANSI 256 escape code like \033[38;5;206m'
  56. """
  57. r, g, b = self.r, self.g, self.b
  58. sep = 42.5
  59. while True:
  60. if r < sep or g < sep or b < sep:
  61. gray = r < sep and g < sep and b < sep
  62. break
  63. sep += 42.5
  64. if gray:
  65. color = 232 + (r + g + b) / 33
  66. else:
  67. color = 16 + int(r / 256. * 6) * 36 + int(g / 256. * 6) * 6 + int(b / 256. * 6)
  68. c = '38' if foreground else '48'
  69. return f'\033[{c};5;{int(color)}m'
  70. def to_ansi_16(self, foreground: bool = True) -> str:
  71. """
  72. Convert RGB to ANSI 16 Color Escape Code
  73. :return: ANSI 16 escape code
  74. """
  75. raise NotImplementedError()
  76. def to_ansi(self, mode: AnsiMode, foreground: bool = True):
  77. if mode == 'rgb':
  78. return self.to_ansi_rgb(foreground)
  79. if mode == '8bit':
  80. return self.to_ansi_8bit(foreground)
  81. if mode == 'ansi':
  82. return self.to_ansi_16(foreground)
  83. def lighten(self, multiplier: float) -> 'RGB':
  84. """
  85. Lighten the color by a multiplier
  86. :param multiplier: Multiplier
  87. :return: Lightened color (original isn't modified)
  88. """
  89. return RGB(*redistribute_rgb(*[v * multiplier for v in self]))
  90. def set_light(self, light: int) -> 'RGB':
  91. """
  92. Set HSL lightness value
  93. :param light: Lightness value
  94. :return: New color (original isn't modified)
  95. """
  96. h, l, s = colorsys.rgb_to_hls(*[v / 255.0 for v in self])
  97. return RGB(*[round(v * 255.0) for v in colorsys.hls_to_rgb(h, light, s)])