pat/pat.py

66 lines
1.8 KiB
Python
Raw Normal View History

2021-03-09 22:15:59 +00:00
#!/usr/bin/python
from enum import IntEnum
2021-03-09 22:36:40 +00:00
from sys import argv, stdin, stderr
2021-03-09 22:15:59 +00:00
from string import whitespace
2021-04-04 15:50:14 +00:00
# These next 2 lines of code are only for ANSI escape support on Windows cmd/powershell
2021-03-09 22:15:59 +00:00
# If you do not use cmd/ps, you can comment them out or remove them
from os import system
2021-03-09 22:36:40 +00:00
2021-03-09 22:15:59 +00:00
system("")
# If the program is using too much memory, try decreasing this value
bytes_to_read = 1000000
class ColorInfo(IntEnum):
AMOUNT = 299
MAX_RGB_VALUE = 255
PER_STAGE = (AMOUNT + 1) // 3
MIN_RGB_VALUE = MAX_RGB_VALUE - PER_STAGE
2021-03-09 22:15:59 +00:00
if len(argv) == 1:
argv.append("-")
for arg in argv[1:]:
2021-03-09 22:36:40 +00:00
try:
file = stdin if arg == "-" else open(arg, "r")
read_result = file.read(bytes_to_read)
2021-03-09 22:36:40 +00:00
except Exception as e:
2021-03-30 23:51:18 +00:00
print(
"Error "
+ (f"reading {file.name}" if "file" in globals() else "opening file")
+ f": {e}",
2021-03-30 23:51:18 +00:00
file=stderr,
)
2021-03-09 22:36:40 +00:00
continue
changes = len(list(filter(lambda c: not c in whitespace, read_result))) - 1
step = 0 if changes == 0 else ColorInfo.AMOUNT / changes
index = 0
for char in read_result:
if char in whitespace:
print(char, end="")
2021-03-09 22:15:59 +00:00
continue
color_value = round(index)
value_modifier = color_value % ColorInfo.PER_STAGE
2021-03-09 22:15:59 +00:00
rgb_values = [
ColorInfo.MIN_RGB_VALUE + value_modifier,
ColorInfo.MAX_RGB_VALUE - value_modifier,
ColorInfo.MIN_RGB_VALUE,
2021-03-09 22:15:59 +00:00
]
[red, green, blue] = [
[rgb_values[1], rgb_values[0], rgb_values[2]],
rgb_values[::-1],
[rgb_values[0], rgb_values[2], rgb_values[1]],
][color_value // ColorInfo.PER_STAGE]
2021-03-09 22:15:59 +00:00
print("\x1b[38;2;%d;%d;%dm%s" % (red, green, blue, char), end="")
index += step
print("\x1b[0m")