impl/python/contrast_ratio.py
874 bytes · the Python implementation · view raw
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from .charts_color_parse_hex import parse_hex
from .charts_color_srgb_to_linear import srgb_to_linear
from .math_round_float import round_float ← from math.round-float ^1.0.0 · built alongside by fune
def relative_luminance(hex: str) -> float: # noqa: A002
"""WCAG 2.x relative luminance: linear-light R, G, B weighted 0.2126, 0.7152, 0.0722."""
c = parse_hex(hex)
return 0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
def luminance_contrast(a: str, b: str) -> float:
"""(lighter + 0.05) / (darker + 0.05), unrounded."""
la = relative_luminance(a)
lb = relative_luminance(b)
return (la + 0.05) / (lb + 0.05) if la > lb else (lb + 0.05) / (la + 0.05)
def contrast_ratio(foreground: str, background: str) -> float:
"""The WCAG 2.x contrast ratio, 1 to 21, rounded to 6 places."""
return round_float(luminance_contrast(foreground, background), 6)