Chapter 7, Exercise 2: Colour audit script ========================================== """Audit a site's colour pairs against WCAG contrast thresholds. py audit.py """ def channel(v): v = v / 255 return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4 def luminance(h): r, g, b = (int(h[i:i + 2], 16) for i in (1, 3, 5)) return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) def ratio(fg, bg): a, b = sorted((luminance(fg), luminance(bg)), reverse=True) return (a + 0.05) / (b + 0.05) def darken(h, step=0.9): r, g, b = (int(int(h[i:i + 2], 16) * step) for i in (1, 3, 5)) return f"#{r:02x}{g:02x}{b:02x}" def fix(fg, bg, target=4.5): while ratio(fg, bg) < target: fg = darken(fg) return fg pairs = [ ("Heading", "#4a90d9", "#ffffff"), ("Body text", "#777777", "#ffffff"), ("Link", "#3b82f6", "#ffffff"), ("Caption", "#aaaaaa", "#f5f5f5"), ("Button", "#ffffff", "#7fb069"), ("Footer text", "#c0c0c0", "#222222"), ] print(f"{'Element':<12}{'Text':<9}{'Back':<9}{'Ratio':>7} Body Large") for name, fg, bg in pairs: r = ratio(fg, bg) body = "pass" if r >= 4.5 else "FAIL" large = "pass" if r >= 3 else "FAIL" print(f"{name:<12}{fg:<9}{bg:<9}{r:>5.2f}:1 {body:<5} {large}") if body == "FAIL": if luminance(fg) > luminance(bg): print(f"{'':<12}(text is lighter than its background; darkening cannot help here)") else: new = fix(fg, bg) print(f"{'':<12}suggested text colour: {new} ({ratio(new, bg):.2f}:1)") --- Output (run with Python 3.14.0 on Windows) --- Element Text Back Ratio Body Large Heading #4a90d9 #ffffff 3.34:1 FAIL pass suggested text colour: #3b74af (4.88:1) Body text #777777 #ffffff 4.48:1 FAIL pass suggested text colour: #6b6b6b (5.33:1) Link #3b82f6 #ffffff 3.68:1 FAIL pass suggested text colour: #2f69c6 (5.31:1) Caption #aaaaaa #f5f5f5 2.13:1 FAIL FAIL suggested text colour: #6e6e6e (4.68:1) Button #ffffff #7fb069 2.53:1 FAIL FAIL (text is lighter than its background; darkening cannot help here) Footer text #c0c0c0 #222222 8.74:1 pass pass Note: the white-on-light-green button cannot be fixed by darkening the text; darken the background instead (for example #3d7a2a) or use dark text.