@kinti/a11y-toolkit 5.31.0 → 5.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -886,7 +886,7 @@ MODES_BY_CRITERION = {
886
886
  '2.4.7': ('rendered', 'journey'),
887
887
  '2.4.11': ('rendered',),
888
888
  '2.5.8': ('rendered',),
889
- '3.2.1': ('keyboard',),
889
+ '3.2.1': ('keyboard', 'site', 'static'),
890
890
  '3.2.2': ('keyboard',),
891
891
  '3.3.1': ('forms', 'journey'),
892
892
  '3.3.3': ('forms', 'journey'),
@@ -982,6 +982,24 @@ _SIGNAL_CRIT = {
982
982
  'autocomplete_mismatch': '1.3.5',
983
983
  'heading_role_removed': '1.3.1',
984
984
  'text_spacing_important': '1.4.12',
985
+ 'a_no_href': '2.1.1',
986
+ 'nested_main': '1.3.1',
987
+ 'fake_list': '1.3.1',
988
+ 'alert_polite': '4.1.2',
989
+ 'headers_attr_bad': '1.3.1',
990
+ 'lang_xml_mismatch': '3.1.2',
991
+ 'nested_interactive': '4.1.2',
992
+ 'invoker_command_bad': '4.1.2',
993
+ 'aria_level_gt6': '1.3.1',
994
+ 'select_auto_focus': '3.2.1',
995
+ 'role_orphan': '1.3.1',
996
+ 'skip_broken': '2.4.1',
997
+ 'docx_fake_list': '1.3.1',
998
+ 'docx_heading_skips': '1.3.1',
999
+ 'docx_generic_link': '2.4.4',
1000
+ 'pdf_table_no_header': '1.3.1',
1001
+ 'pdf_no_heading_tags': '1.3.1',
1002
+ 'pdfua_contradiction': '1.3.1',
985
1003
  'label_in_name': '2.5.3',
986
1004
  'label_orphan': '3.3.2',
987
1005
  'label_vague': '2.4.6',
@@ -32,13 +32,47 @@ _MAX_MEMBER_BYTES = 40 * 1024 * 1024
32
32
  _CRIT = {
33
33
  'docx_no_alt': ('1.1.1', 'high'), 'docx_fake_headings': ('1.3.1', 'medium'),
34
34
  'docx_no_lang': ('3.1.1', 'medium'), 'docx_table_no_header': ('1.3.1', 'low'),
35
+ 'docx_fake_list': ('1.3.1', 'medium'), 'docx_heading_skips': ('1.3.1', 'low'),
36
+ 'docx_generic_link': ('2.4.4', 'medium'),
35
37
  }
36
38
 
39
+ # texto genérico de enlace (2.4.4): la misma familia del HTML, en la voz de
40
+ # los documentos (es/en); cuenta como genérico SOLO repetido (2+), un
41
+ # «descargar» solitario puede ser específico en contexto
42
+ _GENERIC_LINK = {
43
+ 'aquí', 'aquí.', 'pincha aquí', 'pulsa aquí', 'haz clic aquí', 'click here',
44
+ 'here', 'read more', 'leer más', 'más', 'ver más', 'more', 'download',
45
+ 'descargar', 'este enlace', 'this link', 'enlace', 'link', 'detalles',
46
+ 'details', 'más información', 'more information',
47
+ }
48
+ _BULLET = '•●▪◦‣·'
49
+
37
50
 
38
51
  def _t(lang, key):
39
52
  return T.get(lang, T['en'])[key]
40
53
 
41
54
 
55
+ class _OverCap(Exception):
56
+ """Un miembro del ZIP declara más bytes de los que la ingesta admite."""
57
+
58
+
59
+ def _capped_read(z, member):
60
+ """Texto de un miembro del ZIP (None si no existe). El techo de
61
+ descompresión por miembro vive AQUÍ, en la única puerta de lectura del
62
+ cribado: file_size es el declarado del directorio central, el estándar
63
+ contra bombas ZIP de los descompresores serios. Toda lectura pasa por
64
+ esta función (document.xml y styles.xml lo hacían por una comprobación
65
+ previa; la de document.xml.rels la eludía)."""
66
+ try:
67
+ info = z.getinfo(member)
68
+ except KeyError:
69
+ return None
70
+ if info.file_size > _MAX_MEMBER_BYTES:
71
+ raise _OverCap(f'{member} declares {info.file_size} bytes '
72
+ f'(>{_MAX_MEMBER_BYTES}): over the intake cap')
73
+ return z.read(member).decode('utf-8', errors='replace')
74
+
75
+
42
76
  def docx_screen(path, lang='en'):
43
77
  """Cribado de accesibilidad de un .docx (solo stdlib: zipfile + regex XML)."""
44
78
  try:
@@ -47,20 +81,15 @@ def docx_screen(path, lang='en'):
47
81
  return {'error': f'no es un .docx legible: {e}'}
48
82
  if 'word/document.xml' not in z.namelist():
49
83
  return {'error': 'ZIP without word/document.xml (is this really a .docx?)'}
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)}
50
89
 
