@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,296 @@
1
+ #!/usr/bin/env python3
2
+ """Applicability scope — the layer between the audit and the conformance claim.
3
+
4
+ Pattern learned from the Government of Canada CIO wizard (EN 301 549 V4.1.1):
5
+ conformance is not "run all 55", it is "answer what the product IS, then the
6
+ applicable clauses fall out". Their wizard asks 118 questions a human answers
7
+ by hand. This engine does the semi-automatic inverse: it reads what the
8
+ audit actually SAW (the features block: media elements, form controls) and
9
+ proposes the structural exclusions a human only needs to confirm.
10
+
11
+ The honesty rule is load-bearing, borrowed from the evidence pack:
12
+ - the machine PROPOSES ('proposed-excluded') from positive evidence —
13
+ zero <video> elements is evidence, "no 1.2.x finding fired" is NOT
14
+ (absence of signal ≠ absence of content);
15
+ - only a human answer turns a proposal into 'excluded';
16
+ - only 'excluded' rows may become not-applicable downstream (evidence
17
+ pack matrix, VPAT/OpenACR levels). A proposal never excludes anything.
18
+
19
+ With --standard en301549 every row carries its EN 301 549 V4.1.1 clause
20
+ (9.x web / 10.x documents / 11.x software — numbering identity verified
21
+ 55/55 against the official wizard), and the EN-only families (5, 6, 7, 8,
22
+ 12, 13) appear as honest applicability rows this engine does not evaluate.
23
+
24
+ CLI:
25
+ a11yscope.py audit.json [otro.json …] [--standard en301549] [--target web]
26
+ [--answers human.json] [--lang en] [-o scope.json]
27
+ """
28
+
29
+ import argparse
30
+ import hashlib
31
+ import json
32
+ import sys
33
+ from datetime import datetime, timezone
34
+
35
+ STANDARDS = ('wcag22', 'en301549', 'rgaa') # 508 GSA tree: capa privada pro
36
+ STATUS_ORDER = ('in-scope', 'proposed-excluded', 'excluded')
37
+
38
+ # Criterios cuya aplicabilidad depende de un rasgo ESTRUCTURAL detectable:
39
+ # si el rasgo está AUSENTE en la muestra auditada, el criterio se propone
40
+ # excluido (el humano confirma). Fuera de estos dos grupos, nada se propone:
41
+ # la ausencia de señal no es evidencia de ausencia.
42
+ _MEDIA_CRITERIA = ('1.2.1', '1.2.2', '1.2.3', '1.2.4', '1.2.5', '1.4.2')
43
+ _FORM_CRITERIA = ('1.3.5', '3.3.1', '3.3.2', '3.3.3', '3.3.4', '3.3.7', '3.3.8',
44
+ '3.3.9')
45
+
46
+
47
+ def _canon(obj):
48
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
49
+
50
+
51
+ def _sha256(obj):
52
+ return hashlib.sha256(_canon(obj).encode('utf-8')).hexdigest()
53
+
54
+
55
+ def collect_features(reports):
56
+ """Suma el bloque features de todos los informes que lo lleven.
57
+
58
+ Devuelve (features, disponible): sin features (informes previos a la
59
+ versión que los introduce) NO hay propuestas — se dice, no se inventa.
60
+ """
61
+ feats = {'video': 0, 'audio': 0, 'track': 0, 'embed': 0, 'iframe': 0,
62
+ 'object': 0, 'form': 0, 'input': 0, 'select': 0, 'textarea': 0,
63
+ 'table': 0}
64
+ seen = False
65
+ for rep in reports:
66
+ block = rep.get('features')
67
+ if not isinstance(block, dict):
68
+ continue
69
+ seen = True
70
+ for k in feats:
71
+ v = block.get(k)
72
+ if isinstance(v, int) and v > 0:
73
+ feats[k] += v
74
+ return feats, seen
75
+
76
+
77
+ def _media_state(feats, findings_codes):
78
+ """'present' | 'embedded' | 'absent'.
79
+
80
+ iframe/embed/object PUEDEN portar vídeo (YouTube embebido): si solo hay
81
+ embeds, los medios quedan 'embedded' — indeterminado, el criterio se
82
+ mantiene en alcance porque la exclusión exige ausencia estructural.
83
+ """
84
+ if feats['video'] or feats['audio'] or feats['track']:
85
+ return 'present'
86
+ # respaldo positivo: un hallazgo 1.2.x SÓLO dispara si el parser vio
87
+ # medios — no es ausencia de señal, es contenido con problema
88
+ if any(c.startswith('1.2.') for c in findings_codes):
89
+ return 'present'
90
+ if feats['embed'] or feats['iframe'] or feats['object']:
91
+ return 'embedded'
92
+ return 'absent'
93
+
94
+
95
+ def _forms_present(feats, findings_codes):
96
+ if feats['form'] or feats['input'] or feats['select'] or feats['textarea']:
97
+ return True
98
+ # señales 3.3.x/1.3.5: solo disparan sobre campos reales
99
+ return any(c.startswith('3.3.') or c == '1.3.5' for c in findings_codes)
100
+
101
+
102
+ def build_scope(reports, standard='wcag22', target='web', answers=None,
103
+ lang='en', targets=None):
104
+ """Informes (lista de dicts) + respuestas humanas → alcance a11y-scope/1."""
105
+ if standard not in STANDARDS:
106
+ raise ValueError(f"standard must be one of {STANDARDS}, got {standard!r}")
107
+ from . import a11yen301549 as enstd
108
+ from .a11yi18n import pack
109
+ from .a11ycrit import _C
110
+ tx = pack(lang).get('scope', {}) or {}
111
+
112
+ if targets:
113
+ targets = [x for x in targets if x in ('web', 'documents', 'software')] or [target]
114
+ else:
115
+ targets = [target]
116
+ reports = [r for r in reports if isinstance(r, dict)]
117
+ findings_codes = set()
118
+ for rep in reports:
119
+ raw = rep.get('findings')
120
+ if not isinstance(raw, list):
121
+ continue # informe malformado: sin hallazgos aprovechables
122
+ for h in raw:
123
+ if not isinstance(h, dict):
124
+ continue
125
+ crit = h.get('criterion')
126
+ if isinstance(crit, str) and crit:
127
+ findings_codes.add(crit.split(' ')[0])
128
+
129
+ feats, features_seen = collect_features(reports)
130
+ media = _media_state(feats, findings_codes) if features_seen else 'unknown'
131
+ forms = _forms_present(feats, findings_codes) if features_seen else None
132
+
133
+ answers = answers or {}
134
+ if not isinstance(answers, dict):
135
+ raise ValueError('answers must be an object keyed by criterion code')
136
+
137
+ codes_aa = sorted(k for k, v in _C.items() if v[0] in ('A', 'AA'))
138
+ criteria = []
139
+ for code in codes_aa:
140
+ name = (_C[code][1].get(lang) or _C[code][1]['en'])[0]
141
+ row = {'criterion': f'{code} {name}', 'level': _C[code][0]}
142
+ if standard == 'en301549':
143
+ row['clause'] = enstd.clause_for(code, targets[0])
144
+ if len(targets) > 1:
145
+ row['clauses'] = {tg: enstd.clause_for(code, tg) for tg in targets}
146
+
147
+ ans = answers.get(code)
148
+ if isinstance(ans, str): # abreviatura: "excluded"/"in-scope"
149
+ ans = {'status': ans}
150
+ if isinstance(ans, dict) and ans.get('status') in STATUS_ORDER:
151
+ row['status'] = ans['status']
152
+ row['evidence_source'] = 'human'
153
+ if ans.get('reason'):
154
+ row['reason'] = str(ans['reason'])[:500]
155
+ elif code in _MEDIA_CRITERIA and media == 'absent':
156
+ row['status'] = 'proposed-excluded'
157
+ row['evidence_source'] = 'machine:features'
158
+ row['evidence'] = tx.get('evidence_media_absent')
159
+ elif code in _MEDIA_CRITERIA and media == 'embedded':
160
+ # embeds pueden portar vídeo: indeterminado, queda en alcance
161
+ row['status'] = 'in-scope'
162
+ row['evidence'] = tx.get('evidence_media_embedded')
163
+ elif code == '1.2.4' and media == 'present':
164
+ # con medios presentes, en directo vs pregrabado no se distingue
165
+ # en estático: queda en alcance con nota de decisión humana
166
+ row['status'] = 'in-scope'
167
+ row['evidence'] = tx.get('evidence_live_human')
168
+ elif code in _FORM_CRITERIA and forms is False:
169
+ row['status'] = 'proposed-excluded'
170
+ row['evidence_source'] = 'machine:features'
171
+ row['evidence'] = tx.get('evidence_forms_absent')
172
+ else:
173
+ row['status'] = 'in-scope'
174
+ if code in _MEDIA_CRITERIA:
175
+ row['evidence'] = tx.get('evidence_media_present')
176
+ elif code in _FORM_CRITERIA:
177
+ row['evidence'] = tx.get('evidence_forms_present')
178
+ criteria.append(row)
179
+
180
+ if standard == 'rgaa':
181
+ from . import a11yrgaa
182
+ criteria = [{'criterion': c['num'] + ' ' + c['title'],
183
+ 'status': 'in-scope'} for c in a11yrgaa.CRITERIA]
184
+ # las respuestas humanas también aplican a RGAA (antes se descartaban:
185
+ # counters.excluded siempre 0). La máquina NUNCA propone en rgaa —
186
+ # solo una respuesta humana mueve filas. La clave puede venir como el
187
+ # num exacto ('1.1') o con cola de test ('1.1.1'): el num de la fila
188
+ # es el prefijo — el match con separador evita 1.1 vs 1.10.
189
+ for key, ans in answers.items():
190
+ if not isinstance(key, str):
191
+ continue
192
+ a = {'status': ans} if isinstance(ans, str) else (
193
+ ans if isinstance(ans, dict) else None)
194
+ if not a or a.get('status') not in STATUS_ORDER:
195
+ continue
196
+ for row in criteria:
197
+ num = row['criterion'].split(' ')[0]
198
+ if key == num or key.startswith(num + '.'):
199
+ row['status'] = a['status']
200
+ row['evidence_source'] = 'human'
201
+ if a.get('reason'):
202
+ row['reason'] = str(a['reason'])[:500]
203
+
204
+ std508_block = None # 508 GSA tree: moved to the private pro layer
205
+
206
+ counters = {
207
+ 'criteria': len(criteria),
208
+ 'in_scope': sum(1 for r in criteria if r['status'] == 'in-scope'),
209
+ 'proposed_excluded': sum(1 for r in criteria if r['status'] == 'proposed-excluded'),
210
+ 'excluded': sum(1 for r in criteria if r['status'] == 'excluded'),
211
+ }
212
+ if standard == 'en301549':
213
+ # el contador espejo del "Total Clauses" del wizard oficial: solo
214
+ # cuentan las cláusulas EN aplicables (en alcance o excluidas por
215
+ # humano — una propuesta no descuenta)
216
+ counters['en_clauses_applicable'] = counters['in_scope'] + counters['excluded']
217
+
218
+ scope = {
219
+ 'section508': std508_block,
220
+ 'format': 'a11y-scope/1',
221
+ 'lang': lang,
222
+ 'generated': datetime.now(timezone.utc).isoformat(timespec='seconds'),
223
+ 'tool': 'a11y-toolkit (github.com/kinti/a11y-toolkit)',
224
+ 'standard': (enstd.STANDARD_NAME if standard == 'en301549'
225
+ else a11yrgaa.STANDARD_NAME if standard == 'rgaa'
226
+ else 'WCAG 2.2 (A/AA)'),
227
+ 'target': target,
228
+ 'features_observed': feats if features_seen else None,
229
+ 'features_evidence': bool(features_seen),
230
+ 'criteria': criteria,
231
+ 'counters': counters,
232
+ 'notice': tx.get('notice'),
233
+ }
234
+ if not features_seen:
235
+ scope['limitations'] = [tx.get('no_features_note')]
236
+ if standard == 'en301549':
237
+ fam_rows = []
238
+ for fam in enstd.family_rows(lang):
239
+ def _status_for(tg):
240
+ if fam['family'] == '12':
241
+ return 'in-scope'
242
+ if fam['family'] in ('6', '7', '8') and tg == 'web':
243
+ # un producto web no lleva RTT/transmisión de vídeo/hardware:
244
+ # propuesta de la MISMA lógica que usa el wizard oficial
245
+ return 'proposed-excluded'
246
+ return 'human-review'
247
+ status = _status_for(targets[0])
248
+ row_f = {**fam, 'status': status,
249
+ 'evaluated_by_toolkit': False}
250
+ if len(targets) > 1:
251
+ row_f['status_per_target'] = {tg: _status_for(tg) for tg in targets}
252
+ fam_rows.append(row_f)
253
+ scope['en301549_families'] = fam_rows
254
+ if 'software' in targets:
255
+ # cláusulas EN-only de la cláusula 11 (11.5-11.7): aplicabilidad
256
+ # honesta que este motor NO evalúa — revisión humana, jamás una
257
+ # propuesta (la forma del producto NO las decide, a diferencia de
258
+ # 6/7/8 en web) y jamás un claim de conformidad
259
+ scope['en301549_software_clauses'] = [
260
+ {**row, 'status': 'human-review', 'evaluated_by_toolkit': False}
261
+ for row in enstd.software_clause_rows(lang)]
262
+ # el sello excluye el reloj: re-emitir el mismo alcance → mismo sha
263
+ scope['sha256'] = _sha256({k: v for k, v in scope.items() if k != 'generated'})
264
+ return scope
265
+
266
+
267
+ def main(argv):
268
+ from .a11yen301549 import TARGETS
269
+ ap = argparse.ArgumentParser(description='Applicability scope (semi-automatic)')
270
+ ap.add_argument('reports', nargs='+', help='audit report JSON files (any mode)')
271
+ ap.add_argument('--standard', choices=STANDARDS, default='wcag22',
272
+ help='en301549 adds EN 301 549 V4.1.1 clause refs + families')
273
+ ap.add_argument('--target', choices=TARGETS, default='web',
274
+ help='ICT target: web (9.x), documents (10.x), software (11.x)')
275
+ ap.add_argument('--answers', help='JSON file: human confirmations keyed by code '
276
+ '{"1.2.4": {"status": "excluded", "reason": "…"}}')
277
+ ap.add_argument('--lang', default='en', choices=('es', 'en'))
278
+ ap.add_argument('-o', '--out', default='scope.json')
279
+ ap.add_argument('--targets', default=None,
280
+ help='comma-separated ICT targets for combined scope (e.g. web,documents)')
281
+ # (--solicitation se retiró: el generador de anexos vive en a11y-toolkit-pro)
282
+ a = ap.parse_args(argv)
283
+ reports = [json.load(open(r, encoding='utf-8')) for r in a.reports]
284
+ answers = json.load(open(a.answers, encoding='utf-8')) if a.answers else None
285
+ tgts = [t.strip() for t in a.targets.split(',')] if a.targets else None
286
+ scope = build_scope(reports, standard=a.standard, target=a.target,
287
+ answers=answers, lang=a.lang, targets=tgts)
288
+ with open(a.out, 'w', encoding='utf-8') as f:
289
+ json.dump(scope, f, ensure_ascii=False, indent=1)
290
+ print(json.dumps({'scope': a.out, 'sha256': scope['sha256'],
291
+ 'counters': scope['counters']}, ensure_ascii=False))
292
+ return 0
293
+
294
+
295
+ if __name__ == '__main__':
296
+ sys.exit(main(sys.argv[1:]))
@@ -78,13 +78,15 @@ def _add(findings, lang, sev, code, key, **fmt):
78
78
  })
