tools_source: 11
This data as json
| id | tool_id | filename | language | content |
|---|---|---|---|---|
| 11 | 1 | colors.py | py | #!/usr/bin/env python3 """colors — convert between hex, rgb, hsl""" import colorsys import re import sys def hex_to_rgb(h: str) -> tuple[int, int, int]: h = h.lstrip("#") if len(h) == 3: h = "".join(c * 2 for c in h) return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) 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 parse_rgb(text: str) -> tuple[int, int, int]: m = re.match(r"rgb\((\d+),\s*(\d+),\s*(\d+)\)", text) if m: return int(m[1]), int(m[2]), int(m[3]) raise ValueError(f"cannot parse: {text}") def main(): inp = sys.argv[1] if len(sys.argv) > 1 else input().strip() if inp.startswith("#") or re.match(r"^[0-9a-fA-F]{3,8}$", inp): r, g, b = hex_to_rgb(inp) elif inp.startswith("rgb"): r, g, b = parse_rgb(inp) else: print(f"unsupported format: {inp}", file=sys.stderr) sys.exit(1) h, s, l = rgb_to_hsl(r, g, b) hx = f"#{r:02x}{g:02x}{b:02x}" print(f"hex: {hx}") print(f"rgb: rgb({r}, {g}, {b})") print(f"hsl: hsl({h}, {s}%, {l}%)") if __name__ == "__main__": main() |