51
- # techo de descompresión por miembro (revisión externa 2026-11-22): la
52
- # ingesta de contenido NO confiable no puede descomprimir sin límite —
53
- # file_size es el declarado del directorio central, el estándar contra
54
- # bombas ZIP de los descompresores serios
55
- for member in ('word/document.xml', 'word/styles.xml'):
56
- try:
57
- if z.getinfo(member).file_size > _MAX_MEMBER_BYTES:
58
- return {'error': f'{member} declares {z.getinfo(member).file_size} bytes '
59
- f'(>{_MAX_MEMBER_BYTES}): over the intake cap'}
60
- except KeyError:
61
- pass
62
90
 
63
- body = z.read('word/document.xml').decode('utf-8', errors='replace')
91
+ def _screen_zip(z, lang, path):
92
+ body = _capped_read(z, 'word/document.xml')
64
93
 
65
94
  findings = []
66
95
 
@@ -83,12 +112,10 @@ def docx_screen(path, lang='en'):
83
112
 
84
113
  # idioma: w:lang en styles.xml (default del documento)
85
114
  language = None
86
- try:
87
- styles = z.read('word/styles.xml').decode('utf-8', errors='replace')
115
+ styles = _capped_read(z, 'word/styles.xml')
116
+ if styles is not None:
88
117
  m = re.search(r'<w:lang[^>]*w:val="([^"]+)"', styles)
89
118
  language = m.group(1) if m else None
90
- except KeyError:
91
- pass
92
119
  if not language:
93
120
  add('docx_no_lang')
94
121
 
@@ -126,6 +153,113 @@ def docx_screen(path, lang='en'):
126
153
  'issue': _t(lang, 'docx_fake_headings').format(n=fake),
127
154
  'remediation': _t(lang, 'docx_fake_headings_rem')})
128
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:
168
+ fake_list_groups += 1
169
+ elif len(_run) >= 3:
170
+ nums = [t[1] for t in _run if t[0] == 'n']
171
+ if len(nums) == len(_run):
172
+ ok = all(nums[i+1] == nums[i] + 1 for i in range(len(nums)-1))
173
+ if ok and nums[0] in (0, 1):
174
+ fake_list_groups += 1
175
+ _run = []
176
+ for p in _doc_paragraphs:
177
+ if '<w:numPr' in p:
178
+ _flush(); continue
179
+ t = _ptext(p)
180
+ if not t:
181
+ _flush(); continue
182
+ if t[0] in _BULLET:
183
+ _run.append(('b', None)); continue
184
+ m = re.match(r'^(\d{1,3})[.)]\s+\S', t)
185
+ if m:
186
+ _run.append(('n', int(m.group(1)))); continue
187
+ _flush()
188
+ _flush()
189
+ if fake_list_groups:
190
+ findings.append({'severity': 'medium', 'criterion': '1.3.1 (DOCX)',
191
+ 'signal': 'docx_fake_list',
192
+ 'issue': _t(lang, 'docx_fake_list').format(n=fake_list_groups),
193
+ 'remediation': _t(lang, 'docx_fake_list_rem')})
194
+
195
+ # ── saltos de nivel de encabezado: Heading1 → Heading3 aplana la
196
+ # navegación. Niveles por pStyle directo (HeadingN) O por styles.xml
197
+ # (los Word localizados escriben styleIds numéricos cuyo NOMBRE es
198
+ # «heading N» / «Encabezado N» / «Título N»)
199
+ _style_heads = {}
200
+ sx = _capped_read(z, 'word/styles.xml') or ''
201
+ for m in re.finditer(
202
+ r'<w:style [^>]*w:styleId="([^"]+)"[^>]*>.*?'
203
+ r'<w:name w:val="([^"]*)"', sx, re.S):
204
+ mn = re.match(r'(?i)^(?:heading|encabezado|t[ií]tulo|'
205
+ r'berschrift|titre)\s*([1-9])$', m.group(2).strip())
206
+ if mn:
207
+ _style_heads[m.group(1)] = int(mn.group(1))
208
+ levels = []
209
+ for p in _doc_paragraphs:
210
+ ms = re.search(r'<w:pStyle w:val="([^"]+)"', p)
211
+ if not ms:
212
+ continue
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')})
262
+
129
263
  order = {'high': 0, 'medium': 1, 'low': 2}
