Skip to content

Instantly share code, notes, and snippets.

@Alwinfy
Last active March 25, 2024 19:57
Show Gist options
  • Save Alwinfy/64fe59d44b67dbb792f21c4ea78cbe05 to your computer and use it in GitHub Desktop.
Save Alwinfy/64fe59d44b67dbb792f21c4ea78cbe05 to your computer and use it in GitHub Desktop.
bake a poem into a colourful cake
#!/usr/bin/env python3
# bake.py - score a poem with colourized ANSI codes
# Type a poem at stdin, print the colourized poem at stdout.
# Requires at least 256-color support from the teletype.
import sys
def ansi(*codes):
return "\x1b[" + ";".join(map(str, codes)) + "m"
def color(nib):
# this is chosen based on the ANSI 16-color style
# (i.e. 0x1 for red, 0x2 for green,
# 0x4 for blue, 0x8 for brighter),
# but using the 256-color ANSI format
# (i.e. start at 16, add +1 for more red,
# +6 for more green, +36 for more blue),
# with colors picked to land in a nice pastel region.
color = (16 + 2 * 43
+ (nib >> 0 & 1) * 2 * 36
+ (nib >> 1 & 1) * 2 * 6
+ (nib >> 2 & 1) * 2 * 1
+ (nib >> 3 & 1) * 1 * 43
)
ch = chr(nib + (48 if nib < 10 else 55))
return ansi(38, 5, color) + ch
def format_char(ch):
high, low = divmod(ord(ch), 16)
return color(high) + color(low)
for line in list(sys.stdin):
chars = line.strip()
print(" " + " ".join(chars))
print("".join(format_char(ch) for ch in chars) + ansi(0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment