@kinti/a11y-toolkit 5.25.2 → 5.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +31 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +903 -186
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +110 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +451 -96
  14. package/a11y_toolkit/a11yen301549.py +147 -0
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +182 -36
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +28 -7
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +70 -21
  29. package/a11y_toolkit/a11yscope.py +296 -0
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +54 -11
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +222 -24
  39. package/a11y_toolkit/locales/es.json +223 -25
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +247 -59
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env python3
2
+ """The guided wizard — the Canadian pattern, inverted, in the terminal.
3
+
4
+ 2-3 questions a person CAN answer (what are you building, which standard
5
+ applies to your market) configure everything the engine already knows
6
+ how to do: the audit runs with the right standard and the scope artifact
7
+ carries the machine proposals. (The 508 product tree and the tender-annex
8
+ generator live in the private a11y-toolkit-pro layer.)
9
+
10
+ Everything the wizard does is also available as individual commands
11
+ (audit --standard …, scope --solicitation …): the wizard composes, it
12
+ does not hide. Interactive by design; a piped stdin works too (tests,
13
+ CI) and an exhausted stdin aborts gracefully with the non-interactive
14
+ commands as the message.
15
+ """
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ import sys
21
+
22
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
+ sys.path.insert(0, ROOT)
24
+
25
+ from a11y_toolkit.a11yaudit import audit_html, audit_url # noqa: E402
26
+ from a11y_toolkit.a11yscope import build_scope # noqa: E402
27
+
28
+
29
+ def _t(key):
30
+ from .a11yi18n import pack
31
+ return pack(_LANG).get('wiz', {}).get(key) or key
32
+
33
+
34
+ def _ask(prompt, valid=None, default=None):
35
+ """input() con validación: reintenta hasta respuesta válida; en EOF
36
+ aborta con la salida no-interactiva como mensaje (el wizard compone
37
+ comandos que existen)."""
38
+ while True:
39
+ try:
40
+ ans = input(prompt).strip()
41
+ except EOFError:
42
+ print(_t('wiz_abort'))
43
+ sys.exit(1)
44
+ if not ans and default is not None:
45
+ return default
46
+ if valid is None:
47
+ return ans
48
+ if ans in valid:
49
+ return ans
50
+ print(' ' + '/'.join(valid) + '?')
51
+
52
+
53
+ _YESNO = ('y', 'Y', 's', 'S', 'si', 'sí', 'SI', 'yes', 'YES', 'Yes',
54
+ 'n', 'N', 'no', 'NO', 'No')
55
+ _YES = ('y', 'Y', 's', 'S', 'si', 'sí', 'SI', 'yes', 'YES', 'Yes')
56
+ _NO = ('n', 'N', 'no', 'NO', 'No')
57
+
58
+ _LANG = 'en'
59
+
60
+
61
+ def main(argv):
62
+ global _LANG
63
+ ap = argparse.ArgumentParser(
64
+ description='Guided wizard: 2-3 questions → standard, audit, scope '
65
+ 'and tender annex. Also non-interactive commands exist.')
66
+ ap.add_argument('--url', help='page to audit (skipped from the questions if given)')
67
+ ap.add_argument('--file', help='local html to audit')
68
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
69
+ ap.add_argument('-o', '--out', default='scope.json',
70
+ help='where the scope artifact is written (default scope.json)')
71
+ a = ap.parse_args(argv)
72
+ _LANG = a.lang
73
+
74
+ # Q0: qué auditar (flag o pregunta)
75
+ url = (a.url or '').strip()
76
+ if not url and not a.file:
77
+ url = _ask(_t('wiz_need_url') + ' URL: ', valid=None)
78
+
79
+ # Q1: qué estás construyendo
80
+ tgt = _ask(_t('wiz_q_target'), valid={'1', '2', '3', '4'})
81
+ if tgt == '4':
82
+ raw = _ask(_t('wiz_q_multi'))
83
+ targets = [x.strip() for x in raw.split(',') if x.strip() in ('web', 'documents', 'software')] \
84
+ or ['web']
85
+ target = targets[0]
86
+ else:
87
+ target = {'1': 'web', '2': 'documents', '3': 'software'}[tgt]
88
+ targets = [target]
89
+
90
+ # Q2: qué norma (508 GSA tree: capa privada a11y-toolkit-pro)
91
+ std_map = {'1': 'wcag22', '2': 'en301549', '3': 'rgaa'}
92
+ std = std_map[_ask(_t('wiz_q_std'), valid={'1', '2', '3'})]
93
+
94
+ answers = {}
95
+
96
+ # auditoría con el estándar elegido
97
+ std_arg = std if std in ('en301549', 'rgaa') else None
98
+ if url:
99
+ report = audit_url(url, timeout=30, lang=a.lang, standard=std_arg, target=targets[0])
100
+ else:
101
+ report = audit_html(open(a.file, encoding='utf-8', errors='replace').read()[:2_000_000],
102
+ url=a.file, lang=a.lang, standard=std_arg, target=targets[0])
103
+ if 'error' in report:
104
+ print(json.dumps(report, ensure_ascii=False))
105
+ return 1
106
+
107
+ scope = build_scope([report], standard=std, target=target,
108
+ answers=answers or None, lang=a.lang, targets=targets)
109
+ with open(a.out, 'w', encoding='utf-8') as f:
110
+ json.dump(scope, f, ensure_ascii=False, indent=1)
111
+
112
+ # (el anexo de pliego se retiró: a11y-toolkit-pro lo genera desde este
113
+ # MISMO artifact sellado — wizard_pro en la capa privada)
114
+ print(_t('wiz_done').format(scope=a.out, annex='—', score=report.get('score'),
115
+ ins=scope['counters']['in_scope'],
116
+ pro=scope['counters']['proposed_excluded']))
117
+ return 0
118
+
119
+
120
+ if __name__ == '__main__':
121
+ sys.exit(main(sys.argv[1:]))
@@ -77,6 +77,23 @@ def _hsl_a_rgb(h, s, l):
77
77
  return f(0), f(8), f(4)
