Skip to content

Instantly share code, notes, and snippets.

@Alwinfy
Last active March 25, 2024 19:57

Revisions

  1. Alwinfy revised this gist Mar 25, 2024. 1 changed file with 7 additions and 4 deletions.
    11 changes: 7 additions & 4 deletions bake.py
    Original file line number Diff line number Diff line change
    @@ -8,10 +8,13 @@ def ansi(*codes):
    return "\x1b[" + ";".join(map(str, codes)) + "m"

    def color(nib):
    # this is based on the 256-color ANSI format;
    # start at 16, add +1 for more red,
    # +6 for more green, +36 for more blue.
    # colors were picked to land in a nice pastel region.
    # 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
  2. Alwinfy created this gist Mar 25, 2024.
    31 changes: 31 additions & 0 deletions bake.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    #!/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 based on the 256-color ANSI format;
    # start at 16, add +1 for more red,
    # +6 for more green, +36 for more blue.
    # colors were 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))