-
Notifications
You must be signed in to change notification settings - Fork 0
/
phonochrome.py
131 lines (111 loc) · 3 KB
/
phonochrome.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""
Phonochrome: A bijective 8-bit RGB encoding library that generates phonotactically plausible appellations.
"""
import re as _re
import sys as _sys
if _sys.version_info >= (3, 9):
# Use the built-in tuple with type parameters for Python 3.9+
RGB = tuple[int, int, int]
else:
# Use Tuple from typing for Python 3.8 and earlier
from typing import Tuple as _Tuple
RGB = _Tuple[int, int, int]
C = [
"b",
"c",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
"m",
"n",
"p",
"r",
"t",
"v",
"z",
]
V = [
"a",
"e",
"i",
"o",
"u",
"ai",
"io",
"as",
"é",
"ó",
"us",
"ü",
"ia",
"is",
"í",
"os",
]
def encode(rgb: RGB):
"""Encode an 8-bit RGB tuple into a phonochrome appellation."""
if any(c not in range(256) for c in rgb):
raise ValueError("Invalid 8-bit RGB tuple: {rgb}".format(rgb=rgb))
m = ""
for idx, component in enumerate(rgb):
c = C[idx:] + C[:idx]
v = V[idx:] + V[:idx]
h = hex(component)[2:].zfill(2)
m += c[int(h[0], 16)] + v[int(h[1], 16)]
return m
def decode(s: str) -> RGB:
"""Decode a phonochrome appellation into an 8-bit RGB tuple."""
if not s:
return ""
jc = "|".join(C)
jv = "|".join(sorted(V, key=len, reverse=True))
pattern = _re.compile(
"".join(
"(?P<c{i}>{jc})(?P<v{i}>{jv})".format(i=i, jc=jc, jv=jv)
for i in range(1, 4)
)
)
match = pattern.match(s)
if not match:
raise ValueError("Invalid appellation: '{s}'".format(s=s))
groups = match.groups()
rgb = []
for idx, (c, v) in enumerate(zip(groups[::2], groups[1::2])):
C_idx = (C[idx:] + C[:idx]).index(c)
V_idx = (V[idx:] + V[:idx]).index(v)
int_str = "{:1x}{:1x}".format(C_idx, V_idx)
rgb.append(int(int_str, 16))
return tuple(rgb)
def _print_and_exit(func, *args):
try:
print(func(*args))
except ValueError as e:
print("Error: " + str(e))
_sys.exit(2)
else:
_sys.exit(0)
def main():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(title="Commands", dest="command")
# Encode Parser
encode_parser = subparsers.add_parser("encode", help=encode.__doc__)
encode_parser.add_argument("r", type=int, help="Red component (0-255)")
encode_parser.add_argument("g", type=int, help="Green component (0-255)")
encode_parser.add_argument("b", type=int, help="Blue component (0-255)")
# Decode Parser
decode_parser = subparsers.add_parser("decode", help=decode.__doc__)
decode_parser.add_argument("word", type=str, help="Phonochrome to decode")
args = parser.parse_args()
if args.command == "encode":
_print_and_exit(encode, (args.r, args.g, args.b))
elif args.command == "decode":
_print_and_exit(decode, args.word)
else:
parser.print_help()
if __name__ == "__main__":
main()