import logging import math import re import matplotlib from django.db import models from django.utils.safestring import mark_safe re_hex = re.compile("^([0-9a-f]{3,6})(\W)?", re.IGNORECASE) def hex2rgb(hexval): return matplotlib.colors.to_rgb(hexval) def light_or_dark(rgbColor, colors: tuple = ('#FFFFFF', '#333333')): if isinstance(rgbColor, str): rgbColor = hex2rgb(rgbColor) [r, g, b] = rgbColor val = 0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b) hsp = math.sqrt(val) # logging.error([rgbColor, val, hsp]) # if hsp > 127.5: if hsp > .5: # light return colors[1] else: # dark return colors[0] def invert_hex(hexval: str): def _invert(content): text = content.group(1).lower() code = {} l1 = "0123456789abcdef" l2 = "fedcba9876543210" for i in range(len(l1)): code[l1[i]] = l2[i] inverted = "" for j in text: inverted += code[j] return inverted prepend_hash = '' if hexval.startswith('#'): hexval = hexval[1:] prepend_hash = '#' return prepend_hash + re_hex.sub(_invert, hexval) def color_label(instance: models.Model, value:str=None): value = value or instance.color return mark_safe(f'