130
264
  findings.sort(key=lambda h: order[h['severity']])
131
265
 
@@ -137,6 +271,7 @@ def docx_screen(path, lang='en'):
137
271
  'mode': 'docx', 'file': str(path).rsplit('/', 1)[-1],
138
272
  'language': language, 'images': len(docprs),
139
273
  'tables': n_tables, 'tables_without_header': tables_missing,
274
+ 'heading_levels': levels,
140
275
  'score': compute_score(findings),
141
276
  'findings': findings,
142
277
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
@@ -101,7 +101,17 @@ def _detect_browser(pw, preferred=None):
101
101
  def _get_browser(headless=True, preferred=None):
102
102
  """Devuelve un browser del pool (o crea uno si no existe). El driver de
103
103
  Playwright lo arranca y posee el PROPIO pool: el browser devuelto vive
104
- mientras viva el pool, no la sesión de quien lo pidió."""
104
+ mientras viva el pool, no la sesión de quien lo pidió.
105
+
106
+ A11Y_BROWSER_POOL=0 desactiva el pool (ciclo por llamada, el modelo
107
+ pre-pool): el pool deja un event loop CORRIENDO en el hilo que lo crea —
108
+ incompatible con hosts que mezclan su propio Playwright síncrono o varios
109
+ hilos en el mismo proceso (FastAPI threadpool, suites de test con
110
+ fixtures de navegador propias). El proceso MCP es single-thread y
111
+ exclusivo: ahí el pool amortiza de verdad."""
112
+ import os as _os
113
+ if _os.environ.get('A11Y_BROWSER_POOL', '1') == '0':
114
+ return _NoPoolBrowser(headless, preferred)
105
115
  if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
106
116
  (preferred in (None, 'auto') or _POOL['type'] == preferred):
107
117
  return _POOL['browser']
@@ -137,11 +147,42 @@ def _close_pool():
137
147
  atexit.register(_close_pool)
138
148
 
139
149
 
150
+ class _NoPoolBrowser:
151
+ """Ciclo por llamada (A11Y_BROWSER_POOL=0): crea SU playwright+browser y
152
+ los cierra cuando la última página prestada se cierra — la forma pre-pool
153
+ de vivir, para hosts multihilo que no pueden compartir loop."""
154
+
155
+ def __init__(self, headless, preferred):
156
+ from playwright.sync_api import sync_playwright
157
+ self._pw = sync_playwright().start()
158
+ self._nav, kind = _detect_browser(self._pw, preferred)
159
+ self._live_pages = 0
160
+
161
+ def new_context(self, **kw):
162
+ return self._nav.new_context(**kw)
163
+
164
+ def new_page(self, **kw):
165
+ self._live_pages += 1
166
+ return self._nav.new_page(**kw)
167
+
168
+ def is_connected(self):
169
+ return self._nav.is_connected()
170
+
171
+ def close(self):
172
+ try:
173
+ self._nav.close()
174
+ finally:
175
+ self._pw.stop()
176
+
177
+
140
178
  def _pooled_page(nav, auth_state=None, **kw):
141
179
  """(page, close_page) sobre el navegador del pool: con auth_state abre un
142
180
  contexto propio (storage_state) cuyo cierre se lleva también la página;
143
181
  sin él, página directa. close_page traga errores — el navegador del pool
