SPB Git

Repository Public License Research preview

validate_accessibility.py 5.4 KB 108 lines python

1#!/usr/bin/env python32"""Objective accessibility checks. They support, and do not replace, a human accessibility review.34- WCAG 2.x contrast ratios of the semantic palette (brand/colors.tex), dark and print modes:5  body text ≥ 7:1, secondary text and meaning-bearing accents ≥ 4.5:1, non-text structure ≥ 3:1.6- Every figure used in a deck has alt text of at least 150 characters; alt-text.md is generated and current.7- Captions template is honestly marked as not synchronised; no font below the type-scale minimum.8- PDF metadata language and author (when a build exists).9"""10from __future__ import annotations1112import argparse13import re14import subprocess15import sys1617from atlaslib import DIST_DIR, ROOT, Report, load_course, load_yaml, select_sessions, session_dir1819TEXT_PAIRS = [("atlasFg", "atlasBg", 7.0), ("atlasFg", "atlasPanel", 7.0), ("atlasFg", "atlasCodeBg", 7.0),20              ("atlasMuted", "atlasBg", 4.5), ("atlasMuted", "atlasPanel", 4.5),21              ("atlasFlow", "atlasBg", 4.5), ("atlasValid", "atlasBg", 4.5), ("atlasUncertain", "atlasBg", 4.5),22              ("atlasHazard", "atlasBg", 4.5), ("atlasFlow", "atlasPanel", 4.5), ("atlasValid", "atlasPanel", 4.5),23              ("atlasUncertain", "atlasPanel", 4.5), ("atlasHazard", "atlasPanel", 4.5)]24MIN_ALT = 150252627def luminance(hex_color: str) -> float:28    def channel(v: int) -> float:29        c = v / 25530        return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.431    r, g, b = (int(hex_color[i:i + 2], 16) for i in (0, 2, 4))32    return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)333435def contrast(a: str, b: str) -> float:36    la, lb = sorted((luminance(a), luminance(b)), reverse=True)37    return (la + 0.05) / (lb + 0.05)383940def palette() -> tuple[dict, dict]:41    text = (ROOT / "brand" / "colors.tex").read_text(encoding="utf-8")42    base = dict(re.findall(r"\\definecolor\{(\w+)\}\{HTML\}\{([0-9A-Fa-f]{6})\}", text))43    sem = re.findall(r"\\AtlasSemantic\{(\w+)\}\{(\w+)\}\{(\w+)\}", text)44    return {n: base[d] for n, d, _ in sem}, {n: base[p] for n, _, p in sem}454647def main() -> int:48    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)49    ap.add_argument("--session")50    args = ap.parse_args()51    rep = Report("accessibility")52    dark, light = palette()53    table = []54    for mode, pal in (("dark", dark), ("print", light)):55        for fg, bg, need in TEXT_PAIRS:56            ratio = contrast(pal[fg], pal[bg])57            table.append({"mode": mode, "fg": fg, "bg": bg, "ratio": round(ratio, 2), "required": need})58            if ratio < need:59                rep.error(f"contrast {mode}: {fg} on {bg} = {ratio:.2f}:1 (needs {need}:1)")60        ratio = contrast(pal["atlasRule"], pal["atlasBg"])61        table.append({"mode": mode, "fg": "atlasRule", "bg": "atlasBg", "ratio": round(ratio, 2), "required": 1.6})62        if ratio < 1.6:63            rep.error(f"contrast {mode}: structural rules too faint ({ratio:.2f}:1)")64    rep.data["contrast"] = table65    rep.note(f"palette: {len(table)} contrast pairs checked; lowest text ratio "66             f"{min(t['ratio'] for t in table if t['required'] >= 4.5):.2f}:1")6768    for s in select_sessions(load_course(), args.session):69        d, sid = session_dir(s), s["id"]70        mpath = d / "figures" / "manifest.yaml"71        if mpath.exists():72            for f in load_yaml(mpath)["figures"]:73                if len(f.get("alt", "")) < MIN_ALT:74                    rep.error(f"{sid}: figure {f['id']} alt text shorter than {MIN_ALT} characters")75                if not f.get("caption"):76                    rep.error(f"{sid}: figure {f['id']} has no caption")77        r = subprocess.run([sys.executable, str(ROOT / "tools" / "render_docs.py"), "--check", "--session", sid],78                           capture_output=True, text=True)79        if r.returncode:80            rep.error(f"{sid}: alt-text.md or explanations.md out of date — {r.stderr.strip()}")81        vtt = d / "video" / "captions-template.vtt"82        if vtt.exists():83            t = vtt.read_text(encoding="utf-8")84            if not t.startswith("WEBVTT") or "NON synchronisé" not in t:85                rep.error(f"{sid}: captions template must be valid WebVTT and marked as not synchronised")86        for src in list((d / "figures" / "src").glob("*.tex")) + list((d / "slides").rglob("*.tex")):87            for size in re.findall(r"\\fontsize\{([\d.]+)\}", src.read_text(encoding="utf-8")):88                if float(size) < 6:89                    rep.error(f"{sid}: {src.name} uses a {size} pt font (minimum 6 pt ≈ 13 pt projected)")90        pdf = DIST_DIR / "slides" / f"{sid}.pdf"91        if pdf.exists():92            info = subprocess.run(["pdfinfo", str(pdf)], capture_output=True, text=True).stdout93            if "Simon-Pierre Boucher" not in info:94                rep.error(f"{sid}: PDF metadata lacks the author")95            if not re.search(r"Title:\s+\S", info):96                rep.error(f"{sid}: PDF metadata lacks a title")97            text = subprocess.run(["pdftotext", str(pdf), "-"], capture_output=True, text=True).stdout98            if len(text) < 500:99                rep.error(f"{sid}: PDF text is not extractable")100        else:101            rep.warn(f"{sid}: no compiled PDF — metadata checks skipped")102    rep.warn("Beamer output is not a tagged PDF; alt text is delivered through alt-text.md (see docs/accessibility.md)")103    return rep.finish()104105106if __name__ == "__main__":107    sys.exit(main())108
Files main
Menu

Theme