@kinti/a11y-toolkit 5.35.1 → 5.35.3
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/a11yact.py +20 -9
- package/a11y_toolkit/a11yaudit.py +13 -10
- package/a11y_toolkit/a11ycorpus.py +72 -40
- package/a11y_toolkit/a11ydocx.py +153 -174
- package/a11y_toolkit/a11yevidence.py +15 -6
- package/a11y_toolkit/a11ypdf.py +19 -11
- package/a11y_toolkit/a11ysarif.py +19 -13
- package/a11y_toolkit/a11yvtt.py +42 -25
- package/a11y_toolkit/server.py +6 -4
- package/package.json +1 -1
package/a11y_toolkit/a11yact.py
CHANGED
|
@@ -18,7 +18,7 @@ CLI:
|
|
|
18
18
|
import argparse
|
|
19
19
|
import json
|
|
20
20
|
|
|
21
|
-
from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
|
|
21
|
+
from .a11yaudit import completed_report_pages, normalize_signal # noqa: E402 (compat 5.10)
|
|
22
22
|
import sys
|
|
23
23
|
from datetime import datetime, timezone
|
|
24
24
|
|
|
@@ -96,6 +96,9 @@ def act_ids(signal):
|
|
|
96
96
|
|
|
97
97
|
def earl(report, url=None):
|
|
98
98
|
"""Informe de auditoría → EARL 1.0 JSON-LD (solo hallazgos con mapeo ACT)."""
|
|
99
|
+
_, error = completed_report_pages(report)
|
|
100
|
+
if error:
|
|
101
|
+
return error
|
|
99
102
|
assertions = []
|
|
100
103
|
# site crawls anidan en reports[]: cada hallazgo pertenece a SU página —
|
|
101
104
|
# aplanar sin más atribuía el fallo de /gallery a la PORTADA (revisión
|
|
@@ -162,15 +165,23 @@ def main(argv):
|
|
|
162
165
|
print(json.dumps({'act_map': ACT_MAP, 'act_notes': ACT_NOTES},
|
|
163
166
|
ensure_ascii=False, indent=1))
|
|
164
167
|
return 0
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
168
|
+
try:
|
|
169
|
+
if a.from_audit:
|
|
170
|
+
with open(a.from_audit, encoding='utf-8') as f:
|
|
171
|
+
report = json.load(f)
|
|
172
|
+
elif a.url:
|
|
173
|
+
from .a11yaudit import audit_url
|
|
174
|
+
report = audit_url(a.url)
|
|
175
|
+
else:
|
|
176
|
+
ap.print_help()
|
|
177
|
+
return 2
|
|
178
|
+
except (OSError, ValueError) as error:
|
|
179
|
+
print(json.dumps({'error': str(error)}, ensure_ascii=False))
|
|
180
|
+
return 1
|
|
173
181
|
res = earl(report, url=a.url)
|
|
182
|
+
if 'error' in res:
|
|
183
|
+
print(json.dumps(res, ensure_ascii=False))
|
|
184
|
+
return 1
|
|
174
185
|
if a.out:
|
|
175
186
|
with open(a.out, 'w', encoding='utf-8') as f:
|
|
176
187
|
json.dump(res, f, ensure_ascii=False, indent=1)
|
|
@@ -2001,8 +2001,10 @@ def audit_conditions_match(mode, previous, current):
|
|
|
2001
2001
|
|
|
2002
2002
|
def completed_report_pages(report):
|
|
2003
2003
|
"""Return measured pages or the reason they cannot support a comparison."""
|
|
2004
|
-
if not isinstance(report, dict)
|
|
2004
|
+
if not isinstance(report, dict):
|
|
2005
2005
|
return [], {'error': 'the audit failed or was not a report'}
|
|
2006
|
+
if report.get('error'):
|
|
2007
|
+
return [], {'error': report['error']}
|
|
2006
2008
|
pages = report.get('reports', [report])
|
|
2007
2009
|
if not isinstance(pages, list) or not pages:
|
|
2008
2010
|
return [], {'error': 'the audit contains no page reports'}
|
|
@@ -2014,12 +2016,12 @@ def completed_report_pages(report):
|
|
|
2014
2016
|
if not isinstance(page, dict):
|
|
2015
2017
|
return [], {'error': 'the audit contains an invalid page report'}
|
|
2016
2018
|
status = page.get('http_status')
|
|
2017
|
-
if (page.get('error') or not isinstance(page.get('findings'), list)
|
|
2019
|
+
if (page.get('error') or page.get('truncated') or not isinstance(page.get('findings'), list)
|
|
2018
2020
|
or status is not None and (type(status) is not int or not 200 <= status < 400)):
|
|
2019
2021
|
failures.append(page)
|
|
2020
|
-
if failures or report.get('budget_exhausted'):
|
|
2022
|
+
if failures or report.get('budget_exhausted') or report.get('truncated'):
|
|
2021
2023
|
return [], {'error': 'the audit did not complete; compare after all pages are measured',
|
|
2022
|
-
'pages_failed': [page.get('url') for page in failures]}
|
|
2024
|
+
'pages_failed': [page.get('url') or page.get('file') for page in failures]}
|
|
2023
2025
|
return pages, None
|
|
2024
2026
|
|
|
2025
2027
|
|
|
@@ -2908,7 +2910,7 @@ class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
|
|
|
2908
2910
|
_OPENER = urllib.request.build_opener(_CheckedRedirect)
|
|
2909
2911
|
|
|
2910
2912
|
|
|
2911
|
-
def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
|
|
2913
|
+
def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None, *, require_complete=False):
|
|
2912
2914
|
scheme = url.split(':', 1)[0].lower() if ':' in url else ''
|
|
2913
2915
|
if scheme not in ('http', 'https'):
|
|
2914
2916
|
# política única para TODAS las rutas de descarga (audit_url la
|
|
@@ -2926,6 +2928,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
|
|
|
2926
2928
|
_meta['final_url'] = r.geturl()
|
|
2927
2929
|
_meta['status'] = getattr(r, 'status', None)
|
|
2928
2930
|
ceiling = truncate_at or MAX_HTML
|
|
2931
|
+
complete = truncate_at is None or require_complete
|
|
2929
2932
|
# TOTAL-CLOCK reading: the socket timeout is per-operation and a server
|
|
2930
2933
|
# dribbling one byte per operation reset it forever. Read in chunks
|
|
2931
2934
|
# with a global deadline. A full audit requires a complete response.
|
|
@@ -2938,16 +2941,16 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
|
|
|
2938
2941
|
data = b''
|
|
2939
2942
|
while len(data) < ceiling + 1:
|
|
2940
2943
|
if time.monotonic() >= read_deadline:
|
|
2941
|
-
if
|
|
2944
|
+
if complete:
|
|
2942
2945
|
raise _FetchError('err_incomplete_html')
|
|
2943
2946
|
break
|
|
2944
2947
|
chunk = r.read(min(65536, ceiling + 1 - len(data)))
|
|
2945
2948
|
if not chunk:
|
|
2946
2949
|
break
|
|
2947
2950
|
data += chunk
|
|
2948
|
-
if
|
|
2951
|
+
if complete:
|
|
2949
2952
|
if len(data) > ceiling:
|
|
2950
|
-
raise _FetchError('err_too_big', mb=
|
|
2953
|
+
raise _FetchError('err_too_big', mb=ceiling // 1000000)
|
|
2951
2954
|
if getattr(r, 'length', 0):
|
|
2952
2955
|
raise _FetchError('err_incomplete_html')
|
|
2953
2956
|
if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
|
|
@@ -2958,8 +2961,8 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
|
|
|
2958
2961
|
data = stream.read(ceiling + 1)
|
|
2959
2962
|
except EOFError as err:
|
|
2960
2963
|
raise _FetchError('err_incomplete_html') from err
|
|
2961
|
-
if
|
|
2962
|
-
raise _FetchError('err_too_big', mb=
|
|
2964
|
+
if complete and len(data) > ceiling:
|
|
2965
|
+
raise _FetchError('err_too_big', mb=ceiling // 1000000)
|
|
2963
2966
|
if truncate_at is not None:
|
|
2964
2967
|
data = data[:ceiling]
|
|
2965
2968
|
ctype = (r.headers.get('Content-Type') or '').lower()
|
|
@@ -43,6 +43,7 @@ from .a11yaudit import audit_html
|
|
|
43
43
|
|
|
44
44
|
CORPUS_FORMAT = 'a11y-corpus/1'
|
|
45
45
|
EVAL_FORMAT = 'a11y-corpus-evaluation/1'
|
|
46
|
+
_CRITERION_CODE = re.compile(r'[1-4]\.[0-9]\.[1-9][0-9]?')
|
|
46
47
|
|
|
47
48
|
_NOTE_README = """# a11y corpus {version}
|
|
48
49
|
|
|
@@ -61,6 +62,9 @@ on that page (criterion codes, e.g. "1.4.4" — not tool-specific rule ids).
|
|
|
61
62
|
Placebo entries accept the same shape; anything you flag on them counts as a
|
|
62
63
|
false positive by construction (no violation was injected).
|
|
63
64
|
|
|
65
|
+
Submit exactly one row per case, including a row with an empty
|
|
66
|
+
`criteria_found` array for each page that was checked without findings.
|
|
67
|
+
|
|
64
68
|
Score it (from inside this directory):
|
|
65
69
|
|
|
66
70
|
a11ytoolkit corpus evaluate --submission my-submission.jsonl .
|
|
@@ -267,67 +271,88 @@ def evaluate(submission, directory='corpus', submission_name='submission'):
|
|
|
267
271
|
criterio. Contrato NEUTRAL: códigos WCAG, no señales nuestras."""
|
|
268
272
|
entries = _load_entries(directory)
|
|
269
273
|
by_id = {}
|
|
274
|
+
seen = set()
|
|
275
|
+
duplicates = set()
|
|
270
276
|
unknown = []
|
|
271
277
|
invalid = []
|
|
272
278
|
for entry in submission:
|
|
273
279
|
if not isinstance(entry, dict):
|
|
274
|
-
|
|
280
|
+
invalid.append({'entry': repr(entry)[:60]})
|
|
275
281
|
continue
|
|
276
282
|
cid = entry.get('case_id')
|
|
283
|
+
if not isinstance(cid, str) or not cid:
|
|
284
|
+
invalid.append({'case_id': repr(cid)[:60]})
|
|
285
|
+
continue
|
|
277
286
|
if cid not in entries:
|
|
278
287
|
unknown.append(cid)
|
|
279
288
|
continue
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
289
|
+
if cid in seen:
|
|
290
|
+
duplicates.add(cid)
|
|
291
|
+
by_id.pop(cid, None)
|
|
292
|
+
continue
|
|
293
|
+
seen.add(cid)
|
|
294
|
+
found = entry.get('criteria_found')
|
|
295
|
+
if not isinstance(found, list) or any(
|
|
296
|
+
not isinstance(code, str) or not _CRITERION_CODE.fullmatch(code)
|
|
297
|
+
for code in found
|
|
298
|
+
):
|
|
284
299
|
invalid.append({'case_id': cid,
|
|
285
300
|
'criteria_found': repr(found)[:60]})
|
|
286
301
|
continue
|
|
287
|
-
by_id[cid] =
|
|
288
|
-
killed
|
|
302
|
+
by_id[cid] = list(dict.fromkeys(found))
|
|
303
|
+
killed = mutants = controls = mutants_scored = controls_scored = 0
|
|
304
|
+
missed, fps, additional, missing = [], [], [], []
|
|
289
305
|
per_crit = {}
|
|
290
306
|
for cid, case in sorted(entries.items()):
|
|
291
|
-
found = by_id.get(cid
|
|
307
|
+
found = by_id.get(cid)
|
|
308
|
+
if found is None:
|
|
309
|
+
missing.append(cid)
|
|
292
310
|
if case['kind'] == 'placebo':
|
|
311
|
+
controls += 1
|
|
312
|
+
controls_scored += found is not None
|
|
293
313
|
if found:
|
|
294
314
|
fps.append({'case_id': cid, 'criteria_flagged': found})
|
|
295
315
|
continue
|
|
316
|
+
mutants += 1
|
|
296
317
|
exp = case['expected']['criterion']
|
|
297
|
-
per_crit.setdefault(exp, {'expected': 0, 'killed': 0})
|
|
298
|
-
|
|
318
|
+
tally = per_crit.setdefault(exp, {'expected': 0, 'killed': 0})
|
|
319
|
+
tally['expected'] += 1
|
|
320
|
+
if found is None:
|
|
321
|
+
continue
|
|
322
|
+
mutants_scored += 1
|
|
323
|
+
extra = [c for c in found if c != exp]
|
|
299
324
|
if exp in found:
|
|
300
|
-
killed
|
|
301
|
-
|
|
325
|
+
killed += 1
|
|
326
|
+
tally['killed'] += 1
|
|
302
327
|
else:
|
|
303
328
|
missed.append({'case_id': cid, 'expected_criterion': exp,
|
|
304
329
|
'operator': case['expected']['operator'],
|
|
305
|
-
'found_instead':
|
|
306
|
-
extra = [c for c in found if c != exp]
|
|
330
|
+
'found_instead': extra})
|
|
307
331
|
if extra:
|
|
308
332
|
additional.append({'case_id': cid, 'additional_criteria': extra})
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
333
|
+
reasons = []
|
|
334
|
+
if not controls:
|
|
335
|
+
reasons.append('corpus has no control (placebo) pages')
|
|
336
|
+
if missing:
|
|
337
|
+
reasons.append('%d cases without a valid submission' % len(missing))
|
|
338
|
+
if duplicates:
|
|
339
|
+
reasons.append('duplicate case IDs')
|
|
340
|
+
if unknown:
|
|
341
|
+
reasons.append('unknown case IDs')
|
|
342
|
+
if invalid:
|
|
343
|
+
reasons.append('invalid submission entries')
|
|
344
|
+
return {
|
|
317
345
|
'format': EVAL_FORMAT,
|
|
318
346
|
'submission_name': submission_name,
|
|
319
|
-
'mutants':
|
|
320
|
-
'
|
|
347
|
+
'mutants': mutants, 'killed': killed,
|
|
348
|
+
'mutant_pages_scored': mutants_scored,
|
|
349
|
+
'kill_rate': round(killed / mutants, 4) if mutants else None,
|
|
321
350
|
'missed_detail': missed,
|
|
322
|
-
'control_pages':
|
|
351
|
+
'control_pages': controls,
|
|
323
352
|
'false_positives': fps,
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
'incomplete_reason': 'no control (placebo) pages in the submission: '
|
|
328
|
-
'the false-positive claim cannot be evaluated'}
|
|
329
|
-
if pla_scored == 0 else {'incomplete': False}),
|
|
330
|
-
'control_pages_scored': pla_scored,
|
|
353
|
+
'incomplete': bool(reasons),
|
|
354
|
+
**({'incomplete_reason': '; '.join(reasons)} if reasons else {}),
|
|
355
|
+
'control_pages_scored': controls_scored,
|
|
331
356
|
'additional_findings_on_mutants': {'count': len(additional),
|
|
332
357
|
'note': 'reported, not scored: only '
|
|
333
358
|
'placebo flags are false '
|
|
@@ -335,11 +360,11 @@ def evaluate(submission, directory='corpus', submission_name='submission'):
|
|
|
335
360
|
'sample': additional[:10]},
|
|
336
361
|
'per_criterion': per_crit,
|
|
337
362
|
'unknown_case_ids': unknown,
|
|
363
|
+
'duplicate_case_ids': sorted(duplicates),
|
|
338
364
|
'invalid_entries': invalid,
|
|
339
|
-
'cases_without_submission': [
|
|
340
|
-
|
|
365
|
+
'cases_without_submission': missing[:10],
|
|
366
|
+
'cases_without_submission_count': len(missing),
|
|
341
367
|
}
|
|
342
|
-
return out
|
|
343
368
|
|
|
344
369
|
|
|
345
370
|
def reference(directory='corpus'):
|
|
@@ -364,7 +389,7 @@ def _read_submission(path):
|
|
|
364
389
|
return [], None
|
|
365
390
|
if text.startswith('['):
|
|
366
391
|
try:
|
|
367
|
-
return
|
|
392
|
+
return json.loads(text), None
|
|
368
393
|
except json.JSONDecodeError as e:
|
|
369
394
|
return [], {'count': 1,
|
|
370
395
|
'example': 'json array: %s' % str(e)[:120]}
|
|
@@ -380,8 +405,7 @@ def _read_submission(path):
|
|
|
380
405
|
invalid = {'count': 0, 'example': 'line %d: %s' % (n, str(e)[:120])}
|
|
381
406
|
invalid['count'] += 1
|
|
382
407
|
continue
|
|
383
|
-
|
|
384
|
-
out.append(obj)
|
|
408
|
+
out.append(obj)
|
|
385
409
|
return out, invalid
|
|
386
410
|
|
|
387
411
|
|
|
@@ -418,15 +442,23 @@ def main(argv):
|
|
|
418
442
|
print(json.dumps({'ok': ok, 'detail': detail}, ensure_ascii=False))
|
|
419
443
|
return 0 if ok else 1
|
|
420
444
|
if a.action == 'evaluate':
|
|
421
|
-
|
|
445
|
+
try:
|
|
446
|
+
entries, invalid = _read_submission(a.submission)
|
|
447
|
+
except (OSError, UnicodeError) as exc:
|
|
448
|
+
print(json.dumps({'error': str(exc)}, ensure_ascii=False))
|
|
449
|
+
return 1
|
|
422
450
|
res = evaluate(entries, a.directory,
|
|
423
451
|
submission_name=os.path.basename(a.submission))
|
|
424
452
|
if invalid:
|
|
425
453
|
# el grading sigue con las líneas válidas, pero las corruptas se
|
|
426
454
|
# declaran — jamás un veredicto mudo sobre input roto
|
|
427
455
|
res['invalid_lines'] = invalid
|
|
456
|
+
reason = res.get('incomplete_reason')
|
|
457
|
+
res['incomplete'] = True
|
|
458
|
+
res['incomplete_reason'] = (
|
|
459
|
+
reason + '; invalid JSON in submission' if reason else 'invalid JSON in submission')
|
|
428
460
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
429
|
-
return 0
|
|
461
|
+
return 1 if res['incomplete'] else 0
|
|
430
462
|
if a.action == 'reference':
|
|
431
463
|
outp = os.path.join(a.directory, 'results', 'reference.json')
|
|
432
464
|
manifest_path = os.path.join(a.directory, 'MANIFEST.json')
|
package/a11y_toolkit/a11ydocx.py
CHANGED
|
@@ -18,9 +18,11 @@ CLI:
|
|
|
18
18
|
|
|
19
19
|
import argparse
|
|
20
20
|
import json
|
|
21
|
+
import os
|
|
21
22
|
import re
|
|
22
23
|
import sys
|
|
23
24
|
import zipfile
|
|
25
|
+
from xml.etree import ElementTree as ET
|
|
24
26
|
from . import a11yi18n
|
|
25
27
|
|
|
26
28
|
T = a11yi18n.pair('docx') # locales/<lang>.json — community-editable
|
|
@@ -28,6 +30,18 @@ T = a11yi18n.pair('docx') # locales/<lang>.json — community-editable
|
|
|
28
30
|
# techo de ingesta por miembro ZIP: 40 MB descomprimidos — un .docx legítimo
|
|
29
31
|
# no llega ni de lejos; una bomba ZIP sí
|
|
30
32
|
_MAX_MEMBER_BYTES = 40 * 1024 * 1024
|
|
33
|
+
_WORD_NS = ('http://schemas.openxmlformats.org/wordprocessingml/2006/main',
|
|
34
|
+
'http://purl.oclc.org/ooxml/wordprocessingml/main')
|
|
35
|
+
_DRAWING_PROPERTIES = {
|
|
36
|
+
'{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}docPr',
|
|
37
|
+
'{http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing}docPr',
|
|
38
|
+
}
|
|
39
|
+
_RELATIONSHIP_IDS = (
|
|
40
|
+
'{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id',
|
|
41
|
+
'{http://purl.oclc.org/ooxml/officeDocument/relationships}id',
|
|
42
|
+
)
|
|
43
|
+
_RELATIONSHIP = '{http://schemas.openxmlformats.org/package/2006/relationships}Relationship'
|
|
44
|
+
_HEADING_NAME = re.compile(r'^(?:heading|encabezado|t[ií]tulo|überschrift|titre)\s*([1-9])$', re.I)
|
|
31
45
|
|
|
32
46
|
_CRIT = {
|
|
33
47
|
'docx_no_alt': ('1.1.1', 'high'), 'docx_fake_headings': ('1.3.1', 'medium'),
|
|
@@ -57,7 +71,7 @@ class _OverCap(Exception):
|
|
|
57
71
|
|
|
58
72
|
|
|
59
73
|
def _capped_read(z, member):
|
|
60
|
-
"""
|
|
74
|
+
"""Bytes de un miembro del ZIP (None si no existe). El techo de
|
|
61
75
|
descompresión por miembro vive AQUÍ, en la única puerta de lectura del
|
|
62
76
|
cribado: file_size es el declarado del directorio central, el estándar
|
|
63
77
|
contra bombas ZIP de los descompresores serios. Toda lectura pasa por
|
|
@@ -70,195 +84,159 @@ def _capped_read(z, member):
|
|
|
70
84
|
if info.file_size > _MAX_MEMBER_BYTES:
|
|
71
85
|
raise _OverCap(f'{member} declares {info.file_size} bytes '
|
|
72
86
|
f'(>{_MAX_MEMBER_BYTES}): over the intake cap')
|
|
73
|
-
return z.read(member)
|
|
87
|
+
return z.read(member)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _DocumentTree(ET.TreeBuilder):
|
|
91
|
+
def doctype(self, name, pubid, system):
|
|
92
|
+
raise ET.ParseError('DOCTYPE is not supported in DOCX parts')
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _read_xml(z, member):
|
|
96
|
+
data = _capped_read(z, member)
|
|
97
|
+
if data is None:
|
|
98
|
+
return None
|
|
99
|
+
return ET.fromstring(data, parser=ET.XMLParser(target=_DocumentTree()))
|
|
74
100
|
|
|
75
101
|
|
|
76
102
|
def docx_screen(path, lang='en'):
|
|
77
|
-
"""
|
|
103
|
+
"""Screen a local DOCX using the standard library ZIP and XML readers."""
|
|
78
104
|
try:
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
return {'error': '
|
|
84
|
-
try:
|
|
85
|
-
return _screen_zip(z, lang, path)
|
|
86
|
-
except _OverCap as e:
|
|
87
|
-
# contenido NO confiable: la ingesta no descomprime sin límite
|
|
88
|
-
return {'error': str(e)}
|
|
105
|
+
with zipfile.ZipFile(path) as archive:
|
|
106
|
+
return _screen_zip(archive, lang, path)
|
|
107
|
+
except (OSError, zipfile.BadZipFile, RuntimeError, ET.ParseError, ValueError, _OverCap) as error:
|
|
108
|
+
message = 'No se pudo leer el DOCX' if lang == 'es' else 'Could not read DOCX'
|
|
109
|
+
return {'error': f'{message}: {error}', 'mode': 'docx', 'file': os.path.basename(path)}
|
|
89
110
|
|
|
90
111
|
|
|
91
112
|
def _screen_zip(z, lang, path):
|
|
92
|
-
body =
|
|
93
|
-
|
|
113
|
+
body = _read_xml(z, 'word/document.xml')
|
|
114
|
+
if body is None or body.tag not in {f'{{{uri}}}document' for uri in _WORD_NS}:
|
|
115
|
+
message = ('Falta el documento XML de WordprocessingML' if lang == 'es'
|
|
116
|
+
else 'Missing WordprocessingML document')
|
|
117
|
+
return {'error': message, 'mode': 'docx', 'file': os.path.basename(path)}
|
|
118
|
+
word = body.tag.split('}', 1)[0] + '}'
|
|
119
|
+
namespaces = {'w': word[1:-1]}
|
|
120
|
+
value = word + 'val'
|
|
121
|
+
styles = _read_xml(z, 'word/styles.xml')
|
|
122
|
+
relationships = _read_xml(z, 'word/_rels/document.xml.rels')
|
|
94
123
|
findings = []
|
|
95
124
|
|
|
96
|
-
def add(key):
|
|
97
|
-
|
|
98
|
-
findings.append({'severity':
|
|
99
|
-
'signal': key, 'issue': _t(lang, key),
|
|
125
|
+
def add(key, **fields):
|
|
126
|
+
criterion, severity = _CRIT[key]
|
|
127
|
+
findings.append({'severity': severity, 'criterion': f'{criterion} (DOCX)',
|
|
128
|
+
'signal': key, 'issue': _t(lang, key).format(**fields),
|
|
100
129
|
'remediation': _t(lang, key + '_rem')})
|
|
101
130
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
'issue': _t(lang, 'docx_no_alt').format(n=n),
|
|
111
|
-
'remediation': _t(lang, 'docx_no_alt_rem')})
|
|
112
|
-
|
|
113
|
-
# idioma: w:lang en styles.xml (default del documento)
|
|
131
|
+
def paragraph_text(element):
|
|
132
|
+
return ''.join(text.text or '' for text in element.iter(word + 't')).strip()
|
|
133
|
+
|
|
134
|
+
docprs = [node for node in body.iter() if node.tag in _DRAWING_PROPERTIES]
|
|
135
|
+
no_alt = sum(not node.get('descr', '').strip() for node in docprs)
|
|
136
|
+
if no_alt:
|
|
137
|
+
add('docx_no_alt', n=no_alt)
|
|
138
|
+
|
|
114
139
|
language = None
|
|
115
|
-
styles = _capped_read(z, 'word/styles.xml')
|
|
116
140
|
if styles is not None:
|
|
117
|
-
|
|
118
|
-
|
|
141
|
+
default = styles.find('w:docDefaults/w:rPrDefault/w:rPr/w:lang', namespaces)
|
|
142
|
+
if default is None:
|
|
143
|
+
default = styles.find('.//w:lang', namespaces)
|
|
144
|
+
if default is not None:
|
|
145
|
+
language = default.get(value)
|
|
119
146
|
if not language:
|
|
120
147
|
add('docx_no_lang')
|
|
121
148
|
|
|
122
|
-
|
|
123
|
-
# encabezado de la primera tapaba la falta de la segunda con un conteo
|
|
124
|
-
# global, y <w:tblHeader w:val="true"/> —con atributos— no casaba con el
|
|
125
|
-
# regex de elemento vacío)
|
|
126
|
-
n_tables = len(re.findall(r'<w:tbl>', body))
|
|
149
|
+
tables = list(body.iter(word + 'tbl'))
|
|
127
150
|
tables_missing = 0
|
|
128
|
-
for
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
151
|
+
for table in tables:
|
|
152
|
+
pending, has_header = list(table), False
|
|
153
|
+
for node in pending:
|
|
154
|
+
if node.tag == word + 'tr':
|
|
155
|
+
header = node.find('w:trPr/w:tblHeader', namespaces)
|
|
156
|
+
if header is not None and header.get(value, 'true').lower() not in ('0', 'false', 'off'):
|
|
157
|
+
has_header = True
|
|
158
|
+
break
|
|
159
|
+
elif node.tag != word + 'tbl':
|
|
160
|
+
pending.extend(node)
|
|
161
|
+
if not has_header:
|
|
132
162
|
tables_missing += 1
|
|
133
|
-
if
|
|
134
|
-
add('docx_table_no_header')
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
'remediation': _t(lang, 'docx_fake_headings_rem')})
|
|
155
|
-
|
|
156
|
-
# ── listas falsas: párrafos con viñetas/números TIPOGRAFIADOS en vez de
|
|
157
|
-
# lista de Word (sin w:numPr). Umbral anti-FP: 2+ párrafos CONSECUTIVOS
|
|
158
|
-
# con glifo de viñeta, o 3+ consecutivos numerados con incremento +1
|
|
159
|
-
# (los «1. Enero» de las fechas no incrementan y quedan fuera).
|
|
160
|
-
_doc_paragraphs = re.findall(r'<w:p\b.*?</w:p>|<w:p\b[^>]*/>', body, re.S)
|
|
161
|
-
def _ptext(p):
|
|
162
|
-
return ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', p)).strip()
|
|
163
|
-
fake_list_groups, _run = 0, []
|
|
164
|
-
def _flush():
|
|
165
|
-
nonlocal _run, fake_list_groups
|
|
166
|
-
n_bul = sum(1 for t in _run if t[0] == 'b')
|
|
167
|
-
if n_bul >= 2:
|
|
163
|
+
if tables_missing:
|
|
164
|
+
add('docx_table_no_header', n=tables_missing)
|
|
165
|
+
|
|
166
|
+
heading_styles = {}
|
|
167
|
+
if styles is not None:
|
|
168
|
+
for style in styles.iter(word + 'style'):
|
|
169
|
+
name = style.find('w:name', namespaces)
|
|
170
|
+
if name is not None:
|
|
171
|
+
match = _HEADING_NAME.fullmatch(name.get(value, '').strip())
|
|
172
|
+
if match:
|
|
173
|
+
heading_styles[style.get(word + 'styleId')] = int(match.group(1))
|
|
174
|
+
|
|
175
|
+
levels, fake = [], 0
|
|
176
|
+
fake_list_groups, sequence = 0, []
|
|
177
|
+
|
|
178
|
+
def flush():
|
|
179
|
+
nonlocal fake_list_groups
|
|
180
|
+
if sequence.count(None) >= 2:
|
|
181
|
+
fake_list_groups += 1
|
|
182
|
+
elif (len(sequence) >= 3 and sequence[0] in (0, 1)
|
|
183
|
+
and all(number == sequence[0] + i for i, number in enumerate(sequence))):
|
|
168
184
|
fake_list_groups += 1
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if '
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
185
|
+
sequence.clear()
|
|
186
|
+
|
|
187
|
+
for paragraph in body.iter(word + 'p'):
|
|
188
|
+
style = paragraph.find('w:pPr/w:pStyle', namespaces)
|
|
189
|
+
style_id = style.get(value, '') if style is not None else ''
|
|
190
|
+
direct = re.fullmatch(r'Heading([1-9])', style_id, re.I)
|
|
191
|
+
level = int(direct.group(1)) if direct else heading_styles.get(style_id)
|
|
192
|
+
text = paragraph_text(paragraph)
|
|
193
|
+
if level and not re.match(r'(?i)^TOC\d|Sumario|TDC', style_id):
|
|
194
|
+
levels.append(level)
|
|
195
|
+
elif not style_id.startswith('Heading') and 2 < len(text) < 120:
|
|
196
|
+
has_bold = any(node.get(value, 'true').lower() not in ('0', 'false')
|
|
197
|
+
for node in paragraph.iter(word + 'b'))
|
|
198
|
+
size = paragraph.find('.//w:sz', namespaces)
|
|
199
|
+
size_value = size.get(value, '') if size is not None else ''
|
|
200
|
+
if has_bold and size_value.isascii() and size_value.isdecimal() and int(size_value) >= 28:
|
|
201
|
+
fake += 1
|
|
202
|
+
|
|
203
|
+
if not text or paragraph.find('.//w:numPr', namespaces) is not None:
|
|
204
|
+
flush()
|
|
205
|
+
elif text[0] in _BULLET:
|
|
206
|
+
sequence.append(None)
|
|
207
|
+
else:
|
|
208
|
+
number = re.match(r'^(\d{1,3})[.)]\s+\S', text)
|
|
209
|
+
if number:
|
|
210
|
+
sequence.append(int(number.group(1)))
|
|
211
|
+
else:
|
|
212
|
+
flush()
|
|
213
|
+
flush()
|
|
214
|
+
if fake:
|
|
215
|
+
add('docx_fake_headings', n=fake)
|
|
189
216
|
if fake_list_groups:
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
sid = ms.group(1)
|
|
214
|
-
if re.match(r'(?i)^TOC\d|Sumario|TDC', sid):
|
|
215
|
-
continue
|
|
216
|
-
md = re.match(r'(?i)^Heading([1-9])$', sid)
|
|
217
|
-
if md:
|
|
218
|
-
levels.append(int(md.group(1)))
|
|
219
|
-
elif sid in _style_heads:
|
|
220
|
-
levels.append(_style_heads[sid])
|
|
221
|
-
skips = sum(1 for i in range(1, len(levels))
|
|
222
|
-
if levels[i] > levels[i-1] + 1)
|
|
223
|
-
if levels and skips:
|
|
224
|
-
findings.append({'severity': 'low', 'criterion': '1.3.1 (DOCX)',
|
|
225
|
-
'signal': 'docx_heading_skips',
|
|
226
|
-
'issue': _t(lang, 'docx_heading_skips').format(n=skips),
|
|
227
|
-
'remediation': _t(lang, 'docx_heading_skips_rem')})
|
|
228
|
-
|
|
229
|
-
# ── enlaces genéricos: «pincha aquí» (repetido), la URL cruda como
|
|
230
|
-
# texto, o el mismo genérico apuntando a destinos distintos. Relaciones
|
|
231
|
-
# desde word/_rels/document.xml.rels
|
|
232
|
-
rels = {}
|
|
233
|
-
rx = _capped_read(z, 'word/_rels/document.xml.rels') or ''
|
|
234
|
-
for m in re.finditer(r'<Relationship [^>]*Id="([^"]+)"[^>]*Target="([^"]+)"', rx):
|
|
235
|
-
rels[m.group(1)] = m.group(2)
|
|
236
|
-
gen_counts, gen_multi, raw_url, img_links_noalt = {}, 0, 0, 0
|
|
237
|
-
for hl in re.findall(r'<w:hyperlink\b.*?</w:hyperlink>', body, re.S):
|
|
238
|
-
txt = ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', hl)).strip()
|
|
239
|
-
target = ''
|
|
240
|
-
mr = re.search(r'r:id="([^"]+)"', hl)
|
|
241
|
-
if mr:
|
|
242
|
-
target = rels.get(mr.group(1), '')
|
|
243
|
-
low = txt.lower().rstrip('.…: ')
|
|
244
|
-
if txt and target and txt.replace(' ', '') in target:
|
|
245
|
-
raw_url += 1
|
|
246
|
-
elif low in _GENERIC_LINK:
|
|
247
|
-
if gen_counts.get(low, (0, set()))[0] >= 1:
|
|
248
|
-
gen_multi += 1
|
|
249
|
-
n0, t0 = gen_counts.get(low, (0, set()))
|
|
250
|
-
gen_counts[low] = (n0 + 1, t0 | {target})
|
|
251
|
-
# enlace solo-imagen sin alt (el docPr dentro del hyperlink sin descr)
|
|
252
|
-
if '<w:drawing' in hl or '<a:blip' in hl:
|
|
253
|
-
for dp in re.findall(r'<wp:docPr\b[^>]*>', hl):
|
|
254
|
-
if 'descr=' not in dp or re.search(r'descr="\s*"', dp):
|
|
255
|
-
img_links_noalt += 1
|
|
256
|
-
generic_n = gen_multi + raw_url + img_links_noalt
|
|
257
|
-
if generic_n:
|
|
258
|
-
findings.append({'severity': 'medium', 'criterion': '2.4.4 (DOCX)',
|
|
259
|
-
'signal': 'docx_generic_link',
|
|
260
|
-
'issue': _t(lang, 'docx_generic_link').format(n=generic_n),
|
|
261
|
-
'remediation': _t(lang, 'docx_generic_link_rem')})
|
|
217
|
+
add('docx_fake_list', n=fake_list_groups)
|
|
218
|
+
skips = sum(right > left + 1 for left, right in zip(levels, levels[1:]))
|
|
219
|
+
if skips:
|
|
220
|
+
add('docx_heading_skips', n=skips)
|
|
221
|
+
|
|
222
|
+
targets = ({rel.get('Id'): rel.get('Target', '') for rel in relationships.iter(_RELATIONSHIP)}
|
|
223
|
+
if relationships is not None else {})
|
|
224
|
+
generic_links, seen_generic = 0, set()
|
|
225
|
+
for hyperlink in body.iter(word + 'hyperlink'):
|
|
226
|
+
text = paragraph_text(hyperlink)
|
|
227
|
+
rel_id = hyperlink.get(_RELATIONSHIP_IDS[0]) or hyperlink.get(_RELATIONSHIP_IDS[1])
|
|
228
|
+
target = targets.get(rel_id, '')
|
|
229
|
+
label = text.lower().rstrip('.…: ')
|
|
230
|
+
if text and target and text.replace(' ', '') in target:
|
|
231
|
+
generic_links += 1
|
|
232
|
+
elif label in _GENERIC_LINK:
|
|
233
|
+
if label in seen_generic:
|
|
234
|
+
generic_links += 1
|
|
235
|
+
seen_generic.add(label)
|
|
236
|
+
generic_links += sum(not node.get('descr', '').strip() for node in hyperlink.iter()
|
|
237
|
+
if node.tag in _DRAWING_PROPERTIES)
|
|
238
|
+
if generic_links:
|
|
239
|
+
add('docx_generic_link', n=generic_links)
|
|
262
240
|
|
|
263
241
|
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
264
242
|
findings.sort(key=lambda h: order[h['severity']])
|
|
@@ -268,9 +246,9 @@ def _screen_zip(z, lang, path):
|
|
|
268
246
|
from .a11yaudit import compute_score
|
|
269
247
|
|
|
270
248
|
return {
|
|
271
|
-
'mode': 'docx', 'file':
|
|
249
|
+
'mode': 'docx', 'file': os.path.basename(path),
|
|
272
250
|
'language': language, 'images': len(docprs),
|
|
273
|
-
'tables':
|
|
251
|
+
'tables': len(tables), 'tables_without_header': tables_missing,
|
|
274
252
|
'heading_levels': levels,
|
|
275
253
|
'score': compute_score(findings),
|
|
276
254
|
'findings': findings,
|
|
@@ -285,8 +263,9 @@ def main(argv):
|
|
|
285
263
|
ap.add_argument('docx', help='local .docx file')
|
|
286
264
|
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
287
265
|
a = ap.parse_args(argv)
|
|
288
|
-
|
|
289
|
-
|
|
266
|
+
result = docx_screen(a.docx, lang=a.lang)
|
|
267
|
+
print(json.dumps(result, ensure_ascii=False, indent=1))
|
|
268
|
+
return 1 if 'error' in result else 0
|
|
290
269
|
|
|
291
270
|
|
|
292
271
|
if __name__ == '__main__':
|
|
@@ -69,6 +69,11 @@ def _is_page_report(report):
|
|
|
69
69
|
and (status is None or type(status) is int and 200 <= status < 400))
|
|
70
70
|
|
|
71
71
|
|
|
72
|
+
def _complete_page(report):
|
|
73
|
+
return (_is_page_report(report) and not report.get('truncated')
|
|
74
|
+
and not report.get('budget_exhausted') and not report.get('page_errors'))
|
|
75
|
+
|
|
76
|
+
|
|
72
77
|
def _canon(obj):
|
|
73
78
|
return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
|
74
79
|
|
|
@@ -164,26 +169,30 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
|
|
|
164
169
|
if isinstance(inf, dict) and inf.get('error'):
|
|
165
170
|
state = 'failed'
|
|
166
171
|
elif isinstance(inf, dict) and isinstance(inf.get('reports'), list):
|
|
167
|
-
usable = [normalize_report(p) for p in inf['reports'] if
|
|
172
|
+
usable = [normalize_report(p) for p in inf['reports'] if _complete_page(p)]
|
|
168
173
|
if usable:
|
|
169
174
|
state = ('partial' if len(usable) != len(inf['reports']) or inf.get('page_errors')
|
|
170
|
-
or inf.get('budget_exhausted') else 'complete')
|
|
175
|
+
or inf.get('budget_exhausted') or inf.get('truncated') else 'complete')
|
|
171
176
|
modes_included.update(p.get('mode', 'static') for p in usable)
|
|
172
177
|
# The disprover puts its revised findings on the site wrapper.
|
|
173
178
|
# Only actual page reports contribute executed modes.
|
|
174
|
-
if
|
|
179
|
+
if state == 'complete' and _complete_page(inf) and inf['findings']:
|
|
175
180
|
inf = normalize_report(inf)
|
|
176
181
|
pages.append(inf)
|
|
177
182
|
else:
|
|
178
183
|
pages.extend(usable)
|
|
184
|
+
elif any(_is_page_report(p) for p in inf['reports']):
|
|
185
|
+
state = 'partial'
|
|
179
186
|
elif inf.get('page_errors') or any(isinstance(p, dict) and p.get('error')
|
|
180
187
|
for p in inf['reports']):
|
|
181
188
|
state = 'failed'
|
|
182
189
|
elif _is_page_report(inf):
|
|
183
190
|
inf = normalize_report(inf)
|
|
184
|
-
state = '
|
|
185
|
-
|
|
186
|
-
|
|
191
|
+
state = 'partial'
|
|
192
|
+
if _complete_page(inf):
|
|
193
|
+
state = 'complete'
|
|
194
|
+
pages.append(inf)
|
|
195
|
+
modes_included.add(inf.get('mode', 'static'))
|
|
187
196
|
metadata = inf if isinstance(inf, dict) else {}
|
|
188
197
|
mode = metadata.get('mode')
|
|
189
198
|
report_artifacts.append({'type': f"report:{mode if isinstance(mode, str) else 'static'}",
|
package/a11y_toolkit/a11ypdf.py
CHANGED
|
@@ -43,6 +43,7 @@ def _t(lang, key):
|
|
|
43
43
|
# llegó hasta el techo basta para auditar — doctrina de lectura parcial).
|
|
44
44
|
_STREAM_CAP = 20_000_000 # 20 MB por stream descomprimido
|
|
45
45
|
_STREAM_BUDGET = 120_000_000 # 120 MB en total entre todos los streams
|
|
46
|
+
_MAX_PDF_BYTES = 30_000_000
|
|
46
47
|
|
|
47
48
|
|
|
48
49
|
def _decode_filters(chunk, filters_declared):
|
|
@@ -183,19 +184,25 @@ def _stream_low_contrast(text):
|
|
|
183
184
|
|
|
184
185
|
def pdf_screen(path_or_bytes, lang='en'):
|
|
185
186
|
"""Cribado estructural de accesibilidad de un PDF (fichero local)."""
|
|
187
|
+
limit = _MAX_PDF_BYTES
|
|
186
188
|
if isinstance(path_or_bytes, (bytes, bytearray)):
|
|
187
|
-
data = bytes(path_or_bytes)
|
|
189
|
+
data = bytes(path_or_bytes[:limit + 1])
|
|
188
190
|
name = '(bytes)'
|
|
189
|
-
truncated = False
|
|
190
191
|
else:
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
192
|
+
name = os.path.basename(path_or_bytes)
|
|
193
|
+
try:
|
|
194
|
+
with open(path_or_bytes, 'rb') as f:
|
|
195
|
+
data = f.read(limit + 1)
|
|
196
|
+
except OSError as error:
|
|
197
|
+
message = 'No se pudo leer el PDF' if lang == 'es' else 'Could not read PDF'
|
|
198
|
+
return {'error': f'{message}: {error}', 'mode': 'pdf', 'file': name}
|
|
196
199
|
|
|
197
200
|
if not data.startswith(b'%PDF-'):
|
|
198
|
-
|
|
201
|
+
message = 'Falta la cabecera %PDF-' if lang == 'es' else 'Missing %PDF- header'
|
|
202
|
+
return {'error': message, 'mode': 'pdf', 'file': name}
|
|
203
|
+
if len(data) > limit:
|
|
204
|
+
message = 'El PDF supera el límite de 30 MB' if lang == 'es' else 'PDF exceeds the 30 MB limit'
|
|
205
|
+
return {'error': message, 'mode': 'pdf', 'file': name, 'truncated': True}
|
|
199
206
|
|
|
200
207
|
streams = _uncompressed_streams(data)
|
|
201
208
|
# `todo` respeta el MISMO presupuesto acumulado: ensamblar 40 streams de
|
|
@@ -429,7 +436,7 @@ def pdf_screen(path_or_bytes, lang='en'):
|
|
|
429
436
|
'tag_counts': {'td': n_tag_td, 'th': n_tag_th, 'h': n_tag_h},
|
|
430
437
|
'ocr_layer_only': bool(_t_inv and not _t_vis),
|
|
431
438
|
'form_fields': n_fields, 'form_labels': n_tu,
|
|
432
|
-
'truncated':
|
|
439
|
+
'truncated': False,
|
|
433
440
|
'score': compute_score(findings),
|
|
434
441
|
'findings': findings,
|
|
435
442
|
'summary': {s: sum(1 for h in findings if h['severity'] == s)
|
|
@@ -446,8 +453,9 @@ def main(argv):
|
|
|
446
453
|
ap.add_argument('pdf', help='local PDF file')
|
|
447
454
|
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
448
455
|
a = ap.parse_args(argv)
|
|
449
|
-
|
|
450
|
-
|
|
456
|
+
result = pdf_screen(a.pdf, lang=a.lang)
|
|
457
|
+
print(json.dumps(result, ensure_ascii=False, indent=1))
|
|
458
|
+
return 1 if 'error' in result else 0
|
|
451
459
|
|
|
452
460
|
|
|
453
461
|
if __name__ == '__main__':
|
|
@@ -21,7 +21,7 @@ from .a11yact import _NOT_DEAD
|
|
|
21
21
|
from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
|
|
22
22
|
import sys
|
|
23
23
|
|
|
24
|
-
from .a11yaudit import audit_url, audit_site, audit_html
|
|
24
|
+
from .a11yaudit import audit_url, audit_site, audit_html, completed_report_pages
|
|
25
25
|
|
|
26
26
|
LEVEL = {'high': 'error', 'medium': 'warning', 'low': 'note'}
|
|
27
27
|
|
|
@@ -63,13 +63,15 @@ def from_report(report, driver_version=None, standard=None, target=None):
|
|
|
63
63
|
(con la lista 'reports'). Con standard='en301549' cada regla gana
|
|
64
64
|
properties/tags con su cláusula EN 301 549 V4.1.1 (9.x web por defecto,
|
|
65
65
|
10.x documents, 11.x software) — filtrable en code scanning."""
|
|
66
|
+
pages, error = completed_report_pages(report)
|
|
67
|
+
if error:
|
|
68
|
+
return error
|
|
66
69
|
if driver_version is None:
|
|
67
70
|
# versión del driver = fuente única (estaba congelada en '3.2.0' con el
|
|
68
71
|
# motor en 5.26: GitHub mostraba una versión muerta en code scanning)
|
|
69
72
|
from .server import VERSION as _V # lazy: server importa este módulo
|
|
70
73
|
driver_version = _V
|
|
71
74
|
from . import a11yen301549 as _enstd
|
|
72
|
-
pages = report.get('reports') if isinstance(report.get('reports'), list) else [report]
|
|
73
75
|
rules = {}
|
|
74
76
|
results = []
|
|
75
77
|
skipped = 0 # hallazgos truncados/hostiles: se saltan, jamás un KeyError
|
|
@@ -167,19 +169,23 @@ def main(argv):
|
|
|
167
169
|
default=None, help='target EN: web=9.x, documents=10.x, '
|
|
168
170
|
'software=11.x (default: según el modo del informe)')
|
|
169
171
|
a = ap.parse_args(argv)
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
172
|
+
try:
|
|
173
|
+
if a.from_audit:
|
|
174
|
+
with open(a.from_audit, encoding='utf-8') as f:
|
|
175
|
+
report = json.load(f)
|
|
176
|
+
elif a.url:
|
|
177
|
+
report = (audit_site(a.url, max_pages=a.pages, lang=a.lang)
|
|
178
|
+
if a.pages > 1 else audit_url(a.url, lang=a.lang))
|
|
179
|
+
else:
|
|
180
|
+
with open(a.file, encoding='utf-8', errors='replace') as f:
|
|
181
|
+
report = audit_html(f.read(), a.file, lang=a.lang)
|
|
182
|
+
except (OSError, ValueError) as error:
|
|
183
|
+
print(json.dumps({'error': str(error)}, ensure_ascii=False))
|
|
181
184
|
return 1
|
|
182
185
|
sarif = from_report(report, standard=a.standard, target=a.target)
|
|
186
|
+
if 'error' in sarif:
|
|
187
|
+
print(json.dumps(sarif, ensure_ascii=False))
|
|
188
|
+
return 1
|
|
183
189
|
with open(a.out, 'w', encoding='utf-8') as f:
|
|
184
190
|
json.dump(sarif, f, ensure_ascii=False, indent=1)
|
|
185
191
|
summary = report.get('summary', {'high': 0, 'medium': 0, 'low': 0})
|
package/a11y_toolkit/a11yvtt.py
CHANGED
|
@@ -17,10 +17,14 @@ import argparse
|
|
|
17
17
|
import json
|
|
18
18
|
import re
|
|
19
19
|
import sys
|
|
20
|
+
from http.client import HTTPException
|
|
20
21
|
from . import a11yi18n
|
|
21
22
|
|
|
22
23
|
_RE_TIME = re.compile(
|
|
23
|
-
r'(?:(
|
|
24
|
+
r'(?:([0-9]{2,}):)?([0-5][0-9]):([0-5][0-9])\.([0-9]{3})[ \t]+-->[ \t]+'
|
|
25
|
+
r'(?:([0-9]{2,}):)?([0-5][0-9]):([0-5][0-9])\.([0-9]{3})(?=$|[ \t])')
|
|
26
|
+
_RE_HEADER = re.compile(r'WEBVTT(?:[ \t].*)?')
|
|
27
|
+
_MAX_BYTES = 2_000_000
|
|
24
28
|
|
|
25
29
|
# etiquetas de marcado WebVTT — <v>, <i>, <b>, <c.cls>, anclas/timestamps
|
|
26
30
|
# <00:00:01.000>: no se leen en voz alta, no cuentan como caracteres de lectura
|
|
@@ -39,14 +43,30 @@ def _seconds(h, m, s, ms):
|
|
|
39
43
|
|
|
40
44
|
def vtt_check(url, duration=None, lang='en'):
|
|
41
45
|
"""Descarga y juzga un .vtt — el contenido de 1.2.2, no su mera presencia."""
|
|
42
|
-
from .a11yaudit import _fetch,
|
|
46
|
+
from .a11yaudit import _fetch, _FetchError, _t as audit_text, CRIT
|
|
43
47
|
# text/vtt es EL MIME del formato (WebVTT spec): el filtro anti-no-HTML
|
|
44
48
|
# del descargador lo rechazaba con err_not_html servido correctamente
|
|
45
49
|
# (revisión externa, 3ª pasada — la suite no lo veía porque sustituía el
|
|
46
50
|
# descargador)
|
|
47
|
-
|
|
51
|
+
def error(message):
|
|
52
|
+
return {'error': message, 'mode': 'vtt', 'url': url}
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
data = _fetch(url, timeout=30, truncate_at=_MAX_BYTES, accept_ct=('text/vtt',),
|
|
56
|
+
require_complete=True)
|
|
57
|
+
except _FetchError as failure:
|
|
58
|
+
if failure.key == 'err_too_big':
|
|
59
|
+
return error('WebVTT supera el límite de 2 MB' if lang == 'es'
|
|
60
|
+
else 'WebVTT exceeds the 2 MB limit')
|
|
61
|
+
if failure.key == 'err_incomplete_html':
|
|
62
|
+
return error('Descarga de WebVTT incompleta' if lang == 'es'
|
|
63
|
+
else 'Incomplete WebVTT download')
|
|
64
|
+
return error(audit_text(lang, failure.key).format(**failure.fmt))
|
|
65
|
+
except (OSError, HTTPException, ValueError) as failure:
|
|
66
|
+
message = 'No se pudo descargar el WebVTT' if lang == 'es' else 'Could not fetch WebVTT'
|
|
67
|
+
return error(f'{message}: {failure}')
|
|
48
68
|
if isinstance(data, dict) and 'error' in data:
|
|
49
|
-
return data
|
|
69
|
+
return error(data['error'])
|
|
50
70
|
if isinstance(data, bytes):
|
|
51
71
|
text = data.decode('utf-8', errors='replace')
|
|
52
72
|
else:
|
|
@@ -59,34 +79,36 @@ def vtt_check(url, duration=None, lang='en'):
|
|
|
59
79
|
'signal': key, 'issue': _t(lang, key).format(**fmt),
|
|
60
80
|
'remediation': _t(lang, key + '_rem').format(**fmt)})
|
|
61
81
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
82
|
+
text = text.removeprefix('\ufeff').replace('\r\n', '\n').replace('\r', '\n')
|
|
83
|
+
header = text.partition('\n')[0]
|
|
84
|
+
if not _RE_HEADER.fullmatch(header) or '-->' in header:
|
|
85
|
+
return error('Cabecera WebVTT inválida' if lang == 'es' else 'Invalid WebVTT header')
|
|
66
86
|
|
|
67
87
|
blocks = [b for b in re.split(r'\n\s*\n', text) if b.strip()]
|
|
68
88
|
cues, malformed = [], []
|
|
69
89
|
for b in blocks[1:]: # el primero es la cabecera
|
|
70
90
|
lines = [l for l in b.splitlines() if l.strip()]
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
body = '\n'.join(lines[i + 1:]).strip()
|
|
76
|
-
break
|
|
91
|
+
if (lines[0] in ('NOTE', 'STYLE', 'REGION') or lines[0].startswith(('NOTE ', 'NOTE\t'))):
|
|
92
|
+
continue
|
|
93
|
+
timing = 0 if '-->' in lines[0] else 1
|
|
94
|
+
m = _RE_TIME.match(lines[timing]) if timing < len(lines) else None
|
|
77
95
|
if not m:
|
|
78
96
|
if '-->' in b:
|
|
79
97
|
malformed.append(lines[0][:30])
|
|
80
98
|
continue
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
99
|
+
try:
|
|
100
|
+
start = _seconds(*m.groups()[:4])
|
|
101
|
+
end = _seconds(*m.groups()[4:])
|
|
102
|
+
except (ValueError, OverflowError):
|
|
103
|
+
malformed.append(m.group(0)[:30])
|
|
104
|
+
continue
|
|
105
|
+
if end <= start or (cues and start < cues[-1]['start']):
|
|
84
106
|
# intervalo INVÁLIDO (tiempos invertidos): cue malformada y FUERA
|
|
85
107
|
# de toda medida (revisión externa, 3ª pasada — antes fabricaba
|
|
86
108
|
# segundos NEGATIVOS y un «demasiado rápida» por el clamp dur=0.1)
|
|
87
109
|
malformed.append(m.group(0)[:30])
|
|
88
110
|
continue
|
|
89
|
-
cues.append({'start': start, 'end': end, 'text':
|
|
111
|
+
cues.append({'start': start, 'end': end, 'text': '\n'.join(lines[timing + 1:]).strip()})
|
|
90
112
|
|
|
91
113
|
if malformed:
|
|
92
114
|
add('high', 'vtt_malformed', n=len(malformed), example=', '.join(malformed[:3]))
|
|
@@ -168,14 +190,9 @@ def main(argv):
|
|
|
168
190
|
ap.add_argument('--duration', type=float, help='media duration in seconds (coverage check)')
|
|
169
191
|
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
170
192
|
a = ap.parse_args(argv)
|
|
171
|
-
|
|
172
|
-
res = vtt_check(a.url, duration=a.duration, lang=a.lang)
|
|
173
|
-
except ValueError as e: # _FetchError incluido (descarga/scheme/HTML-size)
|
|
174
|
-
print(json.dumps({'error': str(e)}, ensure_ascii=False))
|
|
175
|
-
return 1
|
|
193
|
+
res = vtt_check(a.url, duration=a.duration, lang=a.lang)
|
|
176
194
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
177
|
-
return 0
|
|
178
|
-
return 0
|
|
195
|
+
return 1 if 'error' in res else 0
|
|
179
196
|
|
|
180
197
|
|
|
181
198
|
if __name__ == '__main__':
|
package/a11y_toolkit/server.py
CHANGED
|
@@ -97,7 +97,7 @@ try:
|
|
|
97
97
|
except ImportError:
|
|
98
98
|
ARIALIVE_JS = None # repo checkout: read the file
|
|
99
99
|
|
|
100
|
-
VERSION = '5.35.
|
|
100
|
+
VERSION = '5.35.3'
|
|
101
101
|
|
|
102
102
|
# Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
|
|
103
103
|
PARAM_ALIASES = {
|
|
@@ -714,7 +714,8 @@ TOOLS = [
|
|
|
714
714
|
'.vtt and judges what viewers get: malformed timing lines, empty cues, '
|
|
715
715
|
'overlaps, impossible reading speed (>21 chars/second, BBC/Netflix '
|
|
716
716
|
'standard) and coverage vs the media duration when given. Pass the .vtt '
|
|
717
|
-
'URL (same http/https guard as the audits).
|
|
717
|
+
'URL (same http/https guard as the audits). An invalid header or incomplete '
|
|
718
|
+
'download returns an error. Not a substitute for human '
|
|
718
719
|
'review of accuracy or speaker identification. '
|
|
719
720
|
'Returns JSON: {mode: "vtt", cues, characters, captioned_seconds, '
|
|
720
721
|
'findings [{criterion, severity, signal, issue, remediation}], summary, limits}.'),
|
|
@@ -734,7 +735,8 @@ TOOLS = [
|
|
|
734
735
|
'announces; 3.3.2 inputs, 4.1.2 buttons). '
|
|
735
736
|
'Full PDF/UA conformance needs a spec validator (veraPDF); this finds '
|
|
736
737
|
'the failures that make full validation pointless. Use for enterprise '
|
|
737
|
-
'document pipelines and PDFs linked from the audited site. '
|
|
738
|
+
'document pipelines and PDFs linked from the audited site. Inputs over '
|
|
739
|
+
'30 MB return an error before scoring. '
|
|
738
740
|
'Returns JSON: {mode: "pdf", pages, tagged, lang, title, images, '
|
|
739
741
|
'alt_entries, form_fields, form_labels, findings, summary, limits}.'),
|
|
740
742
|
'inputSchema': {'type': 'object', 'properties': {
|
|
@@ -745,7 +747,7 @@ TOOLS = [
|
|
|
745
747
|
{
|
|
746
748
|
'name': 'a11y_docx_screen',
|
|
747
749
|
'description': ('DOCX accessibility screening — the other half of enterprise paperwork. '
|
|
748
|
-
'Zero-dep structural pass on a LOCAL .docx: images with no alt text '
|
|
750
|
+
'Zero-dep structural pass on a LOCAL .docx with namespace-aware XML: images with no alt text '
|
|
749
751
|
'(docPr without descr), fake headings (bold+big paragraphs with no Heading '
|
|
750
752
|
'style — invisible to navigation pane and TOC), document language, tables '
|
|
751
753
|
'without marked header row. Full review needs a human; this finds what '
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kinti/a11y-toolkit",
|
|
3
|
-
"version": "5.35.
|
|
3
|
+
"version": "5.35.3",
|
|
4
4
|
"mcpName": "io.github.kinti/a11y-toolkit",
|
|
5
5
|
"description": "Zero-dependency WCAG 2.2 accessibility engine (37 MCP tools + CLI): audits, contrast fixing, SHA-256-sealed evidence packs, SARIF, EARL/ACT, CI ratchet. Self-contained: the pure-stdlib Python engine ships inside and runs via python3 \u2014 no downloads, no installs.",
|
|
6
6
|
"license": "MIT",
|