144
- queda caliente para la siguiente llamada, JAMÁS se cierra aquí."""
182
+ queda caliente para la siguiente llamada, JAMÁS se cierra aquí.
183
+ Con A11Y_BROWSER_POOL=0 (nav._NoPoolBrowser), el cierre de la página
184
+ se lleva TAMBIÉN su navegador: el ciclo vive exactamente una llamada."""
185
+ _no_pool = isinstance(nav, _NoPoolBrowser)
145
186
  if auth_state:
146
187
  ctx = nav.new_context(storage_state=auth_state, **kw)
147
188
  page = ctx.new_page()
@@ -151,6 +192,8 @@ def _pooled_page(nav, auth_state=None, **kw):
151
192
  ctx.close()
152
193
  except Exception: # noqa: BLE001
153
194
  pass
195
+ if _no_pool:
196
+ nav.close()
154
197
  return page, close_page
155
198
 
156
199
  page = nav.new_page(**kw)
@@ -160,6 +203,8 @@ def _pooled_page(nav, auth_state=None, **kw):
160
203
  page.close()
161
204
  except Exception: # noqa: BLE001
162
205
  pass
206
+ if _no_pool:
207
+ nav.close()
163
208
  return page, close_page
164
209
 
165
210
  MAX_EXAMPLES = 6
