@kinti/a11y-toolkit 5.22.1 → 5.22.2
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.
- package/a11y_toolkit/__init__.py +5 -0
- package/a11y_toolkit/a11y.py +115 -0
- package/a11y_toolkit/a11yact.py +167 -0
- package/a11y_toolkit/a11yaudit.py +1951 -0
- package/a11y_toolkit/a11ybadge.py +102 -0
- package/a11y_toolkit/a11ybudget.py +122 -0
- package/a11y_toolkit/a11ycrit.py +1017 -0
- package/a11y_toolkit/a11ydiff.py +192 -0
- package/a11y_toolkit/a11ydisprove.py +175 -0
- package/a11y_toolkit/a11ydocx.py +132 -0
- package/a11y_toolkit/a11ydom.py +1831 -0
- package/a11y_toolkit/a11yevidence.py +272 -0
- package/a11y_toolkit/a11yfix.py +330 -0
- package/a11y_toolkit/a11yi18n.py +100 -0
- package/a11y_toolkit/a11yinit.py +113 -0
- package/a11y_toolkit/a11yjourney.py +284 -0
- package/a11y_toolkit/a11yledger.py +210 -0
- package/a11y_toolkit/a11ymutants.py +406 -0
- package/a11y_toolkit/a11yopenacr.py +207 -0
- package/a11y_toolkit/a11ypdf.py +273 -0
- package/a11y_toolkit/a11yroute.py +378 -0
- package/a11y_toolkit/a11ysarif.py +139 -0
- package/a11y_toolkit/a11yscroll.py +212 -0
- package/a11y_toolkit/a11ystatement.py +158 -0
- package/a11y_toolkit/a11yvalidate.py +127 -0
- package/a11y_toolkit/a11yvpat.py +238 -0
- package/a11y_toolkit/a11yvtt.py +136 -0
- package/a11y_toolkit/a11ywcag3.py +262 -0
- package/a11y_toolkit/arialive.js +107 -0
- package/a11y_toolkit/arialive_js.py +113 -0
- package/a11y_toolkit/contrast.py +536 -0
- package/a11y_toolkit/locales/_template.json +468 -0
- package/a11y_toolkit/locales/en.json +525 -0
- package/a11y_toolkit/locales/es.json +525 -0
- package/a11y_toolkit/server.py +1529 -0
- package/package.json +2 -1
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Accessibility regression diff between builds — catch regressions before production.
|
|
3
|
+
|
|
4
|
+
Two commands:
|
|
5
|
+
|
|
6
|
+
snapshot Capture a URL: interactive elements (tag, role, accessible name,
|
|
7
|
+
href) in DOM order + the REAL tab order + the computed
|
|
8
|
+
accessibility tree. Requires Playwright.
|
|
9
|
+
|
|
10
|
+
diff Compare two snapshots: added/removed/renamed interactives,
|
|
11
|
+
focus-order and accessibility-tree changes.
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
a11ydiff.py snapshot https://jquin.net --out before.json
|
|
15
|
+
# …deploy…
|
|
16
|
+
a11ydiff.py snapshot https://jquin.net --out after.json
|
|
17
|
+
a11ydiff.py diff before.json after.json # exit 0 ok / 2 regressions
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import json
|
|
22
|
+
import sys
|
|
23
|
+
from datetime import datetime, timezone
|
|
24
|
+
|
|
25
|
+
COLLECTOR = r'''() => {
|
|
26
|
+
const sel = 'a[href], button, input, select, textarea, summary, [tabindex], ' +
|
|
27
|
+
'[contenteditable], video[controls], audio[controls]';
|
|
28
|
+
const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
|
|
29
|
+
return [...document.querySelectorAll(sel)].filter(visible).map((el, i) => {
|
|
30
|
+
let name = el.getAttribute('aria-label') || '';
|
|
31
|
+
if (!name && el.labels && el.labels[0]) name = el.labels[0].innerText;
|
|
32
|
+
if (!name) name = el.getAttribute('title') || '';
|
|
33
|
+
if (!name && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type))
|
|
34
|
+
name = el.value || '';
|
|
35
|
+
if (!name) name = (el.innerText || '').replace(/\s+/g, ' ').trim();
|
|
36
|
+
if (!name) name = el.getAttribute('alt') || '';
|
|
37
|
+
const link = el.closest('a[href]');
|
|
38
|
+
return {
|
|
39
|
+
key: el.id ? '#' + el.id
|
|
40
|
+
: el.tagName.toLowerCase() + ':' + name.slice(0, 60).toLowerCase() +
|
|
41
|
+
(link ? ':' + link.getAttribute('href') : ''),
|
|
42
|
+
tag: el.tagName.toLowerCase(),
|
|
43
|
+
id: el.id || null,
|
|
44
|
+
role: el.getAttribute('role') || el.tagName.toLowerCase(),
|
|
45
|
+
name: name.trim().slice(0, 90),
|
|
46
|
+
href: link ? link.getAttribute('href') : null,
|
|
47
|
+
dom: i,
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
}'''
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def snapshot(url, output=None, auth_state=None):
|
|
54
|
+
"""Captura una URL. Con salida=None devuelve los datos sin escribir fichero."""
|
|
55
|
+
from playwright.sync_api import sync_playwright
|
|
56
|
+
with sync_playwright() as p:
|
|
57
|
+
nav = p.chromium.launch()
|
|
58
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
59
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
60
|
+
page.goto(url, wait_until='networkidle', timeout=45000)
|
|
61
|
+
elements = page.evaluate(COLLECTOR)
|
|
62
|
+
|
|
63
|
+
# Árbol de accesibilidad REAL (roles/nombres computados, lo que anuncia
|
|
64
|
+
# un lector de pantalla). Playwright ≥1.49; si no está, se omite.
|
|
65
|
+
tree = None
|
|
66
|
+
try:
|
|
67
|
+
tree = page.locator('body').aria_snapshot()
|
|
68
|
+
if len(tree) > 60_000:
|
|
69
|
+
tree = tree[:60_000] + '\n… (truncado)'
|
|
70
|
+
except Exception: # noqa: BLE001
|
|
71
|
+
tree = None
|
|
72
|
+
|
|
73
|
+
order = []
|
|
74
|
+
page.keyboard.press('Tab')
|
|
75
|
+
seen = set()
|
|
76
|
+
for _ in range(len(elements) * 2 + 10):
|
|
77
|
+
info = page.evaluate(r'''() => {
|
|
78
|
+
const el = document.activeElement;
|
|
79
|
+
if (!el || el === document.body) return null;
|
|
80
|
+
const link = el.closest('a[href]');
|
|
81
|
+
let name = el.getAttribute('aria-label') || (el.innerText || '')
|
|
82
|
+
.replace(/\s+/g,' ').trim() || el.getAttribute('title') ||
|
|
83
|
+
(el.tagName==='INPUT' && el.value) || '';
|
|
84
|
+
return el.id ? '#'+el.id : el.tagName.toLowerCase()+':'+name.slice(0,60).toLowerCase()+
|
|
85
|
+
(link ? ':'+link.getAttribute('href') : '');
|
|
86
|
+
}''')
|
|
87
|
+
if info is None:
|
|
88
|
+
break
|
|
89
|
+
entry_key = info + '@' + str(len(seen))
|
|
90
|
+
if info in seen:
|
|
91
|
+
break
|
|
92
|
+
seen.add(info)
|
|
93
|
+
order.append(info)
|
|
94
|
+
page.keyboard.press('Tab')
|
|
95
|
+
nav.close()
|
|
96
|
+
|
|
97
|
+
data = {'url': url, 'ts': datetime.now(timezone.utc).isoformat(),
|
|
98
|
+
'elements': elements, 'focus_order': order}
|
|
99
|
+
if tree is not None:
|
|
100
|
+
data['arbol_accesible'] = tree
|
|
101
|
+
if output:
|
|
102
|
+
with open(output, 'w', encoding='utf-8') as f:
|
|
103
|
+
json.dump(data, f, ensure_ascii=False, indent=1)
|
|
104
|
+
return data
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def diff(a, b):
|
|
108
|
+
ea = {x['key']: x for x in a['elements']}
|
|
109
|
+
eb = {x['key']: x for x in b['elements']}
|
|
110
|
+
aniadidos = sorted(set(eb) - set(ea))
|
|
111
|
+
removed = sorted(set(ea) - set(eb))
|
|
112
|
+
renamed = []
|
|
113
|
+
for k in set(ea) & set(eb):
|
|
114
|
+
if ea[k]['name'] != eb[k]['name']:
|
|
115
|
+
renamed.append({'key': k, 'before': ea[k]['name'], 'after': eb[k]['name']})
|
|
116
|
+
|
|
117
|
+
oa, ob = a['focus_order'], b['focus_order']
|
|
118
|
+
common_a = [x for x in oa if x in set(ob)]
|
|
119
|
+
common_b = [x for x in ob if x in set(oa)]
|
|
120
|
+
focus_removed = [x for x in oa if x not in set(ob)] # perdió el Tab: regresión real
|
|
121
|
+
focus_added = [x for x in ob if x not in set(oa)] # nuevo enfocable: cambio, no pérdida
|
|
122
|
+
focus_changed = common_a != common_b
|
|
123
|
+
first_divergence = next((i for i, (x, y) in enumerate(zip(common_a, common_b)) if x != y), None)
|
|
124
|
+
|
|
125
|
+
# Árbol de accesibilidad: si ambos snapshots lo traen, detecta cambios en
|
|
126
|
+
# roles/nombres computados que la lista de interactivos no ve.
|
|
127
|
+
tree_changed = None
|
|
128
|
+
tree_diff = None
|
|
129
|
+
if 'arbol_accesible' in a and 'arbol_accesible' in b:
|
|
130
|
+
la, lb = a['arbol_accesible'].splitlines(), b['arbol_accesible'].splitlines()
|
|
131
|
+
tree_changed = la != lb
|
|
132
|
+
if tree_changed:
|
|
133
|
+
tree_diff = [f'- {la[i]}' for i in range(min(len(la), len(lb)))
|
|
134
|
+
if la[i] != lb[i]][:5]
|
|
135
|
+
tree_diff += [f'+ {lb[i]}' for i in range(min(len(la), len(lb)))
|
|
136
|
+
if i < len(lb) and la[i] != lb[i]][:5]
|
|
137
|
+
|
|
138
|
+
# perder un elemento del orden de foco ES la regresión que este diff
|
|
139
|
+
# existe para cazar (p. ej. tabindex="-1" añadido al botón de pago):
|
|
140
|
+
# el elemento sigue existiendo, pero ya no es alcanzable por teclado.
|
|
141
|
+
ok = not (aniadidos or removed or renamed or focus_changed
|
|
142
|
+
or focus_removed or tree_changed)
|
|
143
|
+
return {
|
|
144
|
+
'ok': ok,
|
|
145
|
+
'summary': {
|
|
146
|
+
'elements': {'before': len(ea), 'after': len(eb)},
|
|
147
|
+
'added': len(aniadidos), 'removed': len(removed),
|
|
148
|
+
'renamed': len(renamed),
|
|
149
|
+
'focus_order_changed': focus_changed or bool(focus_removed),
|
|
150
|
+
},
|
|
151
|
+
'added': aniadidos, 'removed': removed, 'renamed': renamed,
|
|
152
|
+
'focus': {'before': oa, 'after': ob, 'first_divergence': first_divergence,
|
|
153
|
+
'removed': focus_removed, 'added': focus_added,
|
|
154
|
+
'reordered': bool(focus_changed and not focus_removed and not focus_added)},
|
|
155
|
+
'tree': {'changed': tree_changed, 'first_differences': tree_diff},
|
|
156
|
+
'note': ('Elementos sin id se casan por tag+nombre+href: renombrar produce '
|
|
157
|
+
'eliminado+añadido, no un diff fino. Usa ids estables para trazabilidad.'),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def main(argv):
|
|
162
|
+
p = argparse.ArgumentParser(description=__doc__)
|
|
163
|
+
sub = p.add_subparsers(dest='cmd', required=True)
|
|
164
|
+
s1 = sub.add_parser('snapshot')
|
|
165
|
+
s1.add_argument('url')
|
|
166
|
+
s1.add_argument('--out', default='snapshot.json')
|
|
167
|
+
s2 = sub.add_parser('diff')
|
|
168
|
+
s2.add_argument('a')
|
|
169
|
+
s2.add_argument('b')
|
|
170
|
+
a = p.parse_args(argv)
|
|
171
|
+
|
|
172
|
+
if a.cmd == 'snapshot':
|
|
173
|
+
try:
|
|
174
|
+
d = snapshot(a.url, a.out)
|
|
175
|
+
except ImportError:
|
|
176
|
+
print(json.dumps({'error': 'Playwright not installed: pip install playwright && playwright install chromium'}))
|
|
177
|
+
return 1
|
|
178
|
+
print(json.dumps({'url': d['url'], 'elements': len(d['elements']),
|
|
179
|
+
'focus_steps': len(d['focus_order']), 'out': a.out},
|
|
180
|
+
ensure_ascii=False, indent=1))
|
|
181
|
+
return 0
|
|
182
|
+
with open(a.a, encoding='utf-8') as f:
|
|
183
|
+
ja = json.load(f)
|
|
184
|
+
with open(a.b, encoding='utf-8') as f:
|
|
185
|
+
jb = json.load(f)
|
|
186
|
+
print(json.dumps(diff(ja, jb), ensure_ascii=False, indent=1))
|
|
187
|
+
verdict = diff(ja, jb)
|
|
188
|
+
return 0 if verdict['ok'] else 2
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == '__main__':
|
|
192
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Disprover pattern — re-verify findings against the live page and reject those
|
|
3
|
+
that don't reproduce.
|
|
4
|
+
|
|
5
|
+
The Cloudflare security-audit-skill lesson: every finding deserves a fresh
|
|
6
|
+
verifier that tries to DISPROVE it, not confirm it. This module does that for
|
|
7
|
+
accessibility findings:
|
|
8
|
+
|
|
9
|
+
1. Take an audit report
|
|
10
|
+
2. For each finding, re-check the signal against the live page
|
|
11
|
+
3. Findings that reproduce → estado: confirmed
|
|
12
|
+
4. Findings that don't → estado: rejected + reject_reason
|
|
13
|
+
|
|
14
|
+
This catches:
|
|
15
|
+
- False positives (the element changed, was fixed, or never existed)
|
|
16
|
+
- Race conditions (page was different when first audited)
|
|
17
|
+
- Rendering differences (element is hidden, removed, or in a different context)
|
|
18
|
+
|
|
19
|
+
CLI:
|
|
20
|
+
a11ydisprove.py --url https://example.com --file report.json
|
|
21
|
+
a11ydisprove.py --url https://example.com # audit + disprove in one call
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
|
|
27
|
+
from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
|
|
28
|
+
import sys
|
|
29
|
+
|
|
30
|
+
from .a11yaudit import audit_url, audit_html
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _recheck_static(url, findings, timeout=30, lang='en'):
|
|
34
|
+
"""Re-run the static audit and check which findings still fire."""
|
|
35
|
+
fresh_report = audit_url(url, timeout=timeout, lang=lang)
|
|
36
|
+
if 'error' in fresh_report:
|
|
37
|
+
return findings, fresh_report['error']
|
|
38
|
+
fresh_signals = {h['signal'] for h in fresh_report.get('findings', [])}
|
|
39
|
+
verified = []
|
|
40
|
+
for h in findings:
|
|
41
|
+
if normalize_signal(h.get('signal', '')) in fresh_signals:
|
|
42
|
+
h['status'] = 'confirmed'
|
|
43
|
+
else:
|
|
44
|
+
h['status'] = 'rejected'
|
|
45
|
+
h['reject_reason'] = (
|
|
46
|
+
f"signal '{h.get('signal', '?')}' no longer fires on re-audit — "
|
|
47
|
+
"the page may have changed, or the finding was a false positive")
|
|
48
|
+
verified.append(h)
|
|
49
|
+
return verified, None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _recheck_rendered(url, findings, timeout=45, lang='en'):
|
|
53
|
+
"""Re-run the rendered audit and check which findings still fire."""
|
|
54
|
+
try:
|
|
55
|
+
from .a11ydom import audit_dom_url
|
|
56
|
+
except ImportError:
|
|
57
|
+
return findings, "Playwright not installed"
|
|
58
|
+
fresh_report = audit_dom_url(url, timeout=timeout, lang=lang)
|
|
59
|
+
if 'error' in fresh_report:
|
|
60
|
+
return findings, fresh_report['error']
|
|
61
|
+
fresh_signals = {h['signal'] for h in fresh_report.get('findings', [])}
|
|
62
|
+
verified = []
|
|
63
|
+
for h in findings:
|
|
64
|
+
if normalize_signal(h.get('signal', '')) in fresh_signals:
|
|
65
|
+
h['status'] = 'confirmed'
|
|
66
|
+
else:
|
|
67
|
+
h['status'] = 'rejected'
|
|
68
|
+
h['reject_reason'] = (
|
|
69
|
+
f"signal '{h.get('signal', '?')}' no longer fires in the rendered "
|
|
70
|
+
"re-audit — the element may have changed, been fixed, or the "
|
|
71
|
+
"first finding was a false positive")
|
|
72
|
+
verified.append(h)
|
|
73
|
+
return verified, None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def disprove(url, report=None, timeout=30, lang='en'):
|
|
77
|
+
"""Audit a URL and disprove findings, or verify an existing report.
|
|
78
|
+
|
|
79
|
+
Returns a report with each finding marked confirmed/rejected."""
|
|
80
|
+
if report is None:
|
|
81
|
+
report = audit_url(url, timeout=timeout, lang=lang)
|
|
82
|
+
if 'error' in report:
|
|
83
|
+
return report
|
|
84
|
+
|
|
85
|
+
mode_name = report.get('mode', 'static')
|
|
86
|
+
findings = report.get('findings', [])
|
|
87
|
+
|
|
88
|
+
if mode_name == 'site' and not findings:
|
|
89
|
+
# site reports nest findings INSIDE each page: re-checking them against
|
|
90
|
+
# ONE url marked everything 'rejected' and scored 100 on unreviewed
|
|
91
|
+
# evidence. Honest path: not-rechecked per page, with the pointer to
|
|
92
|
+
# re-verify each page properly.
|
|
93
|
+
every_finding = []
|
|
94
|
+
for page in (report.get('pages') or report.get('reports') or []):
|
|
95
|
+
for h in page.get('findings', []):
|
|
96
|
+
every_finding.append(dict(h, disprover_status='not-rechecked',
|
|
97
|
+
page=page.get('url', '')))
|
|
98
|
+
res = dict(report)
|
|
99
|
+
res['findings'] = every_finding
|
|
100
|
+
res['disprover'] = {'executed': False,
|
|
101
|
+
'reason': ('site mode: each finding belongs to a page; '
|
|
102
|
+
're-verify with a11ydisprove --url <page> '
|
|
103
|
+
'--file <that page report>')}
|
|
104
|
+
return res
|
|
105
|
+
|
|
106
|
+
if mode_name in ('static', 'site'):
|
|
107
|
+
verified, err = _recheck_static(url, findings, timeout=timeout, lang=lang)
|
|
108
|
+
elif mode_name == 'rendered':
|
|
109
|
+
verified, err = _recheck_rendered(url, findings, timeout=timeout, lang=lang)
|
|
110
|
+
else:
|
|
111
|
+
# no re-verifier for this mode: report not-rechecked, never a proxy
|
|
112
|
+
# audit (a keyboard finding must not vanish just because the wrong
|
|
113
|
+
# method ran). `rejected` is reserved for an equivalent check that
|
|
114
|
+
# actually disproves the original finding.
|
|
115
|
+
res = dict(report)
|
|
116
|
+
res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
|
|
117
|
+
res['disprover'] = {'executed': False,
|
|
118
|
+
'reason': f"no re-verifier for mode {mode_name!r}"}
|
|
119
|
+
return res
|
|
120
|
+
|
|
121
|
+
if err:
|
|
122
|
+
return {'error': f'disprove re-audit failed: {err}'}
|
|
123
|
+
|
|
124
|
+
result = dict(report)
|
|
125
|
+
result['findings'] = verified
|
|
126
|
+
result['disprover'] = {
|
|
127
|
+
'executed': True,
|
|
128
|
+
'confirmed': sum(1 for h in verified if h.get('status') == 'confirmed'),
|
|
129
|
+
'rejected': sum(1 for h in verified if h.get('status') == 'rejected'),
|
|
130
|
+
'note': ('Each finding was re-checked against the live page. '
|
|
131
|
+
'Rejected findings include the reason they did not reproduce. '
|
|
132
|
+
'Confirmed findings survived a fresh verification pass.'),
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
# recalcular score sobre los confirmed
|
|
136
|
+
from .a11yaudit import compute_score
|
|
137
|
+
solo_confirmed = [h for h in verified if h.get('status') == 'confirmed']
|
|
138
|
+
result['score_original'] = report.get('score')
|
|
139
|
+
result['score'] = compute_score(solo_confirmed)
|
|
140
|
+
result['summary'] = {
|
|
141
|
+
'high': sum(1 for h in solo_confirmed if h['severity'] == 'high'),
|
|
142
|
+
'medium': sum(1 for h in solo_confirmed if h['severity'] == 'medium'),
|
|
143
|
+
'low': sum(1 for h in solo_confirmed if h['severity'] == 'low'),
|
|
144
|
+
}
|
|
145
|
+
return result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def main(argv):
|
|
149
|
+
ap = argparse.ArgumentParser(description='Disprover: re-verify findings against the live page')
|
|
150
|
+
ap.add_argument('--url', required=True, help='URL to audit and disprove')
|
|
151
|
+
ap.add_argument('--file', help='existing report JSON (optional; if absent, audits first)')
|
|
152
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
153
|
+
ap.add_argument('--timeout', type=int, default=30)
|
|
154
|
+
ap.add_argument('-o', '--out', help='save result JSON here')
|
|
155
|
+
a = ap.parse_args(argv)
|
|
156
|
+
report = None
|
|
157
|
+
if a.file:
|
|
158
|
+
with open(a.file, encoding='utf-8') as f:
|
|
159
|
+
report = json.load(f)
|
|
160
|
+
res = disprove(a.url, report=report, timeout=a.timeout, lang=a.lang)
|
|
161
|
+
if 'error' in res:
|
|
162
|
+
print(json.dumps(res))
|
|
163
|
+
return 1
|
|
164
|
+
output = json.dumps(res, ensure_ascii=False, indent=1)
|
|
165
|
+
if a.out:
|
|
166
|
+
with open(a.out, 'w', encoding='utf-8') as f:
|
|
167
|
+
f.write(output)
|
|
168
|
+
print(json.dumps({'file': a.out, **res['disprover']}))
|
|
169
|
+
else:
|
|
170
|
+
print(output)
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
if __name__ == '__main__':
|
|
175
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""DOCX accessibility screening — the other half of enterprise paperwork.
|
|
3
|
+
|
|
4
|
+
Un .docx es un ZIP: word/document.xml (el cuerpo), word/styles.xml, y las
|
|
5
|
+
imágenes en word/media/. Los fallos raíz de accesibilidad de documentos son
|
|
6
|
+
mecánicamente detectables sin dependencias: imágenes sin texto alternativo
|
|
7
|
+
(el bloque <wp:docPr> sin descr o con descr vacío), idioma del documento sin
|
|
8
|
+
declarar, y cabeceras falsas (párrafos que solo ponen negrita grande en vez
|
|
9
|
+
de estilos de encabezado — el "falso encabezado" que deshabilita el panel de
|
|
10
|
+
navegación y el índice automático).
|
|
11
|
+
|
|
12
|
+
Honestidad: el cribado de PDF y de DOCX comparten filosofía — encuentra lo
|
|
13
|
+
que hace inútil la revisión completa; no sustituye la revisión humana.
|
|
14
|
+
|
|
15
|
+
CLI:
|
|
16
|
+
a11ydocx.py documento.docx [--lang en]
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import zipfile
|
|
24
|
+
from . import a11yi18n
|
|
25
|
+
|
|
26
|
+
T = a11yi18n.pair('docx') # locales/<lang>.json — community-editable
|
|
27
|
+
|
|
28
|
+
_CRIT = {
|
|
29
|
+
'docx_no_alt': ('1.1.1', 'high'), 'docx_fake_headings': ('1.3.1', 'medium'),
|
|
30
|
+
'docx_no_lang': ('3.1.1', 'medium'), 'docx_table_no_header': ('1.3.1', 'low'),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _t(lang, key):
|
|
35
|
+
return T.get(lang, T['en'])[key]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def docx_screen(path, lang='en'):
|
|
39
|
+
"""Cribado de accesibilidad de un .docx (solo stdlib: zipfile + regex XML)."""
|
|
40
|
+
try:
|
|
41
|
+
z = zipfile.ZipFile(path)
|
|
42
|
+
except (zipfile.BadZipFile, FileNotFoundError, IsADirectoryError, PermissionError) as e:
|
|
43
|
+
return {'error': f'no es un .docx legible: {e}'}
|
|
44
|
+
if 'word/document.xml' not in z.namelist():
|
|
45
|
+
return {'error': 'ZIP without word/document.xml (is this really a .docx?)'}
|
|
46
|
+
|
|
47
|
+
body = z.read('word/document.xml').decode('utf-8', errors='replace')
|
|
48
|
+
|
|
49
|
+
findings = []
|
|
50
|
+
|
|
51
|
+
def add(key):
|
|
52
|
+
crit, sev = _CRIT[key]
|
|
53
|
+
findings.append({'severity': sev, 'criterion': f'{crit} (DOCX)',
|
|
54
|
+
'signal': key, 'issue': _t(lang, key),
|
|
55
|
+
'remediation': _t(lang, key + '_rem')})
|
|
56
|
+
|
|
57
|
+
# imágenes: cada <wp:docPr> es una imagen/gráfico; descr = alt text
|
|
58
|
+
docprs = re.findall(r'<wp:docPr\b[^>]*>', body)
|
|
59
|
+
no_alt = [d for d in docprs
|
|
60
|
+
if 'descr=' not in d or re.search(r'descr="\s*"', d)]
|
|
61
|
+
if docprs and no_alt:
|
|
62
|
+
n = len(no_alt)
|
|
63
|
+
findings.append({'severity': 'high', 'criterion': '1.1.1 (DOCX)',
|
|
64
|
+
'signal': 'docx_no_alt',
|
|
65
|
+
'issue': _t(lang, 'docx_no_alt').format(n=n),
|
|
66
|
+
'remediation': _t(lang, 'docx_no_alt_rem')})
|
|
67
|
+
|
|
68
|
+
# idioma: w:lang en styles.xml (default del documento)
|
|
69
|
+
language = None
|
|
70
|
+
try:
|
|
71
|
+
styles = z.read('word/styles.xml').decode('utf-8', errors='replace')
|
|
72
|
+
m = re.search(r'<w:lang[^>]*w:val="([^"]+)"', styles)
|
|
73
|
+
language = m.group(1) if m else None
|
|
74
|
+
except KeyError:
|
|
75
|
+
pass
|
|
76
|
+
if not language:
|
|
77
|
+
add('docx_no_lang')
|
|
78
|
+
|
|
79
|
+
# tablas sin fila de encabezado (tblHeader)
|
|
80
|
+
n_tables = len(re.findall(r'<w:tbl>', body))
|
|
81
|
+
n_tblheader = len(re.findall(r'<w:tblHeader\s*/?>', body))
|
|
82
|
+
if n_tables and not n_tblheader:
|
|
83
|
+
add('docx_table_no_header')
|
|
84
|
+
|
|
85
|
+
# falsos encabezados: párrafo todo-bold + tamaño grande sin estilo Heading
|
|
86
|
+
fake = 0
|
|
87
|
+
for para in re.findall(r'<w:p\b.*?</w:p>', body, re.S):
|
|
88
|
+
if 'w:val="Heading' in para:
|
|
89
|
+
continue
|
|
90
|
+
has_bold = '<w:b/>' in para or '<w:b ' in para
|
|
91
|
+
m_sz = re.search(r'<w:sz w:val="(\d+)"', para)
|
|
92
|
+
large = bool(m_sz) and int(m_sz.group(1)) >= 28
|
|
93
|
+
text = ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', para)).strip()
|
|
94
|
+
if has_bold and large and 2 < len(text) < 120:
|
|
95
|
+
fake += 1
|
|
96
|
+
if fake:
|
|
97
|
+
findings.append({'severity': 'medium', 'criterion': '1.3.1 (DOCX)',
|
|
98
|
+
'signal': 'docx_fake_headings',
|
|
99
|
+
'issue': _t(lang, 'docx_fake_headings').format(n=fake),
|
|
100
|
+
'remediation': _t(lang, 'docx_fake_headings_rem')})
|
|
101
|
+
|
|
102
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
103
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
104
|
+
|
|
105
|
+
def score(hs):
|
|
106
|
+
return max(0, 100 - 25 * sum(1 for h in hs if h['severity'] == 'high')
|
|
107
|
+
- 10 * sum(1 for h in hs if h['severity'] == 'medium')
|
|
108
|
+
- 5 * sum(1 for h in hs if h['severity'] == 'low'))
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
'mode': 'docx', 'file': str(path).rsplit('/', 1)[-1],
|
|
112
|
+
'language': language, 'images': len(docprs),
|
|
113
|
+
'tables': n_tables, 'tables_with_header': n_tblheader,
|
|
114
|
+
'score': score(findings),
|
|
115
|
+
'findings': findings,
|
|
116
|
+
'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
|
|
117
|
+
for s2 in ('high', 'medium', 'low')},
|
|
118
|
+
'limits': _t(lang, 'limits'),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def main(argv):
|
|
123
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
124
|
+
ap.add_argument('docx', help='local .docx file')
|
|
125
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
126
|
+
a = ap.parse_args(argv)
|
|
127
|
+
print(json.dumps(docx_screen(a.docx, lang=a.lang), ensure_ascii=False, indent=1))
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == '__main__':
|
|
132
|
+
sys.exit(main(sys.argv[1:]))
|