@kinti/a11y-toolkit 5.22.1 → 5.22.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/LICENSE +21 -0
- package/a11y_toolkit/__init__.py +5 -0
- package/a11y_toolkit/a11y.py +117 -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/a11ywcagem.py +177 -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 +7 -2
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""OpenACR (GSA) generator — the machine-readable ACR for public procurement.
|
|
3
|
+
|
|
4
|
+
Input: an a11y-evidence-pack/2 (from a11y_evidence / the a11y_evidence MCP
|
|
5
|
+
tool) or raw audit reports (the pack is built here). Output: OpenACR YAML
|
|
6
|
+
(the GSA open standard born from VPAT 2.4Rev 508; gsa.github.io/openacr)
|
|
7
|
+
with the full 55-criterion WCAG 2.2 A/AA matrix — chapters
|
|
8
|
+
success_criteria_level_a / _aa, one `web` component per criterion.
|
|
9
|
+
|
|
10
|
+
Honesty rule (non-negotiable, mirrors the pack and the VPAT): the machine
|
|
11
|
+
fills the adherence `notes`, never the level. Every criterion starts at
|
|
12
|
+
`not-evaluated` unless an automated fail forces `does-not-support` (or
|
|
13
|
+
`partially-supports` for review-level signals). A qualified human sets the
|
|
14
|
+
final level via `overrides` — same vocabulary as a11y_generate_vpat
|
|
15
|
+
(supports, partially_supports, …); the hyphenated forms of the OpenACR
|
|
16
|
+
format itself are accepted too. Every remark references the evidence
|
|
17
|
+
pack's sha256 — the same tamper-evidence rule as every document the
|
|
18
|
+
engine emits. An ACR is a vendor claim, not a certificate.
|
|
19
|
+
|
|
20
|
+
The YAML is written by a fixed-schema emitter (stdlib only): JSON string
|
|
21
|
+
escaping is valid YAML double-quoted style, so there is no parser
|
|
22
|
+
dependency AND no injection — user text (quotes, newlines, colons) can
|
|
23
|
+
never break the document structure.
|
|
24
|
+
|
|
25
|
+
CLI:
|
|
26
|
+
a11yopenacr.py pack.json --product "Acme App" -o openacr.yaml
|
|
27
|
+
a11ytoolkit openacr pack.json --product "Acme App" -o openacr.yaml
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
import argparse
|
|
31
|
+
import datetime
|
|
32
|
+
import json
|
|
33
|
+
import sys
|
|
34
|
+
from . import a11yi18n
|
|
35
|
+
from .a11yvpat import LEVELS, _STATUS_TO_LEVEL, _findings_by_code, _wcag_order
|
|
36
|
+
|
|
37
|
+
TXT = a11yi18n.pair('openacr_txt')
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _t(lang):
|
|
41
|
+
return TXT.get(lang, TXT['en'])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _q(value):
|
|
45
|
+
"""YAML double-quoted scalar: JSON escaping is valid YAML, so user text
|
|
46
|
+
can never break the document structure (fixed schema, no injection)."""
|
|
47
|
+
return json.dumps(str(value), ensure_ascii=False)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _remarks(row, finding, pack_sha):
|
|
51
|
+
"""Remarks por criterio: estado + valor medido + hallazgo + esfuerzo + hash."""
|
|
52
|
+
parts = []
|
|
53
|
+
if row.get('status'):
|
|
54
|
+
parts.append(row['status'])
|
|
55
|
+
if row.get('note'):
|
|
56
|
+
parts.append(row['note'])
|
|
57
|
+
val = row.get('value') or {}
|
|
58
|
+
if val.get('measured') or val.get('example'):
|
|
59
|
+
chunks = []
|
|
60
|
+
if val.get('measured'):
|
|
61
|
+
chunks.append('measured ' + str(val['measured']))
|
|
62
|
+
if val.get('example'):
|
|
63
|
+
chunks.append('e.g. ' + str(val['example']))
|
|
64
|
+
parts.append('; '.join(chunks))
|
|
65
|
+
if finding:
|
|
66
|
+
parts.append('issue: ' + str(finding.get('issue', ''))[:220])
|
|
67
|
+
if finding.get('remediation'):
|
|
68
|
+
parts.append('remediation: ' + str(finding['remediation'])[:220])
|
|
69
|
+
ef = row.get('effort')
|
|
70
|
+
if ef:
|
|
71
|
+
parts.append('remaining human effort: ' + str(ef.get('class'))
|
|
72
|
+
+ ' (' + str(ef.get('minutes')) + ' min)')
|
|
73
|
+
parts.append('evidence pack sha256 ' + pack_sha)
|
|
74
|
+
return ' | '.join(p for p in parts if p)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def generate_openacr(pack=None, reports=None, product='', product_version=None,
|
|
78
|
+
report_date=None, description=None, author=None, contact=None,
|
|
79
|
+
methods=None, notes=None, overrides=None, lang='en',
|
|
80
|
+
output_path=None):
|
|
81
|
+
"""Pack (o informes) → OpenACR YAML (GSA) + resumen.
|
|
82
|
+
|
|
83
|
+
overrides: {'1.1.1': 'supports', …} — niveles fijados por una persona
|
|
84
|
+
cualificada; se aceptan además las formas con guion del propio formato
|
|
85
|
+
('partially-supports'). Ganan sobre la derivación automática."""
|
|
86
|
+
t = _t(lang)
|
|
87
|
+
if pack is None:
|
|
88
|
+
if not reports:
|
|
89
|
+
return {'error': t['error_no_pack']}
|
|
90
|
+
from .a11yevidence import build_pack
|
|
91
|
+
pack = build_pack(reports)
|
|
92
|
+
if not isinstance(pack, dict) or 'criteria' not in pack:
|
|
93
|
+
return {'error': t['error_no_pack']}
|
|
94
|
+
overrides = {k: str(v).replace('-', '_') for k, v in (overrides or {}).items()}
|
|
95
|
+
for code, level in overrides.items():
|
|
96
|
+
if level not in LEVELS[lang]:
|
|
97
|
+
return {'error': t['error_level'].format(n=level)}
|
|
98
|
+
|
|
99
|
+
from .a11ycrit import _C as _CAT
|
|
100
|
+
pack_sha = pack.get('sha256', '')
|
|
101
|
+
by_code = _findings_by_code(pack)
|
|
102
|
+
report_date = report_date or datetime.date.today().isoformat()
|
|
103
|
+
|
|
104
|
+
rows = []
|
|
105
|
+
summary = {n: 0 for n in LEVELS[lang]}
|
|
106
|
+
for row in sorted(pack['criteria'], key=lambda r: _wcag_order(r['criterion'].split(' ')[0])):
|
|
107
|
+
code = row['criterion'].split(' ')[0]
|
|
108
|
+
level = _STATUS_TO_LEVEL.get(row.get('status'), 'not_evaluated')
|
|
109
|
+
level = overrides.get(code, level)
|
|
110
|
+
summary[level] += 1
|
|
111
|
+
cat = _CAT.get(code)
|
|
112
|
+
name = cat[1][lang][0] if cat else row['criterion']
|
|
113
|
+
wcag_level = cat[0] if cat else 'A'
|
|
114
|
+
rows.append({'code': code, 'name': name, 'level': wcag_level,
|
|
115
|
+
'adherence': level,
|
|
116
|
+
'remarks': _remarks(row, by_code.get(code), pack_sha)})
|
|
117
|
+
|
|
118
|
+
author = author or {}
|
|
119
|
+
doc_notes = t['notes_draft']
|
|
120
|
+
if (notes or '').strip():
|
|
121
|
+
doc_notes += ' ' + notes.strip()
|
|
122
|
+
methods = methods or t['method_default']
|
|
123
|
+
|
|
124
|
+
lines = []
|
|
125
|
+
lines.append('title: ' + _q(product + ' — OpenACR'))
|
|
126
|
+
lines.append('product:')
|
|
127
|
+
lines.append(' name: ' + _q(product))
|
|
128
|
+
if product_version:
|
|
129
|
+
lines.append(' version: ' + _q(product_version))
|
|
130
|
+
if description:
|
|
131
|
+
lines.append(' description: ' + _q(description))
|
|
132
|
+
lines.append('author:')
|
|
133
|
+
lines.append(' name: ' + _q(author.get('name', '')))
|
|
134
|
+
lines.append(' company_name: ' + _q(author.get('company', '')))
|
|
135
|
+
lines.append(' email: ' + _q(author.get('email', '') or (contact or '')))
|
|
136
|
+
if author.get('website'):
|
|
137
|
+
lines.append(' website: ' + _q(author['website']))
|
|
138
|
+
lines.append('report_date: ' + _q(report_date))
|
|
139
|
+
lines.append('last_modified_date: ' + _q(report_date))
|
|
140
|
+
lines.append('version: 1')
|
|
141
|
+
lines.append('notes: ' + _q(doc_notes))
|
|
142
|
+
lines.append('evaluation_methods_used: ' + _q(methods))
|
|
143
|
+
lines.append('legal_disclaimer: ' + _q(t['legal_disclaimer']))
|
|
144
|
+
lines.append('chapters:')
|
|
145
|
+
for chapter, wcag_lvl in (('success_criteria_level_a', 'A'),
|
|
146
|
+
('success_criteria_level_aa', 'AA')):
|
|
147
|
+
lines.append(' ' + chapter + ':')
|
|
148
|
+
lines.append(' notes: ' + _q(t['chapter_note']))
|
|
149
|
+
lines.append(' criteria:')
|
|
150
|
+
for f in rows:
|
|
151
|
+
if f['level'] != wcag_lvl:
|
|
152
|
+
continue
|
|
153
|
+
lines.append(' - num: ' + _q(f['code']))
|
|
154
|
+
lines.append(' components:')
|
|
155
|
+
lines.append(' - name: web')
|
|
156
|
+
lines.append(' adherence:')
|
|
157
|
+
lines.append(' level: ' + f['adherence'].replace('_', '-'))
|
|
158
|
+
lines.append(' notes: ' + _q(f['code'] + ' ' + f['name']
|
|
159
|
+
+ ' — ' + f['remarks']))
|
|
160
|
+
|
|
161
|
+
doc = '\n'.join(lines) + '\n'
|
|
162
|
+
res = {'yaml': doc, 'summary': summary,
|
|
163
|
+
'levels': {f['code']: f['adherence'] for f in rows},
|
|
164
|
+
'pack_sha256': pack_sha, 'format': 'openacr', 'draft': True, 'lang': lang}
|
|
165
|
+
if output_path:
|
|
166
|
+
with open(output_path, 'w', encoding='utf-8') as fh:
|
|
167
|
+
fh.write(doc)
|
|
168
|
+
res['saved_to'] = output_path
|
|
169
|
+
return res
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def main(argv):
|
|
173
|
+
ap = argparse.ArgumentParser(description='OpenACR (GSA) YAML from an evidence pack')
|
|
174
|
+
ap.add_argument('pack', nargs='?', help='evidence pack JSON (a11y_evidence output)')
|
|
175
|
+
ap.add_argument('--product', required=True, help='product name')
|
|
176
|
+
ap.add_argument('--reports', nargs='+', help='audit report JSONs (builds the pack) instead of pack')
|
|
177
|
+
ap.add_argument('--product-version', help='product version')
|
|
178
|
+
ap.add_argument('--report-date', help='report date (YYYY-MM-DD, default today)')
|
|
179
|
+
ap.add_argument('--description', help='product description')
|
|
180
|
+
ap.add_argument('--author', help='JSON: {"name":…, "company":…, "email":…, "website":…}')
|
|
181
|
+
ap.add_argument('--contact', help='contact email (author.email fallback)')
|
|
182
|
+
ap.add_argument('--methods', help='evaluation methods used')
|
|
183
|
+
ap.add_argument('--notes', help='additional notes')
|
|
184
|
+
ap.add_argument('--overrides', help='JSON: {"1.1.1": "supports", …}')
|
|
185
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
186
|
+
ap.add_argument('-o', '--out')
|
|
187
|
+
a = ap.parse_args(argv)
|
|
188
|
+
pack = json.load(open(a.pack, encoding='utf-8')) if a.pack else None
|
|
189
|
+
reports = [json.load(open(f, encoding='utf-8')) for f in a.reports] if a.reports else None
|
|
190
|
+
res = generate_openacr(pack=pack, reports=reports, product=a.product,
|
|
191
|
+
product_version=a.product_version, report_date=a.report_date,
|
|
192
|
+
description=a.description,
|
|
193
|
+
author=json.loads(a.author) if a.author else None,
|
|
194
|
+
contact=a.contact, methods=a.methods, notes=a.notes,
|
|
195
|
+
overrides=json.loads(a.overrides) if a.overrides else None,
|
|
196
|
+
lang=a.lang, output_path=a.out)
|
|
197
|
+
if 'error' in res:
|
|
198
|
+
print(res['error'])
|
|
199
|
+
return 1
|
|
200
|
+
print(json.dumps({'summary': res['summary'], 'pack_sha256': res['pack_sha256'],
|
|
201
|
+
'format': res['format'], 'saved_to': res.get('saved_to'),
|
|
202
|
+
'draft': res['draft']}, ensure_ascii=False))
|
|
203
|
+
return 0
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
if __name__ == '__main__':
|
|
207
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""PDF accessibility screening — the space nobody automated.
|
|
3
|
+
|
|
4
|
+
axe-core, pa11y, Lighthouse: HTML only. PDFs carry half the enterprise
|
|
5
|
+
documents and nobody screens them in CI. This module does the zero-dep
|
|
6
|
+
first pass: the structural facts that decide whether a PDF is even
|
|
7
|
+
*addressable* by assistive technology (tagged tree, title, language,
|
|
8
|
+
outline), plus markers of remediation (Alt entries, ActualText).
|
|
9
|
+
|
|
10
|
+
Honest limits, stated in every report: full PDF/UA-1 and PDF/UA-2
|
|
11
|
+
conformance needs a spec validator (veraPDF is the open-source one);
|
|
12
|
+
this screening finds the failures that make full validation pointless.
|
|
13
|
+
|
|
14
|
+
CLI:
|
|
15
|
+
a11ypdf.py documento.pdf [--lang en]
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import zlib
|
|
24
|
+
from . import a11yi18n
|
|
25
|
+
|
|
26
|
+
T = a11yi18n.pair('pdf') # locales/<lang>.json — community-editable
|
|
27
|
+
|
|
28
|
+
_CRIT = {
|
|
29
|
+
'pdf_untagged': ('1.3.1', 'high'), 'pdf_no_title': ('2.4.2', 'low'),
|
|
30
|
+
'pdf_no_lang': ('3.1.1', 'medium'), 'pdf_no_outline': ('1.3.1', 'low'),
|
|
31
|
+
'pdf_no_alt': ('1.1.1', 'high'), 'pdf_encrypted': ('1.1.1', 'medium'),
|
|
32
|
+
'pdf_scanned': ('1.1.1', 'high'),
|
|
33
|
+
'pdf_form_no_label': ('3.3.2', 'medium'), 'pdf_button_no_name': ('4.1.2', 'high'),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _t(lang, key):
|
|
38
|
+
return T.get(lang, T['en'])[key]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _uncompressed_streams(data, limit=60):
|
|
42
|
+
"""Los streams FlateDecode, descomprimidos (zlib es stdlib) — ahí viven
|
|
43
|
+
el XMP, el contenido y buena parte de la estructura."""
|
|
44
|
+
out = []
|
|
45
|
+
for m in re.finditer(rb'stream\r?\n', data):
|
|
46
|
+
start = m.end()
|
|
47
|
+
end = data.find(b'endstream', start)
|
|
48
|
+
if end == -1:
|
|
49
|
+
continue
|
|
50
|
+
chunk = data[start:end].rstrip(b'\r\n')
|
|
51
|
+
try:
|
|
52
|
+
d = zlib.decompressobj()
|
|
53
|
+
out.append(d.decompress(chunk, 20_000_000)) # bomba: techo por stream
|
|
54
|
+
except Exception: # noqa: BLE001
|
|
55
|
+
continue
|
|
56
|
+
if len(out) >= limit:
|
|
57
|
+
break
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def pdf_screen(path_or_bytes, lang='en'):
|
|
62
|
+
"""Cribado estructural de accesibilidad de un PDF (fichero local)."""
|
|
63
|
+
if isinstance(path_or_bytes, (bytes, bytearray)):
|
|
64
|
+
data = bytes(path_or_bytes)
|
|
65
|
+
name = '(bytes)'
|
|
66
|
+
truncated = False
|
|
67
|
+
else:
|
|
68
|
+
tam = os.path.getsize(path_or_bytes)
|
|
69
|
+
with open(path_or_bytes, 'rb') as f:
|
|
70
|
+
data = f.read(30_000_000) # techo duro: 30 MB
|
|
71
|
+
truncated = tam > len(data)
|
|
72
|
+
name = str(path_or_bytes).rsplit('/', 1)[-1]
|
|
73
|
+
|
|
74
|
+
if not data.startswith(b'%PDF-'):
|
|
75
|
+
return {'error': 'not a PDF (no %PDF- marker)'}
|
|
76
|
+
|
|
77
|
+
streams = _uncompressed_streams(data)
|
|
78
|
+
todo = data + b'\n'.join(streams[:40])
|
|
79
|
+
|
|
80
|
+
def present(pat):
|
|
81
|
+
return re.search(pat, todo) is not None
|
|
82
|
+
|
|
83
|
+
encrypted = b'/Encrypt' in data # el trailer vive al FINAL del fichero
|
|
84
|
+
tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or present(rb'/StructTreeRoot')
|
|
85
|
+
marked = present(rb'/Marked\s+true')
|
|
86
|
+
lang_doc = re.search(rb'/Lang\s*\(([^)]{2,20})\)', todo)
|
|
87
|
+
title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', todo) or \
|
|
88
|
+
re.search(rb'<dc:title>.{0,200}?<rdf:li[^>]*>([^<]{1,300})</rdf:li>', todo, re.S)
|
|
89
|
+
n_pages = len(re.findall(rb'/Type\s*/Page[^s]', todo))
|
|
90
|
+
n_alt = len(re.findall(rb'/Alt\s*\(', todo))
|
|
91
|
+
n_actual = len(re.findall(rb'/ActualText', todo))
|
|
92
|
+
n_imgs = len(re.findall(rb'/Subtype\s*/Image', todo))
|
|
93
|
+
n_outline = len(re.findall(rb'/Outlines\s+\d+\s+0\s+R', todo))
|
|
94
|
+
# capa de texto: operadores Tj/TJ en TODA la muestra — streams Flate
|
|
95
|
+
# descomprimidos Y bytes crudos (contenido sin comprimir es legítimo;
|
|
96
|
+
# contar solo Flate acusaba en falso de 'escaneo' a PDFs reales)
|
|
97
|
+
n_text = sum(len(re.findall(rb'\)\s*Tj|\]\s*TJ|\(\s*[A-Za-z0-9]', f)) for f in streams)
|
|
98
|
+
n_text += len(re.findall(rb'\)\s*Tj|\]\s*TJ', data))
|
|
99
|
+
|
|
100
|
+
findings = []
|
|
101
|
+
|
|
102
|
+
# ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
|
|
103
|
+
# Parseo de la secuencia: `rg` cambia el color de relleno de texto,
|
|
104
|
+
# `re` + `f` pinta un rectángulo (fondo), `Tj`/`TJ` escriben texto.
|
|
105
|
+
# El fondo por defecto del PDF es blanco si nadie lo pinta. Si un rect
|
|
106
|
+
# oscuro precede al texto, el fondo efectivo es ese fill — no acusar
|
|
107
|
+
# blanco-sobre-oscuro como bajo (el mismo bug que CSS var() en HTML).
|
|
108
|
+
def _l(r, g, b):
|
|
109
|
+
def lin(v):
|
|
110
|
+
v /= 255.0
|
|
111
|
+
return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
|
|
112
|
+
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
|
|
113
|
+
|
|
114
|
+
def _ratio(f, b):
|
|
115
|
+
l1, l2 = max(f, b), min(f, b)
|
|
116
|
+
return (l1 + 0.05) / (l2 + 0.05)
|
|
117
|
+
|
|
118
|
+
blanc = _l(255, 255, 255)
|
|
119
|
+
low_hits = []
|
|
120
|
+
for stream in streams:
|
|
121
|
+
text = stream.decode('latin-1', 'replace')
|
|
122
|
+
text_color = (0, 0, 0)
|
|
123
|
+
bg_color = (255, 255, 255) # el PDF no pinta fondo por defecto
|
|
124
|
+
painted_bg = False
|
|
125
|
+
for m in re.finditer(
|
|
126
|
+
r'([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+(rg|re)\b'
|
|
127
|
+
r'|\b(f)\b'
|
|
128
|
+
r'|\((?:[^()\\]|\\.)*\)\s*(Tj|TJ)'
|
|
129
|
+
, text):
|
|
130
|
+
op = m.group(4) or m.group(5) or m.group(6)
|
|
131
|
+
if op in ('rg', 're'):
|
|
132
|
+
try:
|
|
133
|
+
text_color = tuple(
|
|
134
|
+
max(0, min(255, round(float(x) * 255)))
|
|
135
|
+
for x in m.groups()[:3])
|
|
136
|
+
except ValueError:
|
|
137
|
+
pass
|
|
138
|
+
if op == 're':
|
|
139
|
+
# el rect se pinta con el fill actual: es el FONDO
|
|
140
|
+
bg_color = text_color
|
|
141
|
+
elif op == 'f':
|
|
142
|
+
pass # el f pinta con el fill ya establecido (fondo ya guardado)
|
|
143
|
+
else: # Tj / TJ
|
|
144
|
+
lt = _l(*text_color)
|
|
145
|
+
lb = _l(*bg_color)
|
|
146
|
+
ratio = _ratio(lt, lb)
|
|
147
|
+
if ratio < 4.5:
|
|
148
|
+
ej = (f'rgb({text_color[0]},{text_color[1]},{text_color[2]})'
|
|
149
|
+
f' sobre rgb({bg_color[0]},{bg_color[1]},{bg_color[2]})'
|
|
150
|
+
f' \u2192 {ratio:.2f}:1')
|
|
151
|
+
if ej not in [x.split(' \u2014 ')[0] for x in low_hits]:
|
|
152
|
+
low_hits.append(ej)
|
|
153
|
+
if len(low_hits) >= 4:
|
|
154
|
+
break
|
|
155
|
+
if low_hits:
|
|
156
|
+
findings.append({
|
|
157
|
+
'severity': 'medium', 'criterion': '1.4.3 (PDF)',
|
|
158
|
+
'signal': 'pdf_low_contrast',
|
|
159
|
+
'issue': _t(lang, 'pdf_low_contrast').format(n=len(low_hits), example='; '.join(low_hits[:3])),
|
|
160
|
+
'remediation': _t(lang, 'pdf_low_contrast_rem')})
|
|
161
|
+
|
|
162
|
+
# ── 2.4.4 en PDF: falso affordance de enlace ──
|
|
163
|
+
# texto azulado sin /Annot URI en la misma página
|
|
164
|
+
bluish, n_uri = [], len(re.findall(rb'/S\s*/URI', data))
|
|
165
|
+
for stream in streams:
|
|
166
|
+
text = stream.decode('latin-1', 'replace')
|
|
167
|
+
for m in re.finditer(
|
|
168
|
+
r'0\s+0\s+1\s+rg\s*(?:\n|.)*?\(([^)]{4,80})\)\s*Tj', text):
|
|
169
|
+
bluish.append(m.group(1)[:40])
|
|
170
|
+
if len(bluish) >= 3:
|
|
171
|
+
break
|
|
172
|
+
if len(bluish) >= 3:
|
|
173
|
+
break
|
|
174
|
+
if bluish and n_uri == 0:
|
|
175
|
+
findings.append({
|
|
176
|
+
'severity': 'medium', 'criterion': '2.4.4 (PDF)',
|
|
177
|
+
'signal': 'pdf_fake_link',
|
|
178
|
+
'issue': _t(lang, 'pdf_fake_link').format(n=len(bluish)),
|
|
179
|
+
'remediation': _t(lang, 'pdf_fake_link_rem'),
|
|
180
|
+
'examples': bluish})
|
|
181
|
+
|
|
182
|
+
# ── 3.3.2 / 4.1.2 en PDF: campos AcroForm sin etiqueta accesible ──
|
|
183
|
+
# /FT declara el tipo de campo (/Tx texto, /Ch lista, /Sig firma, /Btn
|
|
184
|
+
# botón); /TU es el texto alternativo — LO que anuncia el lector de
|
|
185
|
+
# pantalla. Sin /TU, el campo se oye con su nombre técnico o como
|
|
186
|
+
# "button" a secas. Caso claro (ningún /TU): acusa por tipo. Caso
|
|
187
|
+
# parcial: recuento único sin desglosar botones (la herencia /Parent
|
|
188
|
+
# de los grupos de radio hace impredecible el emparejamiento campo a
|
|
189
|
+
# campo en un cribado sin parser de objetos).
|
|
190
|
+
n_fields_txt = len(re.findall(rb'/FT\s*/(?:Tx|Ch|Sig)\b', todo))
|
|
191
|
+
n_fields_btn = len(re.findall(rb'/FT\s*/Btn\b', todo))
|
|
192
|
+
n_tu = len(re.findall(rb'/TU\s*[<(]', todo))
|
|
193
|
+
n_fields = n_fields_txt + n_fields_btn
|
|
194
|
+
if n_fields and n_tu == 0:
|
|
195
|
+
if n_fields_txt:
|
|
196
|
+
findings.append({
|
|
197
|
+
'severity': 'medium', 'criterion': '3.3.2 (PDF)',
|
|
198
|
+
'signal': 'pdf_form_no_label',
|
|
199
|
+
'issue': _t(lang, 'pdf_form_no_label').format(n=n_fields_txt, m=n_fields_txt),
|
|
200
|
+
'remediation': _t(lang, 'pdf_form_no_label_rem')})
|
|
201
|
+
if n_fields_btn:
|
|
202
|
+
findings.append({
|
|
203
|
+
'severity': 'high', 'criterion': '4.1.2 (PDF)',
|
|
204
|
+
'signal': 'pdf_button_no_name',
|
|
205
|
+
'issue': _t(lang, 'pdf_button_no_name').format(n=n_fields_btn),
|
|
206
|
+
'remediation': _t(lang, 'pdf_button_no_name_rem')})
|
|
207
|
+
elif n_tu < n_fields:
|
|
208
|
+
findings.append({
|
|
209
|
+
'severity': 'medium', 'criterion': '3.3.2 (PDF)',
|
|
210
|
+
'signal': 'pdf_form_no_label',
|
|
211
|
+
'issue': _t(lang, 'pdf_form_no_label').format(n=n_fields - n_tu, m=n_fields),
|
|
212
|
+
'remediation': _t(lang, 'pdf_form_no_label_rem')})
|
|
213
|
+
|
|
214
|
+
def add(key):
|
|
215
|
+
crit, sev = _CRIT[key]
|
|
216
|
+
findings.append({'severity': sev, 'criterion': f'{crit} (PDF)',
|
|
217
|
+
'signal': key, 'issue': _t(lang, key),
|
|
218
|
+
'remediation': _t(lang, key + '_rem')})
|
|
219
|
+
|
|
220
|
+
# detecciones de contenido: contraste y falso enlace (necesitan hallazgos)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
if encrypted:
|
|
224
|
+
add('pdf_encrypted')
|
|
225
|
+
if not (tagged and marked):
|
|
226
|
+
add('pdf_untagged')
|
|
227
|
+
if not title_meta:
|
|
228
|
+
add('pdf_no_title')
|
|
229
|
+
if not lang_doc:
|
|
230
|
+
add('pdf_no_lang')
|
|
231
|
+
if n_pages > 8 and not n_outline:
|
|
232
|
+
add('pdf_no_outline')
|
|
233
|
+
if n_text == 0 and n_imgs > 0 and n_pages > 0:
|
|
234
|
+
# sin texto Y con imágenes: patrón de escaneo. Sin imágenes no hay
|
|
235
|
+
# base para acusar (vector puro, formularios vacíos…)
|
|
236
|
+
add('pdf_scanned')
|
|
237
|
+
elif tagged and n_imgs > 0 and n_alt == 0 and n_actual == 0:
|
|
238
|
+
add('pdf_no_alt')
|
|
239
|
+
|
|
240
|
+
from .a11yaudit import compute_score
|
|
241
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
242
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
243
|
+
return {
|
|
244
|
+
'mode': 'pdf', 'file': name,
|
|
245
|
+
'pages': n_pages or None,
|
|
246
|
+
'tagged': bool(tagged and marked),
|
|
247
|
+
'encrypted': encrypted,
|
|
248
|
+
'lang': lang_doc.group(1).decode('latin-1', 'replace') if lang_doc else None,
|
|
249
|
+
'title': (title_meta.group(1).decode('utf-8', 'replace').strip()[:200]
|
|
250
|
+
if title_meta else None),
|
|
251
|
+
'images': n_imgs, 'alt_entries': n_alt, 'actual_text': n_actual,
|
|
252
|
+
'text_operators': n_text,
|
|
253
|
+
'form_fields': n_fields, 'form_labels': n_tu,
|
|
254
|
+
'truncated': truncated,
|
|
255
|
+
'score': compute_score(findings),
|
|
256
|
+
'findings': findings,
|
|
257
|
+
'summary': {s: sum(1 for h in findings if h['severity'] == s)
|
|
258
|
+
for s in ('high', 'medium', 'low')},
|
|
259
|
+
'limits': _t(lang, 'limits'),
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def main(argv):
|
|
264
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
265
|
+
ap.add_argument('pdf', help='local PDF file')
|
|
266
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
267
|
+
a = ap.parse_args(argv)
|
|
268
|
+
print(json.dumps(pdf_screen(a.pdf, lang=a.lang), ensure_ascii=False, indent=1))
|
|
269
|
+
return 0
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
if __name__ == '__main__':
|
|
273
|
+
sys.exit(main(sys.argv[1:]))
|