Skip to content

Instantly share code, notes, and snippets.

@CCXXXI
Last active August 4, 2021 03:15
Show Gist options
  • Select an option

  • Save CCXXXI/8acfb695ddea5bd8a4e4075af4593bb2 to your computer and use it in GitHub Desktop.

Select an option

Save CCXXXI/8acfb695ddea5bd8a4e4075af4593bb2 to your computer and use it in GitHub Desktop.
Change colors in a css file.
import re
import sys
from colorsys import hls_to_rgb, rgb_to_hls
from itertools import chain
def hex2rgb(x):
x = x.lstrip("#")
if len(x) == 3:
x = "".join(chain(*zip(x, x)))
assert len(x) == 6
return tuple(int(x[i : i + 2], 16) for i in (0, 2, 4))
def rgb2hex(r, g, b):
return f"#{r:02x}{g:02x}{b:02x}"
def rgb2hls(r, g, b):
return rgb_to_hls(r / 255, g / 255, b / 255)
def hls2rgb(h, l, s):
return tuple(int(x * 255) for x in hls_to_rgb(h, l, s))
def change_hls(h, l, s):
return h, (l + 1) / 2, s # increase lightness
# return h, 1 - l, s # reverse lightness
def change_hex(x):
r, g, b = hex2rgb(x)
h, l, s = rgb2hls(r, g, b)
h, l, s = change_hls(h, l, s)
r, g, b = hls2rgb(h, l, s)
x = rgb2hex(r, g, b)
return x
def repl(m: re.Match):
return change_hex(m.group())
if __name__ == "__main__":
if len(sys.argv) == 2:
file = sys.argv[1]
else:
file = input("filename:")
with open(file, "r") as f:
content = f.read()
content = re.sub(r"#[0-9a-f]+(?=[^0-9a-f])", repl, content, flags=re.I)
with open(file, "w") as f:
f.write(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment