Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : KA Maps Engine10# File : themes/tools/check.py11# Description : Vérifie les thèmes livrés (`themes/*.json` +12# `themes/brands/*.json`) : contrastes et daltonisme.13# Module : themes14# Repository : https://git.spboucher.ai/ka-maps-engine15# Created : 2026-12-0116# Last Modified : 2026-12-0117#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author : Simon-Pierre Boucher23# Position : Professor of Finance24# Institution : Université du Québec en Outaouais (UQO)25# Department : Département des sciences administratives26# Organization : SP Boucher27#28# Website : https://spboucher.ai29# Git : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General : info@spboucher.ai36# Professional : contact@spboucher.ai37# Direct : simon@spboucher.ai38# Research : research@spboucher.ai39# Development : dev@spboucher.ai40# Support : support@spboucher.ai41# Security/Admin : admin@spboucher.ai42# Notifications : notifications@spboucher.ai43#44# Preferred Contact: support@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification : Public69# Distribution : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License : None specified (no license file in this repository)83# Maintainer : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Vérifie les thèmes livrés (`themes/*.json` + `themes/brands/*.json`) : contrastes et daltonisme.9192Calculs, pas d'appréciation à l'œil :93 1. contraste WCAG 2.x du lettrage contre chaque fond sur lequel il se pose (AA : 4,5:1) ;94 2. contraste du texte des pastilles (tous états, genres et natures) ;95 3. rampes de données : clarté Oklab strictement monotone, écart entre classes voisines, en vision96 normale et simulée (deutéranopie, protanopie, tritanopie — matrices de Machado et al. 2009) ;97 4. états des pastilles distincts deux à deux sous chaque simulation.9899 python3 themes/tools/check.py # tableau + docs/themes/verification.md ; code 1 si échec100"""101import json102import math103import os104import re105import sys106107ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))108THEMES = ["signature", "midnight", "city3d", "minimal", "terrain", "financial", "blueprint"]109BRANDS = ["louka", "immoka", "vraiprix", "valoplex"]110111112# ---------------------------------------------------------------- couleur113def hex_rgba(s):114 s = s.strip()115 if s == "transparent":116 return (0, 0, 0, 0)117 if s == "white":118 return (1, 1, 1, 1)119 if s == "black":120 return (0, 0, 0, 1)121 m = re.fullmatch(r"#([0-9a-fA-F]{3,8})", s)122 if not m:123 raise ValueError(s)124 h = m.group(1)125 if len(h) in (3, 4):126 h = "".join(c * 2 for c in h)127 v = [int(h[i:i + 2], 16) / 255 for i in range(0, len(h), 2)]128 return tuple(v + [1.0])[:4] if len(v) == 3 else tuple(v)129130131def lin(c):132 return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4133134135def unlin(c):136 c = min(1.0, max(0.0, c))137 return c * 12.92 if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055138139140def oklab(rgb):141 r, g, b = (lin(x) for x in rgb[:3])142 l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b143 m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b144 s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b145 l, m, s = (x ** (1 / 3) for x in (l, m, s))146 return (0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,147 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,148 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)149150151def from_oklab(L, a, b):152 l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3153 m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3154 s = (L - 0.0894841775 * a - 1.2914855480 * b) ** 3155 return (unlin(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),156 unlin(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),157 unlin(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s))158159160def resolve(expr, pal, seen=()):161 """Couleur kastyle (littéral, @référence, mix/alpha/lighten/darken) → (r, g, b, a)."""162 if isinstance(expr, str):163 if expr.startswith("@"):164 name = expr[1:]165 if name in seen:166 raise ValueError("cycle " + name)167 return resolve(pal[name], pal, seen + (name,))168 return hex_rgba(expr)169 op = expr[0]170 if op == "alpha":171 c = resolve(expr[1], pal, seen)172 return (*c[:3], expr[2])173 if op == "mix":174 a, b, t = resolve(expr[1], pal, seen), resolve(expr[2], pal, seen), expr[3]175 la, lb = oklab(a), oklab(b)176 return (*from_oklab(*(x + (y - x) * t for x, y in zip(la, lb))), a[3] + (b[3] - a[3]) * t)177 if op in ("lighten", "darken"):178 c = resolve(expr[1], pal, seen)179 L, a, b = oklab(c)180 return (*from_oklab(L + (expr[2] if op == "lighten" else -expr[2]), a, b), c[3])181 raise ValueError(op)182183184def over(fg, bg):185 a = fg[3]186 return tuple(fg[i] * a + bg[i] * (1 - a) for i in range(3)) + (1.0,)187188189def luminance(c):190 r, g, b = (lin(x) for x in c[:3])191 return 0.2126 * r + 0.7152 * g + 0.0722 * b192193194def contrast(a, b):195 la, lb = luminance(a), luminance(b)196 return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)197198199# Machado, Oliveira, Fernandes (2009), sévérité 1,0, appliquées en RVB linéaire.200CVD = {201 "deutéranopie": [[0.367322, 0.860646, -0.227968], [0.280085, 0.672501, 0.047413], [-0.011820, 0.042940, 0.968881]],202 "protanopie": [[0.152286, 1.052583, -0.204868], [0.114503, 0.786281, 0.099216], [-0.003882, -0.048116, 1.051998]],203 "tritanopie": [[1.255528, -0.076749, -0.178779], [-0.078411, 0.930809, 0.147602], [0.004733, 0.691367, 0.303900]],204}205206207def simulate(c, kind):208 if kind == "normale":209 return c210 r, g, b = (lin(x) for x in c[:3])211 m = CVD[kind]212 return tuple(unlin(m[i][0] * r + m[i][1] * g + m[i][2] * b) for i in range(3)) + (1.0,)213214215def delta(a, b):216 return math.dist(oklab(a), oklab(b))217218219VISIONS = ["normale", "deutéranopie", "protanopie", "tritanopie"]220221222# ---------------------------------------------------------------- vérifications223def brand_palette(theme_doc, brand):224 pal = dict(theme_doc["palette"])225 if brand:226 b = json.load(open(os.path.join(ROOT, "brands", f"{brand}.json")))227 pal.update({k: v for k, v in b.get("palette", {}).items() if not k.startswith("_")})228 return pal, b229 return pal, {}230231232TEXT_ON = [233 # (encre, fonds, seuil)234 ("ink", ["land", "residential", "commercial", "park", "forest", "farmland", "building", "road", "road-major", "road-motorway"], 4.5),235 ("ink-soft", ["land", "residential", "commercial", "park", "forest", "building", "road", "road-major"], 4.5),236 ("ink-faint", ["land", "residential", "building", "building-estimated"], 4.5),237 ("water-ink", ["water", "land"], 4.5),238 ("park-ink", ["park", "forest", "land", "cemetery", "golf"], 4.5),239 ("poi-education", ["land", "building", "school"], 4.5),240 ("poi-health", ["land", "building", "hospital"], 4.5),241 ("poi-commerce", ["land", "building", "commercial"], 4.5),242 ("poi-major", ["land", "building"], 4.5),243 ("shield-ink", ["shield"], 4.5),244 ("shield-major-ink", ["shield-major"], 4.5),245]246# Lisibilité des traits (non textuels, WCAG 1.4.11 : 3:1) là où le trait porte une information.247LINE_ON = [248 ("boundary", ["land"], 3.0),249 ("road-far-major", ["land"], 1.6),250 ("building-outline", ["land"], 1.25),251 ("water-line", ["land"], 1.25),252 ("transit-ink", ["land"], 3.0),253]254PILL = [("accent", "accent-ink"), ("accent-good", "accent-good-ink"), ("accent-high", "accent-high-ink"), ("accent-sold", "accent-sold-ink"),255 ("accent-seen", "accent-seen-ink"), ("accent-selected", "accent-selected-ink")]256SEQ = {"value": ["heat-0", "heat-1", "heat-2", "heat-3", "heat-4"], "yield": ["cool-0", "cool-1", "cool-2", "cool-3", "cool-4"]}257DIV = ["cool-div-2", "cool-div-1", "neutral", "heat-div-1", "heat-div-2"]258STATES = ["accent", "accent-good", "accent-high", "accent-seen", "accent-sold"]259260261def check(theme, brand=None):262 doc = json.load(open(os.path.join(ROOT, f"{theme}.json")))263 pal, bdoc = brand_palette(doc, brand)264 R = lambda name: resolve("@" + name, pal)265 land = R("land")266 rows, fails = [], []267268 def row(kind, what, value, need, ok):269 rows.append((kind, what, value, need, ok))270 if not ok:271 fails.append(f"{theme}{'+' + brand if brand else ''} : {kind} {what} = {value} (< {need})")272273 if not brand:274 # L'autoroute se détache du sol par sa chaussée (thème sombre) ou par son filet (thèmes clairs).275 m = max(contrast(R("casing-motorway"), land), contrast(R("road-motorway"), land))276 row("trait", "autoroute (filet ou chaussée) / land", round(m, 2), 1.6, m >= 1.6)277 for ink, grounds, need in TEXT_ON:278 worst = min((contrast(R(ink), over(R(g), land)), g) for g in grounds)279 row("texte", f"{ink} / {worst[1]}", round(worst[0], 2), need, worst[0] >= need)280 for ink, grounds, need in LINE_ON:281 worst = min((contrast(over(R(ink), land), over(R(g), land)), g) for g in grounds)282 row("trait", f"{ink} / {worst[1]}", round(worst[0], 2), need, worst[0] >= need)283 # Pastilles : texte sur fond plein, et (nature estimée / hypothèse) teinte de fond devenue texte sur `paper`.284 kinds = dict(doc["markers"]["pill"]["kinds"])285 for k, v in bdoc.get("markers", {}).get("pill", {}).get("kinds", {}).items():286 kinds[k] = v287 pairs = list(PILL)288 for k, v in kinds.items():289 if k.startswith("_"):290 continue291 d = v.get("default", {})292 if "fill" in d and "text" in d:293 pairs.append((d["fill"], d["text"]))294 paper = R("pill-paper")295 seen_pairs = set()296 for fill, text in pairs:297 key = json.dumps([fill, text])298 if key in seen_pairs:299 continue300 seen_pairs.add(key)301 f = resolve(fill if fill.startswith(("@", "#")) else "@" + fill, pal) if isinstance(fill, str) else resolve(fill, pal)302 tx = resolve(text if text.startswith(("@", "#")) else "@" + text, pal) if isinstance(text, str) else resolve(text, pal)303 name = fill if isinstance(fill, str) else "expr"304 c = contrast(tx, f)305 row("pastille", f"texte sur {name}", round(c, 2), 4.5, c >= 4.5)306 c2 = contrast(f, paper)307 row("pastille", f"{name} en texte et contour sur pill-paper (estimé, hypothèse)", round(c2, 2), 4.5, c2 >= 4.5)308 # États distincts deux à deux, toutes visions.309 for vis in VISIONS:310 worst = (9, "")311 for i, a in enumerate(STATES):312 for b in STATES[i + 1:]:313 d = delta(simulate(R(a), vis), simulate(R(b), vis))314 worst = min(worst, (d, f"{a} / {b}"))315 row("états", f"{vis} : {worst[1]}", round(worst[0], 3), 0.06, worst[0] >= 0.06)316 # Rampes : uniquement celles du thème, ou celles que la marque redéfinit.317 scales = dict(doc["scales"]) if not brand else {}318 for k, v in bdoc.get("scales", {}).items():319 scales[k] = v320 for name, sc in scales.items():321 if name.startswith("_"):322 continue323 cols = [resolve(c, pal) for _, c in sc["stops"]]324 Ls = [oklab(c)[0] for c in cols]325 vals = [v for v, _ in sc["stops"]]326 diverging = vals[0] < 0 < vals[-1]327 if diverging:328 mid = len(cols) // 2329 mono = all(Ls[i] < Ls[i + 1] for i in range(mid)) and all(Ls[i] > Ls[i + 1] for i in range(mid, len(cols) - 1)) or \330 all(Ls[i] > Ls[i + 1] for i in range(mid)) and all(Ls[i] < Ls[i + 1] for i in range(mid, len(cols) - 1))331 else:332 mono = all(Ls[i] > Ls[i + 1] for i in range(len(cols) - 1)) or all(Ls[i] < Ls[i + 1] for i in range(len(cols) - 1))333 row("rampe", f"{name} : clarté monotone", "oui" if mono else "non", "oui", mono)334 for vis in VISIONS:335 sim = [simulate(c, vis) for c in cols]336 adj = min(delta(sim[i], sim[i + 1]) for i in range(len(sim) - 1))337 row("rampe", f"{name} : écart voisin min, {vis}", round(adj, 3), 0.06, adj >= 0.06)338 if diverging:339 ends = delta(sim[0], sim[-1])340 row("rampe", f"{name} : extrêmes, {vis}", round(ends, 3), 0.12, ends >= 0.12)341 # La classe la plus proche du fond doit rester perceptible sur le sol du thème.342 near = min(delta(c, land) for c in cols if c[3] > 0.99) if not diverging else None343 if near is not None:344 row("rampe", f"{name} : classe la plus proche du sol", round(near, 3), 0.02, near >= 0.02)345 return rows, fails346347348def main():349 all_fails = []350 md = ["# Vérification des thèmes — contrastes et daltonisme", "",351 "Produit par `themes/tools/check.py` sur les fichiers livrés ; ne pas modifier à la main.", "",352 "Seuils : texte 4,5:1 (WCAG AA) ; texte de pastille 4,5:1 dans les trois natures ; traits porteurs d'information 3:1, traits de fond selon le rôle ;",353 "écart Oklab (ΔE) entre classes voisines d'une rampe ≥ 0,06 et entre états de pastille ≥ 0,06 (l'état « vu » est aussi plus petit), en vision normale et sous",354 "deutéranopie, protanopie et tritanopie simulées (Machado et al., 2009).", ""]355 for t in THEMES:356 for b in [None] + BRANDS:357 if b and not os.path.exists(os.path.join(ROOT, "brands", f"{b}.json")):358 continue359 rows, fails = check(t, b)360 all_fails += fails361 title = t + (f" + {b}" if b else "")362 bad = [r for r in rows if not r[4]]363 md += [f"## {title}", "", f"{len(rows)} mesures, {len(bad)} sous le seuil.", "", "| Mesure | Objet | Valeur | Seuil | |", "|---|---|---|---|---|"]364 for kind, what, value, need, ok in rows:365 md.append(f"| {kind} | {what} | {value} | {need} | {'✓' if ok else '✗'} |")366 md.append("")367 print(f"{title:24s} {len(rows):3d} mesures, {len(bad)} sous le seuil")368 out = os.path.join(os.path.dirname(ROOT), "docs", "themes", "verification.md")369 os.makedirs(os.path.dirname(out), exist_ok=True)370 open(out, "w").write("\n".join(md) + "\n")371 for f in all_fails:372 print(" ✗", f)373 sys.exit(1 if all_fails else 0)374375376if __name__ == "__main__":377 main()378