78
78
 
79
79
 
80
+ def _hue_deg(x):
81
+ """Ángulo CSS con unidades — deg (por defecto), turn, rad, grad → grados.
82
+ None si no es numérico (antes: rstrip('deg') tragaba '0.5turn' y cascaba)."""
83
+ x = x.strip().lower()
84
+ for suf, factor in (('turn', 360.0), ('grad', 0.9),
85
+ ('rad', 180.0 / math.pi), ('deg', 1.0)):
86
+ if x.endswith(suf):
87
+ try:
88
+ return float(x[:-len(suf)]) * factor
89
+ except ValueError:
90
+ return None
91
+ try:
92
+ return float(x)
93
+ except ValueError:
94
+ return None
95
+
96
+
80
97
  def parse_color(s):
81
98
  """'#rgb' | '#rrggbb' | '#rrggbbaa' | rgb()/rgba() | hsl()/hsla() | nombre CSS
82
99
  → dict r,g,b (y 'a' si hay alfa). Acepta comas o espacios como separadores.
@@ -104,30 +121,40 @@ def parse_color(s):
104
121
  body, alfa_ext = re.split(r'\s*/\s*', body, 1)
105
122
  parts = [p for p in (x.strip() for x in re.split(r'[\s,]+', body)) if p]
106
123
  kind, v = m.group(1), parts
107
- if kind.startswith('rgb'):
124
+ try:
125
+ if kind.startswith('rgb'):
126
+ if len(v) < 3:
127
+ return None
128
+ def _channel(x):
129
+ if x.endswith('%'):
130
+ return max(0, min(255, round(float(x[:-1]) * 2.55)))
131
+ return max(0, min(255, int(float(x))))
132
+ c = {'r': _channel(v[0]), 'g': _channel(v[1]), 'b': _channel(v[2])}
133
+ if len(v) >= 4:
134
+ c['a'] = max(0.0, min(1.0, float(v[3].rstrip('%')) / (100 if v[3].endswith('%') else 1)))
135
+ elif alfa_ext:
136
+ c['a'] = max(0.0, min(1.0, float(alfa_ext.strip().rstrip('%')) / (100 if alfa_ext.strip().endswith('%') else 1)))
137
+ return c
108
138
  if len(v) < 3:
109
139
  return None
110
- def _channel(x):
111
- if x.endswith('%'):
112
- return max(0, min(255, round(float(x[:-1]) * 2.55)))
113
- return max(0, min(255, int(float(x))))
114
- c = {'r': _channel(v[0]), 'g': _channel(v[1]), 'b': _channel(v[2])}
140
+ h_ = _hue_deg(v[0])
141
+ if h_ is None:
142
+ return None
143
+ s_ = max(0.0, min(1.0, float(v[1].rstrip('%')) / 100.0))
144
+ l_ = max(0.0, min(1.0, float(v[2].rstrip('%')) / 100.0))
145
+ r, g, b = _hsl_a_rgb(h_, s_, l_)
146
+ c = {'r': max(0, min(255, r)), 'g': max(0, min(255, g)),
147
+ 'b': max(0, min(255, b))}
115
148
  if len(v) >= 4:
116
149
  c['a'] = max(0.0, min(1.0, float(v[3].rstrip('%')) / (100 if v[3].endswith('%') else 1)))
117
150
  elif alfa_ext:
118
- c['a'] = max(0.0, min(1.0, float(alfa_ext.strip().rstrip('%')) / (100 if alfa_ext.strip().endswith('%') else 1)))
151
+ # hsl(0 0% 0% / 0.5) — sintaxis moderna con barra: MISMO trato
152
+ # que rgb() con barra (el canal existía solo para la rama rgb)
153
+ c['a'] = max(0.0, min(1.0, float(alfa_ext.strip().rstrip('%'))
154
+ / (100 if alfa_ext.strip().endswith('%') else 1)))
119
155
  return c
120
- if len(v) < 3:
121
- return None
122
- h_ = float(v[0].rstrip('deg')) % 360
123
- s_ = max(0.0, min(1.0, float(v[1].rstrip('%')) / 100.0))
124
- l_ = max(0.0, min(1.0, float(v[2].rstrip('%')) / 100.0))
125
- r, g, b = _hsl_a_rgb(h_, s_, l_)
126
- c = {'r': max(0, min(255, r)), 'g': max(0, min(255, g)),
127
- 'b': max(0, min(255, b))}
128
- if len(v) >= 4:
129
- c['a'] = max(0.0, min(1.0, float(v[3].rstrip('%')) / (100 if v[3].endswith('%') else 1)))
130
- return c
156
+ except (ValueError, TypeError, OverflowError):
157
+ return None # contrato: color inválido → None, nunca traceback
131
158
  if t in COLOR_NAMES:
132
159
  h = COLOR_NAMES[t]
133
160
  return {'r': int(h[0:2], 16), 'g': int(h[2:4], 16), 'b': int(h[4:6], 16)}
@@ -213,10 +240,12 @@ def pair(fg_s, bg_s, with_suggestion=True, lang='en'):
213
240
  if fg.get('a', 1) < 1:
214
241
  fg = composite(fg, bg)
215
242
  alpha_note = hexs(fg)
216
- r = ratio(fg, bg)
243
+ # se redondea ANTES de los veredictos: lo mostrado y el veredicto nunca
244
+ # discrepan (un ratio en [4.495,4.5) no puede imprimir "4.5" y fallar)
245
+ r = round(ratio(fg, bg), 2)
217
246
  out = {
218
247
  'text': hexs(fg), 'background': hexs(bg),
219
- 'ratio': round(r, 2),
248
+ 'ratio': r,
220
249
  'verdicts': verdicts(r, lang),
221
250
  }
222
251
  if alpha_note:
@@ -300,20 +329,23 @@ def _percentile(vals, p):
300
329
  def decode_png(data):
301
330
  """Bytes PNG → (ancho, alto, bytes RGB). Sin dependencias.
