-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolortool.py
More file actions
364 lines (284 loc) · 11.8 KB
/
colortool.py
File metadata and controls
364 lines (284 loc) · 11.8 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env python3
"""
colortool -- Color converter, palette generator, contrast checker. Zero deps.
Convert between hex/RGB/HSL, generate palettes, check WCAG accessibility.
Shows terminal color previews where supported.
Usage:
py colortool.py "#ff6b35" # Show all formats
py colortool.py "rgb(255,107,53)" # Parse RGB
py colortool.py "hsl(20,100%,60%)" # Parse HSL
py colortool.py red # Named CSS color
py colortool.py palette "#ff6b35" # Color harmonies
py colortool.py contrast "#ffffff" "#333333" # WCAG contrast ratio
py colortool.py blend "#ff0000" "#0000ff" 5 # Gradient steps
py colortool.py random 5 # Random colors
py colortool.py list # Named CSS colors
"""
import argparse
import colorsys
import math
import os
import random
import re
import sys
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
# Common CSS named colors
NAMED_COLORS = {
"black": (0, 0, 0), "white": (255, 255, 255), "red": (255, 0, 0),
"green": (0, 128, 0), "blue": (0, 0, 255), "yellow": (255, 255, 0),
"cyan": (0, 255, 255), "magenta": (255, 0, 255), "orange": (255, 165, 0),
"purple": (128, 0, 128), "pink": (255, 192, 203), "brown": (165, 42, 42),
"gray": (128, 128, 128), "grey": (128, 128, 128),
"silver": (192, 192, 192), "gold": (255, 215, 0), "navy": (0, 0, 128),
"teal": (0, 128, 128), "olive": (128, 128, 0), "maroon": (128, 0, 0),
"lime": (0, 255, 0), "aqua": (0, 255, 255), "coral": (255, 127, 80),
"salmon": (250, 128, 114), "tomato": (255, 99, 71), "skyblue": (135, 206, 235),
"steelblue": (70, 130, 180), "indigo": (75, 0, 130), "violet": (238, 130, 238),
"crimson": (220, 20, 60), "turquoise": (64, 224, 208), "ivory": (255, 255, 240),
"khaki": (240, 230, 140), "lavender": (230, 230, 250), "plum": (221, 160, 221),
"sienna": (160, 82, 45), "tan": (210, 180, 140), "wheat": (245, 222, 179),
"beige": (245, 245, 220), "chocolate": (210, 105, 30), "firebrick": (178, 34, 34),
"forestgreen": (34, 139, 34), "hotpink": (255, 105, 180), "limegreen": (50, 205, 50),
"midnightblue": (25, 25, 112), "orangered": (255, 69, 0), "royalblue": (65, 105, 225),
"slategray": (112, 128, 144), "springgreen": (0, 255, 127),
}
def color_supported() -> bool:
if os.environ.get("NO_COLOR"):
return False
if sys.platform == "win32":
return bool(os.environ.get("TERM") or os.environ.get("WT_SESSION"))
return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
USE_COLOR = color_supported()
def swatch(r: int, g: int, b: int, width: int = 2) -> str:
"""Render a color swatch using 24-bit ANSI."""
if not USE_COLOR:
return "##"
return f"\033[48;2;{r};{g};{b}m{' ' * width}\033[0m"
def c(code: str, text: str) -> str:
return f"{code}{text}{RESET}" if USE_COLOR else text
# --- Color parsing ---
def parse_color(s: str) -> tuple[int, int, int] | None:
"""Parse color from various formats. Returns (R, G, B) or None."""
s = s.strip().lower()
# Named color
if s in NAMED_COLORS:
return NAMED_COLORS[s]
# Hex: #rgb, #rrggbb
m = re.match(r"^#?([0-9a-f]{6})$", s)
if m:
h = m.group(1)
return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
m = re.match(r"^#?([0-9a-f]{3})$", s)
if m:
h = m.group(1)
return (int(h[0]*2, 16), int(h[1]*2, 16), int(h[2]*2, 16))
# rgb(r,g,b)
m = re.match(r"^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", s)
if m:
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
# hsl(h,s%,l%)
m = re.match(r"^hsl\(\s*(\d+)\s*,\s*(\d+)%?\s*,\s*(\d+)%?\s*\)$", s)
if m:
h, sat, l = int(m.group(1)), int(m.group(2)), int(m.group(3))
return hsl_to_rgb(h, sat, l)
# Try as r,g,b
m = re.match(r"^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)$", s)
if m:
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
return None
# --- Conversions ---
def rgb_to_hex(r: int, g: int, b: int) -> str:
return f"#{r:02x}{g:02x}{b:02x}"
def rgb_to_hsl(r: int, g: int, b: int) -> tuple[int, int, int]:
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
return (round(h * 360), round(s * 100), round(l * 100))
def hsl_to_rgb(h: int, s: int, l: int) -> tuple[int, int, int]:
r, g, b = colorsys.hls_to_rgb(h / 360, l / 100, s / 100)
return (round(r * 255), round(g * 255), round(b * 255))
def rgb_to_hsv(r: int, g: int, b: int) -> tuple[int, int, int]:
h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
return (round(h * 360), round(s * 100), round(v * 100))
def luminance(r: int, g: int, b: int) -> float:
"""Relative luminance (WCAG 2.0)."""
def lin(c):
c = c / 255
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
def contrast_ratio(rgb1: tuple, rgb2: tuple) -> float:
"""WCAG contrast ratio."""
l1 = luminance(*rgb1)
l2 = luminance(*rgb2)
lighter = max(l1, l2)
darker = min(l1, l2)
return (lighter + 0.05) / (darker + 0.05)
def closest_name(r: int, g: int, b: int) -> str:
"""Find closest named color."""
best_name = ""
best_dist = float("inf")
for name, (nr, ng, nb) in NAMED_COLORS.items():
dist = math.sqrt((r - nr)**2 + (g - ng)**2 + (b - nb)**2)
if dist < best_dist:
best_dist = dist
best_name = name
return best_name
# --- Display ---
def show_color(r: int, g: int, b: int, label: str = ""):
"""Display a color with all its representations."""
hex_val = rgb_to_hex(r, g, b)
h, s, l = rgb_to_hsl(r, g, b)
hv, sv, vv = rgb_to_hsv(r, g, b)
name = closest_name(r, g, b)
sw = swatch(r, g, b, 6)
if label:
print(f"\n {c(BOLD, label)}")
print(f"\n {sw} {c(BOLD, hex_val)}")
print(f" RGB: rgb({r}, {g}, {b})")
print(f" HSL: hsl({h}, {s}%, {l}%)")
print(f" HSV: hsv({hv}, {sv}%, {vv}%)")
print(f" Name: ~{name}")
print(f" Lum: {luminance(r, g, b):.3f}")
print()
def show_color_compact(r: int, g: int, b: int, label: str = ""):
"""Compact one-line color display."""
hex_val = rgb_to_hex(r, g, b)
h, s, l = rgb_to_hsl(r, g, b)
sw = swatch(r, g, b, 3)
prefix = f"{label:>15} " if label else " "
print(f"{prefix}{sw} {hex_val} rgb({r:>3},{g:>3},{b:>3}) hsl({h:>3},{s:>3}%,{l:>3}%)")
# --- Commands ---
def cmd_show(color_str: str):
rgb = parse_color(color_str)
if not rgb:
print(f" Error: cannot parse color '{color_str}'", file=sys.stderr)
sys.exit(1)
show_color(*rgb)
def cmd_palette(color_str: str):
rgb = parse_color(color_str)
if not rgb:
print(f" Error: cannot parse color '{color_str}'", file=sys.stderr)
sys.exit(1)
r, g, b = rgb
h, s, l = rgb_to_hsl(r, g, b)
print(f"\n {c(BOLD, 'Color Harmonies')} for {rgb_to_hex(r, g, b)}\n")
# Complementary
comp = hsl_to_rgb((h + 180) % 360, s, l)
print(f" {c(DIM, 'Complementary:')}")
show_color_compact(r, g, b, "base")
show_color_compact(*comp, "complement")
# Analogous
a1 = hsl_to_rgb((h - 30) % 360, s, l)
a2 = hsl_to_rgb((h + 30) % 360, s, l)
print(f"\n {c(DIM, 'Analogous:')}")
show_color_compact(*a1, "-30deg")
show_color_compact(r, g, b, "base")
show_color_compact(*a2, "+30deg")
# Triadic
t1 = hsl_to_rgb((h + 120) % 360, s, l)
t2 = hsl_to_rgb((h + 240) % 360, s, l)
print(f"\n {c(DIM, 'Triadic:')}")
show_color_compact(r, g, b, "base")
show_color_compact(*t1, "+120deg")
show_color_compact(*t2, "+240deg")
# Shades (same hue, different lightness)
print(f"\n {c(DIM, 'Shades (dark to light):')}")
for pct in [20, 35, 50, 65, 80]:
shade = hsl_to_rgb(h, s, pct)
show_color_compact(*shade, f"L={pct}%")
print()
def cmd_contrast(color1_str: str, color2_str: str):
rgb1 = parse_color(color1_str)
rgb2 = parse_color(color2_str)
if not rgb1 or not rgb2:
print(" Error: cannot parse one or both colors", file=sys.stderr)
sys.exit(1)
ratio = contrast_ratio(rgb1, rgb2)
print(f"\n {c(BOLD, 'Contrast Check')}\n")
show_color_compact(*rgb1, "foreground")
show_color_compact(*rgb2, "background")
print()
print(f" Ratio: {c(BOLD, f'{ratio:.2f}:1')}")
print()
# WCAG grades
checks = [
("AA Normal Text", 4.5), ("AA Large Text", 3.0),
("AAA Normal Text", 7.0), ("AAA Large Text", 4.5),
]
for label, threshold in checks:
if ratio >= threshold:
print(f" {c(BOLD + '\033[32m', 'PASS')} {label} (>= {threshold}:1)")
else:
print(f" {c(BOLD + '\033[31m', 'FAIL')} {label} (>= {threshold}:1)")
print()
def cmd_blend(color1_str: str, color2_str: str, steps: int):
rgb1 = parse_color(color1_str)
rgb2 = parse_color(color2_str)
if not rgb1 or not rgb2:
print(" Error: cannot parse colors", file=sys.stderr)
sys.exit(1)
print(f"\n {c(BOLD, 'Gradient')} ({steps} steps)\n")
for i in range(steps):
t = i / (steps - 1) if steps > 1 else 0
r = round(rgb1[0] + (rgb2[0] - rgb1[0]) * t)
g = round(rgb1[1] + (rgb2[1] - rgb1[1]) * t)
b = round(rgb1[2] + (rgb2[2] - rgb1[2]) * t)
show_color_compact(r, g, b, f"step {i+1}")
print()
def cmd_random(count: int):
print(f"\n {c(BOLD, f'{count} Random Colors')}\n")
for i in range(count):
r, g, b = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
show_color_compact(r, g, b, f"#{i+1}")
print()
def cmd_list():
print(f"\n {c(BOLD, 'Named CSS Colors')} ({len(NAMED_COLORS)})\n")
for name in sorted(NAMED_COLORS):
r, g, b = NAMED_COLORS[name]
sw = swatch(r, g, b, 2)
print(f" {sw} {name:<16} {rgb_to_hex(r, g, b)}")
print()
def main():
parser = argparse.ArgumentParser(
description="colortool -- color converter, palette generator, contrast checker",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
sub = parser.add_subparsers(dest="command")
p = sub.add_parser("show", help="Show color in all formats (default)")
p.add_argument("color", help="Color (hex, rgb(), hsl(), name)")
p = sub.add_parser("palette", help="Generate color harmonies")
p.add_argument("color", help="Base color")
p = sub.add_parser("contrast", help="Check WCAG contrast ratio")
p.add_argument("fg", help="Foreground color")
p.add_argument("bg", help="Background color")
p = sub.add_parser("blend", help="Generate gradient between two colors")
p.add_argument("color1", help="Start color")
p.add_argument("color2", help="End color")
p.add_argument("steps", nargs="?", type=int, default=5, help="Number of steps (default: 5)")
p = sub.add_parser("random", help="Generate random colors")
p.add_argument("count", nargs="?", type=int, default=5, help="Number of colors (default: 5)")
sub.add_parser("list", help="List named CSS colors")
args = parser.parse_args()
if args.command == "palette":
cmd_palette(args.color)
elif args.command == "contrast":
cmd_contrast(args.fg, args.bg)
elif args.command == "blend":
cmd_blend(args.color1, args.color2, args.steps)
elif args.command == "random":
cmd_random(args.count)
elif args.command == "list":
cmd_list()
elif args.command == "show":
cmd_show(args.color)
elif not args.command:
# Check if first positional arg looks like a color
remaining = sys.argv[1:]
if remaining and not remaining[0].startswith("-"):
cmd_show(remaining[0])
else:
parser.print_help()
else:
parser.print_help()
if __name__ == "__main__":
main()