@@ -672,7 +717,8 @@ _JS = r'''(maxEj) => {
672
717
  }
673
718
  }
674
719
  for (const el of deepQ('a[target="_blank"]')) {
675
- const t = (el.innerText || '') + ' ' + (el.getAttribute('aria-label') || '') + ' ' + (el.getAttribute('title') || '');
720
+ // title NO cuenta: hover-only, invisible para quien navega con teclado
721
+ const t = (el.innerText || '') + ' ' + (el.getAttribute('aria-label') || '');
676
722
  if (!/(nueva|nuevo|ventana|pesta|tab\b|window|external|externo|exterior)/i.test(t)) out.blank++;
677
723
  }
678
724
  for (const el of deepQ('video')) {
@@ -816,9 +862,9 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
816
862
  _add(findings, lang, 'low', '1.4.3', 'contrast_review', n=remaining)
817
863
 
818
864
  # 1b. Contraste del placeholder (::placeholder): el gris típico sobre
819
- # blanco falla 1.4.3 y el AT lo lee como texto real (Léonie Watson,
820
- # estado del sector 2026). Severidad de contrast_fail (medium: la misma
821
- # clase de texto que falla, no grave como un bloqueo de uso).
865
+ # blanco falla 1.4.3 y el AT lo lee como texto real. Severidad de
866
+ # contrast_fail (medium: la misma clase de texto que falla, no grave
867
+ # como un bloqueo de uso).
822
868
  ph_failures = data.get('placeholderContrast') or []
823
869
  if ph_failures:
824
870
  det = '; '.join(
@@ -98,10 +98,10 @@ def _index(p):
98
98
  for i in (a.get('aria-labelledby') or '').split()).strip()
99
99
  return lb, (a.get('aria-label') or '').strip(), (a.get('title') or '').strip()
100
100
 
101
- def _add(a, role, name, match_extra=None, route=None):
101
+ def _add(a, role, name, match_extra=None):
102
102
  if not name or id(a) in seen:
103
103
  return
104
- path = route or p._elem_paths.get(id(a))
104
+ path = p.element_path(a)
105
105
  if not path:
106
106
  return
107
107
  seen.add(id(a))
@@ -130,11 +130,11 @@ def _index(p):
130
130
  or ' '.join(x for x in img_names if x).strip()
131
131
  or (a.get('alt') or '').strip() or ti)
132
132
 
133
- for level, a, text, hidden, route in p.headings_raw:
133
+ for level, a, text, hidden in p.headings_raw:
134
134
  if hidden:
135
135
  continue
136
136
  lb, al, _ti = _name_sources(a)
137
- _add(a, f'h{level}', lb or al or text.strip(), route=route)
137
+ _add(a, f'h{level}', lb or al or text.strip())
138
138
 
139
139
  for a, hidden in p.imgs_all:
140
140
  if hidden:
@@ -227,7 +227,7 @@ def pdf_screen(path_or_bytes, lang='en'):
227
227
  _info_refs = re.findall(rb'/Info\s+(\d+)\s+\d+\s+R', todo)
228
228
  if _info_refs:
229
229
  _obj_id = _info_refs[-1] # actualizaciones incrementales: el último manda
230
- _m_obj = re.search(b'\b' + _obj_id + b'\s+\d+\s+obj(.{0,4000}?)endobj', todo, re.S)
230
+ _m_obj = re.search(rb'\b' + _obj_id + rb'\s+\d+\s+obj(.{0,4000}?)endobj', todo, re.S)
231
231
  if _m_obj:
232
232
  title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', _m_obj.group(1))
233
233
  if not title_meta:
@@ -243,6 +243,17 @@ def pdf_screen(path_or_bytes, lang='en'):
243
243
  title_meta = _m
244
244
  break
245
245
  n_pages = len(re.findall(rb'/Type\s*/Page[^s]', todo))
246
+ # estructura del árbol de tags (solo si tagged): TD sin TH = tablas planas;
247
+ # cero H1-H6 = documento etiquetado SIN jerarquía navegable
248
+ n_tag_td = len(re.findall(rb'/S\s*/TD\b', todo))
249
+ n_tag_th = len(re.findall(rb'/S\s*/TH\b', todo))
250
+ n_tag_h = len(re.findall(rb'/S\s*/H[1-6]\b', todo))
251
+ # la declaración PDF/UA del XMP viaja de dos formas: como atributo
252
+ # (pdfuaid:part="2", la única que se leía) y como elemento RDF
253
+ # (<pdfuaid:part>2</pdfuaid:part>, que es como XMP serializa una propiedad)
254
+ _m_ua = re.search(rb'pdfuaid:part\s*=\s*["\x27]?\s*(\d+)', todo) \
255
+ or re.search(rb'<pdfuaid:part(?:\s[^>]*)?>\s*(\d+)\s*</pdfuaid:part>', todo)
256
+ pdfua_part = int(_m_ua.group(1)) if _m_ua else None
246
257
  # /Alt acepta literal (/Alt (…)) y hex (/Alt <FEFF…>, la forma natural
247
258
  # UTF-16BE para alt no latino) — misma paridad que /TU
248
259
  n_alt = len(re.findall(rb'/Alt\s*[<(]', todo))
@@ -254,10 +265,30 @@ def pdf_screen(path_or_bytes, lang='en'):
254
265
  # contar solo Flate acusaba en falso de 'escaneo' a PDFs reales)
255
266
  n_text = sum(len(re.findall(rb'\)\s*Tj|\]\s*TJ|\(\s*[A-Za-z0-9]', f)) for f in streams)
256
267
  n_text += len(re.findall(rb'\)\s*Tj|\]\s*TJ', data))
268
+ # modo de render del texto: el operador `N Tr` fija el modo; 3 = invisible
269
+ # (capa OCR de un escaneo o fuentes invisibles). Si TODO el texto va en
270
+ # modo 3, lo visible es imagen y la capa 'de texto' no se pinta: dato de
271
+ # informe para la revisión (¿el escaneo tiene etiquetado/alt?), no fallo.
272
+ _mode, _t_vis, _t_inv = 0, 0, 0
273
+ _RE_TROPS = re.compile(rb'(?P<tr>[\d.]+)\s+Tr\b|(?P<show>Tj|TJ)\b')
274
+ for _blob in list(streams) + [data]:
275
+ for _m in _RE_TROPS.finditer(_blob):
276
+ if _m.group('tr') is not None:
277
+ try:
278
+ _mode = int(float(_m.group('tr')))
279
+ except ValueError:
280
+ pass
281
+ elif _m.group('show'):
282
+ if _mode == 3:
283
+ _t_inv += 1
284
+ else:
285
+ _t_vis += 1
257
286
 
258
287
  findings = []
259
288
 
260
- # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
289
+ # capa OCR pura (todo el texto en modo 3): el dato viaja en el informe; la
290
+ # nota solo al final si procede (tras el conteo real de streams)
291
+
261
292
  low_hits = []
262
293
  for stream in streams:
263
294
  for ej in _stream_low_contrast(stream.decode('latin-1', 'replace')):
@@ -292,6 +323,36 @@ def pdf_screen(path_or_bytes, lang='en'):
292
323
  'remediation': _t(lang, 'pdf_fake_link_rem'),
293
324
  'examples': bluish})
294
325
 
326
+ # ── 1.3.1 en PDF: etiquetado plano (tablas sin TH, sin H1-H6) ──
327
+ _tagged_ok = bool(tagged and marked)
328
+ if _tagged_ok and n_tag_td and not n_tag_th:
329
+ findings.append({
330
+ 'severity': 'medium', 'criterion': '1.3.1 (PDF)',
331
+ 'signal': 'pdf_table_no_header',
332
+ 'issue': _t(lang, 'pdf_table_no_header').format(n=n_tag_td),
333
+ 'remediation': _t(lang, 'pdf_table_no_header_rem')})
334
+ if _tagged_ok and (n_pages or 0) >= 3 and not n_tag_h \
335
+ and not re.search(rb'/H[1-6]\b[^>]{0,200}/RoleMap|RoleMap[^>]{0,200}/H[1-6]\b', todo) \
336
+ and not re.search(rb'/FT\s*/(?:Tx|Ch|Btn|Sig)', todo):
337
+ findings.append({
338
+ 'severity': 'low', 'criterion': '1.3.1 (PDF)',
339
+ 'signal': 'pdf_no_heading_tags',
340
+ 'issue': _t(lang, 'pdf_no_heading_tags'),
341
+ 'remediation': _t(lang, 'pdf_no_heading_tags_rem')})
342
+ # ── contradicción PDF/UA: XMP declara pdfuaid:part pero falta idioma,
343
+ # título o etiquetado — el sello miente sobre su propio documento
344
+ if pdfua_part is not None:
345
+ _missing = [k for k, v in (('/Lang', lang_found is None),
346
+ ('/Title', title_meta is None),
347
+ ('StructTree', not _tagged_ok)) if v]
348
+ if _missing:
349
+ findings.append({
350
+ 'severity': 'high', 'criterion': '1.3.1 (PDF)',
351
+ 'signal': 'pdfua_contradiction',
352
+ 'issue': _t(lang, 'pdfua_contradiction').format(
353
+ part=pdfua_part, missing=', '.join(_missing)),
354
+ 'remediation': _t(lang, 'pdfua_contradiction_rem')})
355
+
295
356
  # ── 3.3.2 / 4.1.2 en PDF: campos AcroForm sin etiqueta accesible ──
296
357
  # /FT declara el tipo de campo (/Tx texto, /Ch lista, /Sig firma, /Btn
297
358
  # botón); /TU es el texto alternativo — LO que anuncia el lector de
@@ -353,7 +414,7 @@ def pdf_screen(path_or_bytes, lang='en'):
353
414
  from .a11yaudit import compute_score
354
415
  order = {'high': 0, 'medium': 1, 'low': 2}
355
416
  findings.sort(key=lambda h: order[h['severity']])
356
- return {
417
+ _report = {
357
418
  'mode': 'pdf', 'file': name,
358
419
  'pages': n_pages or None,
359
420
  'tagged': bool(tagged and marked),
@@ -363,6 +424,10 @@ def pdf_screen(path_or_bytes, lang='en'):
363
424
  if title_meta else None),
364
425
  'images': n_imgs, 'alt_entries': n_alt, 'actual_text': n_actual,
365
426
  'text_operators': n_text,
427
+ 'text_render': {'visible_ops': _t_vis, 'invisible_ops': _t_inv},
428
+ 'pdfua_claimed': pdfua_part,
429
+ 'tag_counts': {'td': n_tag_td, 'th': n_tag_th, 'h': n_tag_h},
430
+ 'ocr_layer_only': bool(_t_inv and not _t_vis),
366
431
  'form_fields': n_fields, 'form_labels': n_tu,
367
432
  'truncated': truncated,
368
433
  'score': compute_score(findings),
@@ -371,6 +436,9 @@ def pdf_screen(path_or_bytes, lang='en'):
371
436
  for s in ('high', 'medium', 'low')},
372
437
  'limits': _t(lang, 'limits'),
373
438
  }
439
+ if _report['ocr_layer_only']:
440
+ _report['ocr_layer_note'] = _t(lang, 'pdf_ocr_layer_note')
441
+ return _report
374
442
 
375
443
 
376
444
  def main(argv):