302
331
 
303
- Soporta color types 0 (gris), 2 (RGB), 3 (paleta) y 6 (RGBA) a 8 bits;
304
- el alfa se compone sobre blanco (las capturas de navegador son opacas).
305
- Lanza ValueError si el PNG está fuera de ese soporte (p. ej. 16 bits)."""
332
+ Soporta color types 0 (gris), 2 (RGB), 3 (paleta) y 6 (RGBA) a 8 bits,
333
+ SIN entrelazado (Adam7); el alfa se compone sobre blanco (las capturas
334
+ de navegador son opacas). Lanza ValueError si el PNG está fuera de ese
335
+ soporte (p. ej. 16 bits, gris+alfa, entrelazado)."""
306
336
  import struct
307
337
  import zlib
308
338
  if data[:8] != b'\x89PNG\r\n\x1a\n':
309
339
  raise ValueError('not a PNG file')
310
340
  pos, idat, w, h, bd, ct, plte = 8, b'', 0, 0, 0, 0, None
341
+ interlace = 0
311
342
  while pos < len(data):
312
343
  ln = struct.unpack('>I', data[pos:pos + 4])[0]
313
344
  kind = data[pos + 4:pos + 8]
314
345
  body = data[pos + 8:pos + 8 + ln]
315
346
  if kind == b'IHDR':
316
347
  w, h, bd, ct = struct.unpack('>IIBB', body[:10])
348
+ interlace = body[12] if len(body) >= 13 else 0
317
349
  elif kind == b'IDAT':
318
350
  idat += body
319
351
  elif kind == b'PLTE':
@@ -323,9 +355,15 @@ def decode_png(data):
323
355
  pos += 12 + ln
324
356
  if bd != 8:
325
357
  raise ValueError(f'PNG bit depth {bd} unsupported (8-bit only)')
326
- channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(ct)
358
+ if ct == 4:
359
+ raise ValueError('PNG color type 4 (grayscale+alpha) unsupported '
360
+ '(convert to RGBA (6) or RGB (2))')
361
+ channels = {0: 1, 2: 3, 3: 1, 6: 4}.get(ct)
327
362
  if channels is None:
328
363
  raise ValueError(f'PNG color type {ct} unsupported')
364
+ if interlace:
365
+ raise ValueError('PNG interlaced (Adam7) unsupported '
366
+ '(export non-interlaced)')
329
367
  if ct == 3 and not plte:
330
368
  raise ValueError('PNG palette without PLTE chunk')
331
369
  raw = zlib.decompress(idat)