79
79
 
80
80
 
81
- def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None):
81
+ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, browser='auto'):
82
82
  from playwright.sync_api import sync_playwright
83
+ from .a11ydom import _get_browser
83
84
  with sync_playwright() as p:
84
- nav = p.chromium.launch()
85
+ nav = _get_browser(p, preferred=browser)
85
86
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
86
- page = ctx.new_page(viewport={'width': 1280, 'height': 800}) if auth_state \
87
- else nav.new_page(viewport={'width': 1280, 'height': 800})
87
+ # BrowserContext.new_page() NO acepta viewport: va en el new_context
88
+ page = (ctx.new_page() if auth_state
89
+ else nav.new_page(viewport={'width': 1280, 'height': 800}))
88
90
  try:
89
91
  page.goto(url, wait_until='load', timeout=timeout * 1000)
90
92
  page.wait_for_timeout(500)
@@ -205,7 +207,7 @@ def main(argv):
205
207
  print(json.dumps({'error': 'Playwright not installed'}))
206
208
  return 1
207
209
  print(json.dumps(res, ensure_ascii=False, indent=1))
208
- return 0
210
+ return 1 if 'error' in res else 0
209
211
 
210
212
 
211
213
  if __name__ == '__main__':
@@ -13,6 +13,11 @@ Usage:
13
13
  declaracion.py --entity "Name" --url "https://…" --status partial \
14
14
  --inaccessible "…" --feedback "a@b.gal" [--framework rd1112|eaa] \
15
15
  [--lang es|en] [--output decl.html]
16
+
17
+ FROZEN LAYER (2026-11-04, founder decision "freeze the docs"): this
18
+ module stays public as an HONEST DRAFT generator (the machine fills
19
+ Remarks/texts, never the claim). Maintenance fixes only; new
20
+ capabilities live in the SaaS (a11y.es / Lince).
16
21
  """
17
22
 
18
23
  import argparse
@@ -50,9 +55,11 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
50
55
  return {'error': t['error_inconsistent']}
51
56
 
52
57
  e = lambda s: html.escape(str(s), quote=True) # noqa: E731
58
+ today = TODAY() # una sola lectura del reloj: una ejecución que cruce la
59
+ # medianoche no puede fechar cuerpo y resumen con días distintos
53
60
  status_title, status_text = STATES.get(lang, STATES['es'])[status]
54
- evaluation_date = evaluation_date or TODAY()
55
- review_date = review_date or TODAY()
61
+ evaluation_date = evaluation_date or today
62
+ review_date = review_date or today
56
63
  method = method or t['method_default']
57
64
  feedback = feedback or t['feedback_default']
58
65
 
@@ -75,6 +82,23 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
75
82
  <h2>{t['h_alt_access']}</h2>
76
83
  <p>{e(alternative_format)}</p>'''
77
84
 
85
+ # RD 1112/2018 art. 10.1(b): el procedimiento de reclamación se ENLAZA,
86
+ # no queda en texto inerte — un valor http(s) se renderiza como <a>
87
+ # (escapado); el texto que no es URL se queda plano (también escapado).
88
+ # El canal de feedback recibe el MISMO trato (es un canal de contacto)
89
+ feedback_html = ''
90
+ if feedback:
91
+ esc_f = e(feedback)
92
+ feedback_html = (f'<a href="{esc_f}">{esc_f}</a>'
93
+ if str(feedback).lower().startswith(('http://', 'https://'))
94
+ else esc_f)
95
+ complaints_html = ''
96
+ if complaints:
97
+ esc_c = e(complaints)
98
+ complaints_html = (f'<a href="{esc_c}">{esc_c}</a>'
99
+ if str(complaints).lower().startswith(('http://', 'https://'))
100
+ else esc_c)
101
+
78
102
  doc_title = t['title'][framework]
79
103
  doc = f'''<!doctype html>
80
104
  <html lang="{html.escape(str(lang), quote=True)}">
@@ -97,14 +121,14 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
97
121
  <h2>{t['h_preparation']}</h2>
98
122
  <ul>
99
123
  <li>{t['l_evaluation']}: <time datetime="{e(evaluation_date)}">{e(evaluation_date)}</time></li>
100
- <li>{t['l_declared']} <time datetime="{e(TODAY())}">{e(TODAY())}</time></li>
124
+ <li>{t['l_declared']} <time datetime="{e(today)}">{e(today)}</time></li>
101
125
  <li>{t['l_method']}: {e(method)}</li>
102
126
  <li>{t['l_review']}: <time datetime="{e(review_date)}">{e(review_date)}</time></li>
103
127
  </ul>
104
128
 
105
129
  <h2>{t['h_contact']}</h2>
106
- <p>{t['contact'].format(f=e(feedback))}</p>
107
- <p>{e(complaints) if complaints else t['complaints'][framework]}</p>
130
+ <p>{t['contact'].format(f=feedback_html)}</p>
131
+ <p>{complaints_html if complaints else t['complaints'][framework]}</p>
108
132
  {disalt}
109
133
  </main>
110
134
  </body>
@@ -116,7 +140,7 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
116
140
  'entity': entity, 'url': url, 'framework': framework, 'lang': lang,
117
141
  'status': status_title,
118
142
  'inaccessible_items': len(inaccessible_content),
119
- 'dates': {'evaluation': evaluation_date, 'declaration': TODAY(),
143
+ 'dates': {'evaluation': evaluation_date, 'declaration': today,
120
144
  'review': review_date},
121
145
  },
122
146
  }