@kinti/a11y-toolkit 5.23.0 → 5.25.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.
@@ -29,6 +29,8 @@
29
29
  a11ytoolkit route --goal "gate my PR" # which tools for the task
30
30
  a11ytoolkit route --file page.html # diagnosis: read the page, order the exams
31
31
  a11ytoolkit mutants --seed 7 --n 12 # the engine's sealed self-exam
32
+ a11ytoolkit corpus build && a11ytoolkit corpus verify # versioned audit corpus (dataset + baselines)
33
+ a11ytoolkit fingerprints page1.html page2.html --dir p/ # twin-page detection (one audit per template)
32
34
  """
33
35
 
34
36
  import sys
@@ -47,6 +49,7 @@ from . import a11ycrit
47
49
  from . import a11ydiff
48
50
  from . import a11ysarif
49
51
  from . import a11ywcagem
52
+ from . import a11ycorpus
50
53
  from . import a11yplan
51
54
  from . import contrast
52
55
  from . import a11ystatement
@@ -60,6 +63,7 @@ from . import a11yinit
60
63
  from . import a11ywcag3
61
64
  from . import a11yroute
62
65
  from . import a11ymutants
66
+ from . import a11yfingerprints
63
67
 
64
68
  SUBCOMMANDS = {
65
69
  'pair': (contrast, 'pair'),
@@ -71,6 +75,7 @@ SUBCOMMANDS = {
71
75
  'criterion': (a11ycrit, None),
72
76
  'sarif': (a11ysarif, None),
73
77
  'wcagem': (a11ywcagem, None),
78
+ 'corpus': (a11ycorpus, None),
74
79
  'plan': (a11yplan, None),
75
80
  'fix': (a11yfix, None),
76
81
  'kbd': (a11ydom, 'kbd_main'),
@@ -95,6 +100,7 @@ SUBCOMMANDS = {
95
100
  'wcag3': (a11ywcag3, None),
96
101
  'route': (a11yroute, None),
97
102
  'mutants': (a11ymutants, None),
103
+ 'fingerprints': (a11yfingerprints, None),
98
104
  }
99
105
 
100
106
 
@@ -0,0 +1,408 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_corpus — the versioned audit corpus (the VK-LSVD translation).
3
+
4
+ Cross-industry translation: VK-LSVD (WWW '26, arXiv 2602.04567) turned an
5
+ industrial dataset into ecosystem gravity — dataset + documented schema +
6
+ published baselines + a challenge on top. This module does the same for
7
+ accessibility evaluation: FROZEN pages with a sealed ground truth (the
8
+ mutant bank: one injected violation per page, placebo controls for false
9
+ positives), a NEUTRAL evaluation contract any engine can answer (criterion
10
+ codes, not our signal names), a reference baseline from this engine, and a
11
+ versioned manifest with a hash seal — same tamper-evidence DNA as the
12
+ evidence pack.
13
+
14
+ Why frozen beats regenerated: the mutant generator evolves with the engine;
15
+ a corpus that silently changed underneath a published score is a broken
16
+ benchmark. A published corpus version is never edited (D12 applied to
17
+ data): pages ship as files, the manifest seals every hash, changes ship as
18
+ a new version with a changelog entry.
19
+
20
+ The challenge shape: third parties produce a submission (one JSON line per
21
+ case with the WCAG criteria their evaluator flags), `corpus evaluate`
22
+ scores it deterministically — kill rate on mutants, false positives on
23
+ placebos, per-criterion confusion. `corpus reference` re-runs this engine
24
+ over the frozen pages and ships the baseline with it.
25
+
26
+ CLI (this is infrastructure, not a tool — D17):
27
+ a11ycorpus.py build [--version 2026.10.0] [--seed 7] [--n 18] [--out corpus]
28
+ a11ycorpus.py verify [dir]
29
+ a11ycorpus.py evaluate --submission sub.jsonl [dir]
30
+ a11ycorpus.py reference [dir]
31
+ """
32
+
33
+ import argparse
34
+ import datetime
35
+ import hashlib
36
+ import json
37
+ import os
38
+ import re
39
+ import sys
40
+
41
+ from .a11ymutants import generate as generate_exam
42
+ from .a11yaudit import audit_html
43
+
44
+ CORPUS_FORMAT = 'a11y-corpus/1'
45
+ EVAL_FORMAT = 'a11y-corpus-evaluation/1'
46
+
47
+ _NOTE_README = """# a11y corpus {version}
48
+
49
+ Frozen pages with sealed ground truth for evaluation-benchmarking ANY
50
+ accessibility engine. Version {version}, {n_total} entries ({n_mutants}
51
+ sealed mutants + {n_control} placebo controls). Format `{fmt}`.
52
+
53
+ ## The contract (engine-neutral)
54
+
55
+ One JSON line per case in your submission file:
56
+
57
+ {{"case_id": "m7-0", "criteria_found": ["1.1.1"]}}
58
+
59
+ `criteria_found` = the WCAG 2.x criteria YOUR evaluator reports as failing
60
+ on that page (criterion codes, e.g. "1.4.4" — not tool-specific rule ids).
61
+ Placebo entries accept the same shape; anything you flag on them counts as a
62
+ false positive by construction (no violation was injected).
63
+
64
+ Score it:
65
+
66
+ a11ytoolkit corpus evaluate --submission my-submission.jsonl {rel}
67
+
68
+ ## Verify this corpus (no toolkit needed)
69
+
70
+ Every file hash and the manifest seal are plain sha256:
71
+
72
+ cd {rel} && shasum -a 256 -c <(python3 -c \\
73
+ "import json;m=json.load(open('MANIFEST.json'));[print(v+' '+k) for k,v in m['files'].items()]")
74
+
75
+ The seal `MANIFEST.json.sha256` covers the canonical manifest without the
76
+ seal itself — recompute and compare (see a11ycorpus.py `verify`).
77
+
78
+ ## Baseline
79
+
80
+ `results/reference.json` is this engine's own submission scored by the same
81
+ harness (published WITH the dataset, LSVD-style). A published corpus
82
+ version is never edited; changes ship as a new version + changelog entry.
83
+ """
84
+
85
+
86
+ def _canon(obj):
87
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True,
88
+ separators=(',', ':'))
89
+
90
+
91
+ def _sha(data_bytes):
92
+ return hashlib.sha256(data_bytes).hexdigest()
93
+
94
+
95
+ def _side_features(html_text):
96
+ """Características baratas y declaradas por página (para estratificar)."""
97
+ lang = re.search(r'<html[^>]*\blang="([a-z-]+)"', html_text, re.I)
98
+ title = re.search(r'<title>([^<]*)</title>', html_text)
99
+ return {
100
+ 'bytes': len(html_text.encode('utf-8')),
101
+ 'lang': lang.group(1) if lang else None,
102
+ 'title': title.group(1) if title else None,
103
+ 'imgs': len(re.findall(r'<img\b', html_text)),
104
+ 'buttons': len(re.findall(r'<button\b', html_text)),
105
+ 'links': len(re.findall(r'<a\b', html_text)),
106
+ }
107
+
108
+
109
+ def build(version='2026.10.0', seeds=(7,), n_per_seed=18, out='corpus',
110
+ date=None, with_reference=True):
111
+ """Congela un examen del banco de mutantes como corpus versionado.
112
+ Determinista dadas (version, seeds, n, date) y la versión del motor (el
113
+ baseline reference la embebe) — mismo insumo, mismos bytes."""
114
+ if len(set(seeds)) != len(seeds):
115
+ # los ids de caso llevan la seed (m{seed}-{i}): duplicarla colisiona
116
+ # TODOS los ids y el manifiesto mentiría sobre el número de casos
117
+ raise ValueError('duplicate seeds collide every case id: %s' % list(seeds))
118
+ date = date or datetime.date.today().isoformat()
119
+ os.makedirs(os.path.join(out, 'pages'), exist_ok=True)
120
+ os.makedirs(os.path.join(out, 'results'), exist_ok=True)
121
+ entries = []
122
+ for seed in seeds:
123
+ exam = generate_exam(seed, n_per_seed)
124
+ for item in exam['mutants'] + exam['control_pages']:
125
+ fname = 'pages/%s.html' % item['id']
126
+ with open(os.path.join(out, fname), 'w', encoding='utf-8') as f:
127
+ f.write(item['html'])
128
+ s = item['sealed']
129
+ case = {'case_id': item['id'], 'kind': 'mutant', 'file': fname,
130
+ 'side_features': _side_features(item['html']),
131
+ 'expected': {'criterion': s['criterion'],
132
+ 'operator': s['operator'],
133
+ 'detail': s['detail']}}
134
+ if item['id'].startswith('p'):
135
+ case['kind'] = 'placebo'
136
+ case['expected'] = None
137
+ entries.append(case)
138
+ entries.sort(key=lambda c: c['case_id'])
139
+ with open(os.path.join(out, 'cases.jsonl'), 'w', encoding='utf-8') as f:
140
+ for c in entries:
141
+ f.write(json.dumps(c, ensure_ascii=False, sort_keys=True) + '\n')
142
+
143
+ n_mut = sum(1 for c in entries if c['kind'] == 'mutant')
144
+ n_pla = len(entries) - n_mut
145
+ changelog = ('# Corpus changelog\n\n'
146
+ '## %s\n\n- initial release: %d sealed mutants + %d placebo '
147
+ 'controls (a11ymutants seeds %s, n=%d per seed, frozen '
148
+ 'byte-for-byte)\n' % (version, n_mut, n_pla,
149
+ list(seeds), n_per_seed))
150
+ with open(os.path.join(out, 'CHANGELOG.md'), 'w', encoding='utf-8') as f:
151
+ f.write(changelog)
152
+
153
+ manifest = {
154
+ 'format': CORPUS_FORMAT,
155
+ 'version': version,
156
+ 'date': date,
157
+ 'generator': {'source': 'a11ymutants (sealed exam)', 'seeds': list(seeds),
158
+ 'n_per_seed': n_per_seed},
159
+ 'counts': {'cases': len(entries), 'mutants': n_mut, 'placebos': n_pla,
160
+ 'criteria_covered': sorted({c['expected']['criterion']
161
+ for c in entries if c['expected']})},
162
+ 'contract': {'submission': 'JSONL {case_id, criteria_found: [WCAG codes]}',
163
+ 'scoring': 'kill = expected criterion flagged on a mutant; '
164
+ 'any flag on a placebo = false positive by '
165
+ 'construction'},
166
+ 'license_note': 'pages are engine-generated fixtures (MIT, same as the '
167
+ 'toolkit); no third-party crawl ships here',
168
+ 'files': {},
169
+ }
170
+ if with_reference:
171
+ ref = reference(out)
172
+ ref_text = json.dumps(ref, ensure_ascii=False, indent=1, sort_keys=True)
173
+ with open(os.path.join(out, 'results', 'reference.json'), 'w',
174
+ encoding='utf-8') as f:
175
+ f.write(ref_text)
176
+ manifest['files']['results/reference.json'] = _sha(ref_text.encode('utf-8'))
177
+ for rel in sorted(set(['cases.jsonl', 'CHANGELOG.md']
178
+ + ['pages/%s.html' % c['case_id'] for c in entries])):
179
+ with open(os.path.join(out, rel), 'rb') as f:
180
+ manifest['files'][rel] = _sha(f.read())
181
+ manifest['sha256'] = _sha(_canon({k: v for k, v in manifest.items()
182
+ if k != 'sha256'}).encode('utf-8'))
183
+ with open(os.path.join(out, 'MANIFEST.json'), 'w', encoding='utf-8') as f:
184
+ json.dump(manifest, f, ensure_ascii=False, indent=1, sort_keys=True)
185
+ readme = _NOTE_README.format(version=version, n_total=len(entries),
186
+ n_mutants=n_mut, n_control=n_pla,
187
+ fmt=CORPUS_FORMAT, rel=out.rstrip('/') or '.')
188
+ with open(os.path.join(out, 'README.md'), 'w', encoding='utf-8') as f:
189
+ f.write(readme)
190
+ return manifest
191
+
192
+
193
+ def verify(directory='corpus'):
194
+ """(ok, detail): cada hash del manifiesto + el sello del propio manifiesto."""
195
+ mpath = os.path.join(directory, 'MANIFEST.json')
196
+ if not os.path.exists(mpath):
197
+ return False, 'MANIFEST.json missing'
198
+ try:
199
+ manifest = json.load(open(mpath, encoding='utf-8'))
200
+ except (json.JSONDecodeError, UnicodeDecodeError) as e:
201
+ return False, 'manifest unreadable: %s' % e
202
+ if not isinstance(manifest, dict):
203
+ return False, 'manifest must be a JSON object'
204
+ seal = manifest.pop('sha256', None)
205
+ if seal is None:
206
+ return False, 'manifest has no seal'
207
+ if _sha(_canon(manifest).encode('utf-8')) != seal:
208
+ return False, 'manifest seal broken (MANIFEST.json edited)'
209
+ table = manifest.get('files')
210
+ if not isinstance(table, dict) or not table:
211
+ return False, 'manifest has no files table'
212
+ for rel, expected in table.items():
213
+ if not isinstance(rel, str) or '..' in rel or rel.startswith('/'):
214
+ return False, 'illegal path in manifest: %r' % rel
215
+ path = os.path.join(directory, rel)
216
+ if not os.path.exists(path):
217
+ return False, 'missing file: %s' % rel
218
+ with open(path, 'rb') as f:
219
+ if _sha(f.read()) != expected:
220
+ return False, 'hash mismatch: %s' % rel
221
+ return True, '%d files + seal verified' % len(table)
222
+
223
+
224
+ def _load_entries(directory='corpus'):
225
+ entries = {}
226
+ with open(os.path.join(directory, 'cases.jsonl'), encoding='utf-8') as f:
227
+ for line in f:
228
+ line = line.strip()
229
+ if line:
230
+ c = json.loads(line)
231
+ entries[c['case_id']] = c
232
+ return entries
233
+
234
+
235
+ def engine_submission(directory='corpus'):
236
+ """Este motor sobre las páginas congeladas → submission (mismo contrato
237
+ que un tercero: criterios que reporta por página)."""
238
+ sub = []
239
+ for cid, case in sorted(_load_entries(directory).items()):
240
+ html_text = open(os.path.join(directory, case['file']),
241
+ encoding='utf-8').read()
242
+ rep = audit_html(html_text, case['file'], lang='en')
243
+ found = sorted({h['criterion'].split(' ')[0]
244
+ for h in rep.get('findings', [])})
245
+ sub.append({'case_id': cid, 'criteria_found': found})
246
+ return sub
247
+
248
+
249
+ def evaluate(submission, directory='corpus', submission_name='submission'):
250
+ """Submission (lista de {case_id, criteria_found}) → veredicto determinista:
251
+ kill rate sobre mutantes, falsos positivos sobre placebos, confusión por
252
+ criterio. Contrato NEUTRAL: códigos WCAG, no señales nuestras."""
253
+ entries = _load_entries(directory)
254
+ by_id = {}
255
+ unknown = []
256
+ invalid = []
257
+ for entry in submission:
258
+ if not isinstance(entry, dict):
259
+ unknown.append(repr(entry)[:40])
260
+ continue
261
+ cid = entry.get('case_id')
262
+ if cid not in entries:
263
+ unknown.append(cid)
264
+ continue
265
+ found = entry.get('criteria_found', [])
266
+ if not isinstance(found, list):
267
+ # un string iteraría CARACTERES y mentiría el veredicto en
268
+ # silencio: se rechaza declarado, jamás se traga
269
+ invalid.append({'case_id': cid,
270
+ 'criteria_found': repr(found)[:60]})
271
+ continue
272
+ by_id[cid] = [str(c) for c in found]
273
+ killed, missed, fps, additional = [], [], [], []
274
+ per_crit = {}
275
+ for cid, case in sorted(entries.items()):
276
+ found = by_id.get(cid, [])
277
+ if case['kind'] == 'placebo':
278
+ if found:
279
+ fps.append({'case_id': cid, 'criteria_flagged': found})
280
+ continue
281
+ exp = case['expected']['criterion']
282
+ per_crit.setdefault(exp, {'expected': 0, 'killed': 0})
283
+ per_crit[exp]['expected'] += 1
284
+ if exp in found:
285
+ killed.append(cid)
286
+ per_crit[exp]['killed'] += 1
287
+ else:
288
+ missed.append({'case_id': cid, 'expected_criterion': exp,
289
+ 'operator': case['expected']['operator'],
290
+ 'found_instead': [c for c in found if c != exp]})
291
+ extra = [c for c in found if c != exp]
292
+ if extra:
293
+ additional.append({'case_id': cid, 'additional_criteria': extra})
294
+ n_mut = sum(1 for c in entries.values() if c['kind'] == 'mutant')
295
+ n_pla = len(entries) - n_mut
296
+ return {
297
+ 'format': EVAL_FORMAT,
298
+ 'submission_name': submission_name,
299
+ 'mutants': n_mut, 'killed': len(killed),
300
+ 'kill_rate': round(len(killed) / n_mut, 4) if n_mut else None,
301
+ 'missed_detail': missed,
302
+ 'control_pages': n_pla,
303
+ 'false_positives': fps,
304
+ 'additional_findings_on_mutants': {'count': len(additional),
305
+ 'note': 'reported, not scored: only '
306
+ 'placebo flags are false '
307
+ 'positives by construction',
308
+ 'sample': additional[:10]},
309
+ 'per_criterion': per_crit,
310
+ 'unknown_case_ids': unknown,
311
+ 'invalid_entries': invalid,
312
+ 'cases_without_submission': [cid for cid in sorted(entries)
313
+ if cid not in by_id][:10],
314
+ }
315
+
316
+
317
+ def reference(directory='corpus'):
318
+ """Baseline LSVD-style: este motor sobre el corpus congelado, puntuado
319
+ por el MISMO arnés que un tercero. Va publicado con el dataset."""
320
+ from . import server
321
+ sub = engine_submission(directory)
322
+ res = evaluate(sub, directory, submission_name='a11y-toolkit reference')
323
+ res['engine'] = {'name': 'a11y-toolkit', 'version': server.VERSION}
324
+ return res
325
+
326
+
327
+ def _read_submission(path):
328
+ """JSONL (un objeto por línea) o UN array JSON completo: el contrato es
329
+ neutral y terceros mandan ambos; el lector acepta los dos."""
330
+ with open(path, encoding='utf-8') as f:
331
+ text = f.read().strip()
332
+ if not text:
333
+ return []
334
+ if text.startswith('['):
335
+ return [e for e in json.loads(text) if isinstance(e, dict)]
336
+ out = []
337
+ for line in text.splitlines():
338
+ line = line.strip()
339
+ if line:
340
+ obj = json.loads(line)
341
+ if isinstance(obj, dict):
342
+ out.append(obj)
343
+ return out
344
+
345
+
346
+ def main(argv):
347
+ ap = argparse.ArgumentParser(description='Versioned audit corpus (VK-LSVD translation)')
348
+ sub = ap.add_subparsers(dest='action', required=True)
349
+ b = sub.add_parser('build', help='freeze a corpus version from the mutant bank')
350
+ b.add_argument('--version', default='2026.10.0')
351
+ b.add_argument('--seed', type=int, action='append', default=None)
352
+ b.add_argument('--n', type=int, default=18)
353
+ b.add_argument('--out', default='corpus')
354
+ b.add_argument('--date', help='release date ISO (default: today)')
355
+ b.add_argument('--no-reference', action='store_true')
356
+ v = sub.add_parser('verify', help='recompute every hash + the manifest seal')
357
+ v.add_argument('directory', nargs='?', default='corpus')
358
+ e = sub.add_parser('evaluate', help='score a neutral submission (JSONL)')
359
+ e.add_argument('--submission', required=True)
360
+ e.add_argument('directory', nargs='?', default='corpus')
361
+ r = sub.add_parser('reference', help='this engine over the frozen pages → baseline')
362
+ r.add_argument('--force', action='store_true',
363
+ help='rewrite the baseline of a sealed corpus (publishes a '
364
+ 'new engine baseline; breaks the old manifest seal)')
365
+ r.add_argument('directory', nargs='?', default='corpus')
366
+ a = ap.parse_args(argv)
367
+ if a.action == 'build':
368
+ m = build(version=a.version, seeds=tuple(a.seed or [7]), n_per_seed=a.n,
369
+ out=a.out, date=a.date, with_reference=not a.no_reference)
370
+ print(json.dumps({'corpus': a.out, 'version': m['version'],
371
+ 'cases': m['counts']['cases'],
372
+ 'sha256': m['sha256']}, ensure_ascii=False))
373
+ return 0
374
+ if a.action == 'verify':
375
+ ok, detail = verify(a.directory)
376
+ print(json.dumps({'ok': ok, 'detail': detail}, ensure_ascii=False))
377
+ return 0 if ok else 1
378
+ if a.action == 'evaluate':
379
+ res = evaluate(_read_submission(a.submission), a.directory,
380
+ submission_name=os.path.basename(a.submission))
381
+ print(json.dumps(res, ensure_ascii=False, indent=1))
382
+ return 0
383
+ if a.action == 'reference':
384
+ outp = os.path.join(a.directory, 'results', 'reference.json')
385
+ manifest_path = os.path.join(a.directory, 'MANIFEST.json')
386
+ if (os.path.exists(outp) and os.path.exists(manifest_path)
387
+ and not a.force):
388
+ # un corpus sellado es inmutable (D22): re-escribir su baseline
389
+ # tras un bump del motor rompería el sello y el pin del repo
390
+ print(json.dumps({'error': ('results/reference.json already exists '
391
+ 'in a sealed corpus — rewriting it '
392
+ 'breaks the manifest; use --force to '
393
+ 'publish a NEW engine baseline')},
394
+ ensure_ascii=False))
395
+ return 2
396
+ res = reference(a.directory)
397
+ os.makedirs(os.path.dirname(outp), exist_ok=True)
398
+ with open(outp, 'w', encoding='utf-8') as f:
399
+ json.dump(res, f, ensure_ascii=False, indent=1, sort_keys=True)
400
+ print(json.dumps({'reference': outp, 'kill_rate': res['kill_rate'],
401
+ 'false_positives': len(res['false_positives']),
402
+ 'engine': res['engine']}, ensure_ascii=False))
403
+ return 0
404
+ return 2
405
+
406
+
407
+ if __name__ == '__main__':
408
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_distrib — distributional aggregation (the HEGM translation).
3
+
4
+ Cross-industry translation: VK AI's HEGM (Hierarchical Exponential-Gaussian
5
+ Mixtures, ICDM 2026, arXiv 2608.23356) models the FULL distribution instead
6
+ of the mean because watch-time data is zero-inflated and long-tailed — the
7
+ mean lies in silence. Per-page accessibility numbers have exactly that
8
+ shape: most sampled pages are clean, a few are catastrophic. This module is
9
+ the statistics layer of WCAG-EM aggregation:
10
+
11
+ - prevalence with a Wilson score interval (closed form, small-n honest)
12
+ - per-page effort modeled as a zero-inflated mixture — a declared point
13
+ mass at exactly zero (pages with nothing pending) plus an exponential
14
+ tail and a gaussian body over the positives, fitted by pure-Python EM
15
+ with a DECLARED init: deterministic, reproducible
16
+ - HEGM's own failure catalog imported as fit VALIDATIONS: a dead
17
+ component, a collapsed variance, a single distinct value — a fit that
18
+ trips any of them never publishes a fitted interval; the rejection and
19
+ the fallback are declared in the output, never hidden. A bad fit is
20
+ data, not an embarrassment to bury.
21
+ - totals and site projections via a seeded percentile bootstrap (B and
22
+ seed declared in the output)
23
+ - effort minutes are a RANGE per criterion everywhere in the pack, so the
24
+ inference runs on both bands and publishes the OUTER ENVELOPE — a point
25
+ estimate that hid the range would be the exact lie this module exists
26
+ to avoid.
27
+
28
+ Statistics, never conformance: everything here is inference over the
29
+ SAMPLE. No output of this module is a conformance claim; the human still
30
+ owns the verdict (zero-claims rule, same as the pack).
31
+ """
32
+
33
+ import math
34
+ import random
35
+
36
+ # z two-sided 95% (declared constant — no tables, no scipy)
37
+ _Z975 = 1.959963984540054
38
+
39
+ # init y validaciones DECLARADAS (el catálogo de modos de fallo de HEGM,
40
+ # traducido a reglas que este módulo se aplica a sí mismo)
41
+ _INIT_SIGMA_FLOOR = 1.0 # minutos: un único valor distinto no arranca colapsado
42
+ _MIN_ABOVE_ZERO = 4 # menos de 4 positivos: 4 parámetros no se sostienen
43
+ _MIN_WEIGHT = 0.02 # peso < 2% = componente muerto
44
+ _MIN_SIGMA_RATIO = 0.01 # σ < 1% del rango observado = varianza colapsada
45
+ _MAX_ITER = 200
46
+ _TOL = 1e-9
47
+ _B_DEFAULT = 2000
48
+
49
+ _NOTE = {
50
+ 'es': ('Estadística sobre la muestra, nunca conformidad: los intervalos '
51
+ 'describen lo que la muestra permite afirmar, no lo que el sitio '
52
+ 'es. Los minutos son un rango por criterio: la inferencia corre '
53
+ 'sobre ambas bandas y publica el envolvente exterior (declarado). '
54
+ 'Un ajuste que no pasa las validaciones se declara y cae al '
55
+ 'bootstrap; jamás se publica un intervalo de un ajuste roto.'),
56
+ 'en': ('Statistics over the sample, never conformance: the intervals '
57
+ 'describe what the sample supports, not what the site is. Minutes '
58
+ 'are a range per criterion: the inference runs on both bands and '
59
+ 'publishes the outer envelope (declared). A fit that fails its '
60
+ 'validations is declared and falls back to the bootstrap; an '
61
+ 'interval from a broken fit is never published.'),
62
+ }
63
+
64
+
65
+ def wilson_interval(k, n, z=_Z975):
66
+ """Wilson score interval for k successes of n (closed form, deterministic;
67
+ honest at small n where the naive p±z rule goes below 0 or above 1).
68
+ k outside [0, n] is a caller lie and fails LOUD, never clamped silent."""
69
+ if n <= 0:
70
+ return None
71
+ if k < 0 or k > n:
72
+ raise ValueError('k=%s outside [0, n=%s]: a proportion cannot' % (k, n))
73
+ p = k / n
74
+ denom = 1 + z * z / n
75
+ center = (p + z * z / (2 * n)) / denom
76
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
77
+ return [round(max(0.0, center - half), 4), round(min(1.0, center + half), 4)]
78
+
79
+
80
+ def _dens_exp(lam, x):
81
+ return lam * math.exp(-lam * x) if lam > 0 else 0.0
82
+
83
+
84
+ def _dens_gauss(mu, sigma, x):
85
+ if sigma <= 0:
86
+ return 0.0
87
+ return math.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * math.sqrt(2 * math.pi))
88
+
89
+
90
+ def fit_mixture(values):
91
+ """Mezcla cero-inflada (δ0 en el cero exacto + Exp + Gauss sobre los
92
+ positivos) por EM determinista. NUNCA lanza: un ajuste que no se sostiene
93
+ se devuelve con sus validaciones en rojo — es un resultado."""
94
+ n = len(values)
95
+ zeros = sum(1 for v in values if v == 0)
96
+ pos = [v for v in values if v > 0]
97
+ out = {'model': 'zero-inflated exponential+gaussian EM',
98
+ 'init': 'declared (pi_zero = zeros/n, w = 0.5, lam = 1/mean, '
99
+ 'sigma floored at 1.0 min)',
100
+ 'sample': n, 'zeros': zeros, 'positives': len(pos),
101
+ 'pi_zero': round(zeros / n, 4) if n else 1.0,
102
+ 'max_iter': _MAX_ITER, 'tol': _TOL,
103
+ 'validations': {}, 'ok': False, 'rejections': []}
104
+ if not pos:
105
+ out['rejections'].append('no positive values: the zero mass is the '
106
+ 'whole sample (nothing to fit, honestly)')
107
+ elif len(set(pos)) < 2:
108
+ out['rejections'].append('single distinct positive value: variance '
109
+ 'collapses by construction')
110
+ elif len(pos) < _MIN_ABOVE_ZERO:
111
+ out['rejections'].append('fewer than %d positive values: four free '
112
+ 'parameters do not stand on less' % _MIN_ABOVE_ZERO)
113
+ if out['rejections']:
114
+ out['validations'] = {'dead_component': None, 'variance_collapse': None,
115
+ 'single_distinct_value': len(set(pos)) < 2 if pos else None}
116
+ return out
117
+
118
+ mean = sum(pos) / len(pos)
119
+ var = sum((v - mean) ** 2 for v in pos) / len(pos)
120
+ w = 0.5
121
+ lam = 1.0 / mean
122
+ mu = mean
123
+ sigma = max(math.sqrt(var), _INIT_SIGMA_FLOOR)
124
+ iterations = 0
125
+ stable = False
126
+ zero_density = False
127
+ prev_ll = None
128
+ for _ in range(_MAX_ITER):
129
+ iterations += 1
130
+ # E-step sobre los positivos (los ceros exactos son masa puntual)
131
+ r_e, ll = [], 0.0
132
+ for x in pos:
133
+ de = w * _dens_exp(lam, x)
134
+ dg = (1 - w) * _dens_gauss(mu, sigma, x)
135
+ tot = de + dg
136
+ if tot <= 0:
137
+ # underflow: densidad CERO bajo ambos componentes — otro modo
138
+ # de fallo del catálogo HEGM, se declara (nunca -1e300 mudo)
139
+ zero_density = True
140
+ tot = 1e-300
141
+ r_e.append(de / tot)
142
+ ll += math.log(tot)
143
+ if prev_ll is not None and abs(ll - prev_ll) < _TOL:
144
+ stable = True
145
+ break
146
+ prev_ll = ll
147
+ # M-step
148
+ se, sg = sum(r_e), len(pos) - sum(r_e)
149
+ w = se / len(pos)
150
+ if se > 0:
151
+ lam = se / sum(r * x for r, x in zip(r_e, pos))
152
+ if sg > 0:
153
+ mu = sum((1 - r) * x for r, x in zip(r_e, pos)) / sg
154
+ sigma = math.sqrt(max(
155
+ 1e-12,
156
+ sum((1 - r) * (x - mu) ** 2 for r, x in zip(r_e, pos)) / sg))
157
+ rng_pos = max(pos) - min(pos)
158
+ dead = w < _MIN_WEIGHT or w > 1 - _MIN_WEIGHT
159
+ collapse = sigma < _MIN_SIGMA_RATIO * rng_pos
160
+ out.update({'w_exp': round(w, 4), 'w_gauss': round(1 - w, 4),
161
+ 'lambda': round(lam, 6), 'mu': round(mu, 4),
162
+ 'sigma': round(sigma, 4),
163
+ 'iterations': iterations, 'converge': stable,
164
+ 'validations': {'dead_component': dead,
165
+ 'variance_collapse': collapse,
166
+ 'single_distinct_value': False}})
167
+ if dead:
168
+ out['rejections'].append('dead component: mixture weight %.4f outside '
169
+ '[%.2f, %.2f]' % (w, _MIN_WEIGHT, 1 - _MIN_WEIGHT))
170
+ if collapse:
171
+ out['rejections'].append('collapsed variance: sigma %.4f < 1%% of the '
172
+ 'observed range %.4f' % (sigma, rng_pos))
173
+ if zero_density:
174
+ out['rejections'].append('density underflow: a positive point has zero '
175
+ 'likelihood under both components')
176
+ if not stable:
177
+ out['rejections'].append('EM did not converge in %d iterations' % _MAX_ITER)
178
+ out['ok'] = not out['rejections']
179
+ return out
180
+
181
+
182
+ def bootstrap_mean_ci(values, b=_B_DEFAULT, seed=7,
183
+ lo_pct=2.5, hi_pct=97.5):
184
+ """Percentile bootstrap de la MEDIA (semilla y B declarados → el mismo
185
+ intervalo siempre). Vacío → None; constante → [c, c] (honesto)."""
186
+ if not values:
187
+ return None
188
+ rng = random.Random(seed)
189
+ n = len(values)
190
+ stats = sorted(sum(rng.choices(values, k=n)) / n for _ in range(b))
191
+ i_lo = min(b - 1, max(0, int(b * lo_pct / 100)))
192
+ i_hi = min(b - 1, max(0, int(b * hi_pct / 100)))
193
+ return [round(stats[i_lo], 2), round(stats[i_hi], 2)]
194
+
195
+
196
+ def _mean(xs):
197
+ return sum(xs) / len(xs) if xs else 0.0
198
+
199
+
200
+ def _median(xs):
201
+ if not xs:
202
+ return 0.0
203
+ s = sorted(xs)
204
+ m = len(s) // 2
205
+ return s[m] if len(s) % 2 else (s[m - 1] + s[m]) / 2
206
+
207
+
208
+ def effort_inference(per_page_minutes_lo, per_page_minutes_hi, seed=7,
209
+ projected_pages=None, lang='en'):
210
+ """Bandas de minutos por página (la lo y la hi del rango por criterio,
211
+ sumadas por página) → bloque de inferencia completo para el reporte
212
+ WCAG-EM. Envolvente exterior de ambas bandas; jamás un punto oculto."""
213
+ if not per_page_minutes_lo:
214
+ raise ValueError('empty sample: nothing to infer over')
215
+ lo_band = [float(v) for v in per_page_minutes_lo]
216
+ hi_band = [float(v) for v in per_page_minutes_hi]
217
+ if len(lo_band) != len(hi_band):
218
+ raise ValueError('lo/hi bands must have one value per sampled page')
219
+ if projected_pages is not None and int(projected_pages) < 1:
220
+ raise ValueError('projected_pages must be a positive integer')
221
+ n = len(lo_band)
222
+ mid = [(a + b) / 2 for a, b in zip(lo_band, hi_band)]
223
+ block = {
224
+ 'format': 'a11y-effort-inference/1',
225
+ 'sample_pages': n,
226
+ 'zero_pages': sum(1 for v in mid if v == 0),
227
+ 'observed_total_minutes': [round(sum(lo_band), 1), round(sum(hi_band), 1)],
228
+ 'per_page_minutes': {
229
+ 'mean': [round(_mean(lo_band), 2), round(_mean(hi_band), 2)],
230
+ 'median': [round(_median(lo_band), 2), round(_median(hi_band), 2)],
231
+ },
232
+ 'seed': seed, 'bootstrap_b': _B_DEFAULT,
233
+ 'ci95_method': 'percentile bootstrap over pages, outer envelope of '
234
+ 'the lo/hi minute bands',
235
+ }
236
+ for name, band in (('lo', lo_band), ('hi', hi_band)):
237
+ block['fit_%s' % name] = fit_mixture(band)
238
+ block['ci95_mean_%s' % name] = bootstrap_mean_ci(band, seed=seed)
239
+ bounds_lo = [block['ci95_mean_lo'][0], block['ci95_mean_hi'][0]]
240
+ bounds_hi = [block['ci95_mean_lo'][1], block['ci95_mean_hi'][1]]
241
+ block['ci95_mean_envelope'] = [round(min(bounds_lo), 2), round(max(bounds_hi), 2)]
242
+ if projected_pages:
243
+ npages = int(projected_pages)
244
+ block['projection'] = {
245
+ 'pages': npages,
246
+ 'declared_by': 'plan.estimated_pages (evaluator figure, not a '
247
+ 'measurement)',
248
+ 'expected_total_minutes': [round(npages * _mean(lo_band), 1),
249
+ round(npages * _mean(hi_band), 1)],
250
+ 'ci95_minutes': [round(npages * min(bounds_lo), 1),
251
+ round(npages * max(bounds_hi), 1)],
252
+ }
253
+ block['mixture_used'] = bool(block['fit_lo']['ok'] and block['fit_hi']['ok'])
254
+ block['note'] = _NOTE['es' if lang == 'es' else 'en']
255
+ return block
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_fingerprints — multi-hash template fingerprints (twin-page detection).
3
+
4
+ Cross-industry translation: multi-hash identification. One hash of a page
5
+ breaks the moment a csrf token or a timestamp changes; several independent
6
+ hashes over DIFFERENT normalizations identify by intersection — a template
7
+ stays recognizable when its volatile parts change, and the view that
8
+ diverges tells what KIND of change it was.
9
+
10
+ Three views of the document, text always excluded (content varies per page;
11
+ that is the point):
12
+ structure tag + depth — the skeleton (defines the template)
13
+ classes + sorted class list — the skin (design-system change)
14
+ attributes + stable attributes — real attribute changes, with the
15
+ id-referencing / volatile attrs excluded by design (id, for,
16
+ name, href, src, …) so per-page ids and csrf tokens can never
17
+ split a template
18
+
19
+ Regions: the landmark containers (header/nav/main/aside/footer) plus
20
+ `document` for everything outside them. Each (view, region) → sha256[:12].
21
+
22
+ Template = the complete structure view (same skeleton = same template — a
23
+ declared rule, not fuzzy similarity). Inside a template every page is
24
+ compared view-by-view against the representative (the lexicographically
25
+ smallest page id); each mismatch is a localized {page, region, view} entry:
26
+ "header diverges in classes, footer identical".
27
+
28
+ sample_suggestion = one representative per template, the structured-sample
29
+ helper for WCAG-EM Step 3. The evaluator still owns the sample; identical
30
+ structure does not guarantee identical findings after rendering.
31
+
32
+ CLI:
33
+ a11yfingerprints.py page1.html page2.html [--dir pages/] [--lang es] [-o out.json]
34
+ """
35
+
36
+ import argparse
37
+ import hashlib
38
+ import json
39
+ import os
40
+ import sys
41
+ from html.parser import HTMLParser
42
+
43
+ VIEWS = ('structure', 'classes', 'attributes')
44
+
45
+ # landmarks que abren región propia; lo que queda fuera vive en 'document'
46
+ _REGIONS = ('header', 'nav', 'main', 'aside', 'footer')
47
+
48
+ # attrs volátiles por construcción: referencian ids únicos por página o
49
+ # cambian con cada petición — si entraran en una vista, partirían plantillas
50
+ # falsamente (el csrf/token/per-page-id NO es un rediseño)
51
+ _VOLATILE = frozenset((
52
+ 'id', 'for', 'name', 'href', 'src', 'srcset', 'action', 'headers',
53
+ 'list', 'style', 'value', 'aria-controls', 'aria-describedby',
54
+ 'aria-labelledby', 'aria-owns', 'aria-details', 'aria-errormessage',
55
+ ))
56
+
57
+ _VOID = frozenset(('area', 'base', 'br', 'col', 'embed', 'hr', 'img',
58
+ 'input', 'link', 'meta', 'param', 'source', 'track',
59
+ 'wbr', 'path', 'circle', 'rect', 'line', 'polyline',
60
+ 'polygon', 'ellipse', 'stop', 'use'))
61
+
62
+ # vistas que se comparan dentro de una plantilla (structure NO puede divergir
63
+ # por definición — es la clave de agrupación)
64
+ _DIVERGENCE_VIEWS = ('classes', 'attributes')
65
+
66
+ _NOTES = {
67
+ 'en': ('Suggests a structured sample: one representative per detected '
68
+ 'template (WCAG-EM Step 3 helper). The evaluator still owns sample '
69
+ 'selection; identical structure does not guarantee identical '
70
+ 'findings after rendering. Volatile attributes (per-page ids, '
71
+ 'urls, tokens) are excluded by design so they cannot split '
72
+ 'templates.'),
73
+ 'es': ('Sugiere una muestra estructurada: un representante por plantilla '
74
+ 'detectada (ayudante del paso 3 de WCAG-EM). El evaluador sigue '
75
+ 'siendo dueño de la selección; estructura idéntica no garantiza '
76
+ 'hallazgos idénticos tras el render. Los atributos volátiles '
77
+ '(ids por página, urls, tokens) se excluyen a propósito para que '
78
+ 'no puedan partir plantillas.'),
79
+ }
80
+
81
+
82
+ def _digest(lines):
83
+ return hashlib.sha256('\n'.join(lines).encode('utf-8')).hexdigest()[:12]
84
+
85
+
86
+ class _Serializer(HTMLParser):
87
+ """Serializa el documento a 3 vistas × regiones. Tolerante al HTML hostil:
88
+ cierres sin apertura, anidación imposible y attrs duplicados no rompen
89
+ nada (el parser de stdlib ya de-duplica attrs; los cierres huérfanos se
90
+ ignoran, los abiertos sin cerrar se limpian al final)."""
91
+
92
+ def __init__(self):
93
+ super().__init__(convert_charrefs=True)
94
+ self.lines = {v: {} for v in VIEWS} # view -> region -> [lines]
95
+ self._stack = [] # [(tag, era_landmark_antes)]
96
+ self._landmarks = [] # landmarks abiertos (externo→interno)
97
+
98
+ # región vigente: el landmark MÁS EXTERNO abierto; si ninguno, 'document'
99
+ def _region(self):
100
+ return self._landmarks[0] if self._landmarks else 'document'
101
+
102
+ def _close_landmark(self, tag):
103
+ """Cierra el landmark MÁS RECIENTE de ese tag (LIFO, como el stack).
104
+ remove() a secas borraría el primero y corrompería el orden
105
+ externo→interno con landmarks anidados del mismo tipo."""
106
+ for i in range(len(self._landmarks) - 1, -1, -1):
107
+ if self._landmarks[i] == tag:
108
+ del self._landmarks[i]
109
+ return
110
+
111
+ def _emit(self, tag, attrs, depth):
112
+ region = self._region()
113
+ cls = sorted((attrs.get('class') or '').split())
114
+ # sin \n/\r en los valores: un attr hostil no puede falsificar
115
+ # líneas del material que se hashea (dos documentos distintos, un
116
+ # mismo digest sería una divergencia perdida)
117
+ stable = sorted('{}={}'.format(k, v.replace('\n', ' ').replace('\r', ' '))
118
+ for k, v in attrs.items()
119
+ if k not in _VOLATILE and k != 'class')
120
+ for view, extra in (('structure', ''),
121
+ ('classes', ' .' + '.'.join(cls) if cls else ''),
122
+ ('attributes', ' ' + ' '.join(stable) if stable else '')):
123
+ self.lines[view].setdefault(region, []).append(
124
+ '{} {}{}'.format(depth, tag, extra))
125
+
126
+ def handle_starttag(self, tag, attrs):
127
+ tag = tag.lower()
128
+ adict = {}
129
+ for k, v in attrs: # parser stdlib ya deduplica,
130
+ adict.setdefault(k, v or '') # pero no perdemos nada siendo explícitos
131
+ depth = len(self._stack)
132
+ if tag in _REGIONS:
133
+ # el propio landmark pertenece a SU región: abre antes de emitir
134
+ # (append: el PRIMERO de la lista es el más externo → _region())
135
+ self._landmarks.append(tag)
136
+ self._emit(tag, adict, depth)
137
+ if tag not in _VOID:
138
+ self._stack.append(tag)
139
+
140
+ def handle_startendtag(self, tag, attrs):
141
+ # <tag/> autocontenido: emite sin apilar (el mismo elemento, una vez)
142
+ self.handle_starttag(tag, attrs)
143
+ if self._stack and self._stack[-1] == tag and tag not in _VOID:
144
+ self._stack.pop()
145
+ if tag in self._landmarks:
146
+ self._close_landmark(tag)
147
+
148
+ def handle_endtag(self, tag):
149
+ tag = tag.lower()
150
+ if tag in self._stack:
151
+ # pop hasta el cierre correcto; lo que quede abierto fuera se ignora
152
+ while self._stack:
153
+ open_tag = self._stack.pop()
154
+ if open_tag in _REGIONS:
155
+ self._close_landmark(open_tag)
156
+ if open_tag == tag:
157
+ break
158
+ elif tag in _REGIONS and tag in self._landmarks:
159
+ self._close_landmark(tag)
160
+
161
+
162
+ def fingerprint_html(html_text):
163
+ """html (str) → {hashes: {view: {region: digest}}, template, regions}.
164
+
165
+ Determinista: mismas vistas, mismo sha, sin red ni azar."""
166
+ s = _Serializer()
167
+ try:
168
+ s.feed(html_text or '')
169
+ s.close()
170
+ except Exception:
171
+ pass # el parser stdlib no lanza con entrada hostil, pero si algo
172
+ # escapa, lo YA serializado sigue siendo un fingerprint válido
173
+ hashes = {v: {r: _digest(ls) for r, ls in s.lines[v].items()}
174
+ for v in VIEWS}
175
+ structure = hashes['structure']
176
+ template = 't-' + hashlib.sha256(
177
+ '|'.join('{}:{}'.format(r, structure[r]) for r in sorted(structure))
178
+ .encode('utf-8')).hexdigest()[:8]
179
+ return {'hashes': hashes, 'template': template,
180
+ 'regions': sorted(structure)}
181
+
182
+
183
+ def fingerprint_pages(pages, lang='en'):
184
+ """pages: [{'page': id, 'html': str}] → informe completo.
185
+
186
+ Agrupa por plantilla (vista structure), localiza la divergencia vista a
187
+ vista contra el representante (id lexicográfico mínimo — regla
188
+ declarada) y sugiere una muestra de un representante por plantilla
189
+ (ayudante del paso 3 de WCAG-EM; el evaluador decide)."""
190
+ if not isinstance(pages, list) or not all(
191
+ isinstance(p, dict) and 'page' in p and 'html' in p for p in pages):
192
+ raise ValueError('pages must be a list of {page, html} dicts')
193
+
194
+ entries = []
195
+ for p in pages:
196
+ fp = fingerprint_html(p['html'])
197
+ entries.append({'page': p['page'], 'hashes': fp['hashes'],
198
+ 'regions': fp['regions'], 'template': fp['template']})
199
+
200
+ groups = {}
201
+ for e in entries:
202
+ groups.setdefault(e['template'], []).append(e)
203
+
204
+ templates = []
205
+ for tid in sorted(groups):
206
+ members = sorted(groups[tid], key=lambda e: e['page'])
207
+ rep = members[0]
208
+ rep_h = rep['hashes']
209
+ divergence = []
210
+ for m in members[1:]:
211
+ for view in _DIVERGENCE_VIEWS:
212
+ regions = set(rep_h[view]) | set(m['hashes'][view])
213
+ for r in sorted(regions):
214
+ if rep_h[view].get(r) != m['hashes'][view].get(r):
215
+ divergence.append({'page': m['page'],
216
+ 'region': r, 'view': view})
217
+ templates.append({
218
+ 'template': tid,
219
+ 'pages': [m['page'] for m in members],
220
+ 'page_count': len(members),
221
+ 'representative': rep['page'],
222
+ 'divergence': divergence,
223
+ })
224
+
225
+ return {
226
+ 'mode': 'template-fingerprints',
227
+ 'pages_total': len(entries),
228
+ 'templates_total': len(templates),
229
+ 'views': list(VIEWS),
230
+ 'volatile_attrs_ignored': sorted(_VOLATILE),
231
+ 'pages': entries,
232
+ 'templates': templates,
233
+ 'sample_suggestion': sorted(t['representative'] for t in templates),
234
+ 'note': _NOTES['es' if lang == 'es' else 'en'],
235
+ }
236
+
237
+
238
+ def main(argv):
239
+ ap = argparse.ArgumentParser(description=__doc__)
240
+ ap.add_argument('pages', nargs='*', help='HTML pages to fingerprint')
241
+ ap.add_argument('--dir', help='also read every *.html/*.htm in this '
242
+ 'directory (sorted)')
243
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
244
+ ap.add_argument('-o', '--out', help='also write the report to this file')
245
+ a = ap.parse_args(argv)
246
+
247
+ names = list(a.pages)
248
+ if a.dir:
249
+ for f in sorted(os.listdir(a.dir)):
250
+ if f.lower().endswith(('.html', '.htm')):
251
+ names.append(os.path.join(a.dir, f))
252
+ if not names:
253
+ ap.error('no pages: pass pages and/or --dir')
254
+
255
+ pages = []
256
+ for name in names:
257
+ with open(name, encoding='utf-8', errors='replace') as f:
258
+ pages.append({'page': name, 'html': f.read()})
259
+
260
+ report = fingerprint_pages(pages, lang=a.lang)
261
+ text = json.dumps(report, ensure_ascii=False, indent=1)
262
+ if a.out:
263
+ with open(a.out, 'w', encoding='utf-8') as f:
264
+ f.write(text + '\n')
265
+ print(text)
266
+ return 0
267
+
268
+
269
+ if __name__ == '__main__':
270
+ sys.exit(main(sys.argv[1:]))
@@ -18,6 +18,7 @@ Design (documented in docs/i18n.md):
18
18
  Brand voice without forking the engine.
19
19
  """
20
20
 
21
+ import ast
21
22
  import json
22
23
  import os
23
24
  import re
@@ -79,11 +80,70 @@ def pair(namespace):
79
80
  return {lang: pack(lang).get(namespace, {}) for lang in ('es', 'en')}
80
81
 
81
82
 
83
+ # ── reglas plurales CLDR SIN eval ───────────────────────────────────────────
84
+ # Un locale pack es DATO (community-editable por diseño, y use_overlay() puede
85
+ # capar encima un pack de un tercero): dato jamás se convierte en código. La
86
+ # gramática CLDR es comparaciones y módulos sobre n — se evalúa con un AST de
87
+ # lista blanca; cualquier constructo fuera de esa gramática levanta ValueError.
88
+ _CLDR_COMPARE = {ast.Eq: lambda a, b: a == b, ast.NotEq: lambda a, b: a != b,
89
+ ast.Lt: lambda a, b: a < b, ast.LtE: lambda a, b: a <= b,
90
+ ast.Gt: lambda a, b: a > b, ast.GtE: lambda a, b: a >= b}
91
+ _CLDR_BINOP = {ast.Mod: lambda a, b: a % b, ast.Add: lambda a, b: a + b,
92
+ ast.Sub: lambda a, b: a - b, ast.Mult: lambda a, b: a * b}
93
+
94
+
95
+ def eval_plural_rule(rule, n):
96
+ """Evalúa 'n != 1', 'n % 10 == 1 and n % 100 != 11'… SIN eval dinámico.
97
+
98
+ Lista blanca AST: BoolOp(And/Or), Not, Compare (== != < <= > >=),
99
+ BinOp (% + - *), enteros/flotantes y el nombre `n`. TODO lo demás
100
+ (llamadas, atributos, subíndices, imports…) → ValueError."""
101
+ if not isinstance(rule, str) or not rule or len(rule) > 120:
102
+ raise ValueError('plural rule must be a short non-empty string')
103
+ tree = ast.parse(rule, mode='eval')
104
+
105
+ def ev(node):
106
+ if isinstance(node, ast.Expression):
107
+ return ev(node.body)
108
+ if isinstance(node, ast.BoolOp) and isinstance(node.op, (ast.And, ast.Or)):
109
+ vals = (ev(v) for v in node.values)
110
+ return all(vals) if isinstance(node.op, ast.And) else any(vals)
111
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
112
+ return not ev(node.operand)
113
+ if isinstance(node, ast.Compare):
114
+ left = ev(node.left)
115
+ for op, comp in zip(node.ops, node.comparators):
116
+ fn = _CLDR_COMPARE.get(type(op))
117
+ if fn is None:
118
+ raise ValueError('operator not in the CLDR subset')
119
+ right = ev(comp)
120
+ if not fn(left, right):
121
+ return False
122
+ left = right # encadenadas: a < b < c
123
+ return True
124
+ if isinstance(node, ast.BinOp) and type(node.op) in _CLDR_BINOP:
125
+ return _CLDR_BINOP[type(node.op)](ev(node.left), ev(node.right))
126
+ if (isinstance(node, ast.Constant)
127
+ and isinstance(node.value, (int, float))
128
+ and not isinstance(node.value, bool)):
129
+ return node.value
130
+ if isinstance(node, ast.Name) and node.id == 'n':
131
+ return n
132
+ raise ValueError('construct not in the CLDR subset: %s'
133
+ % type(node).__name__)
134
+
135
+ result = ev(tree)
136
+ if not isinstance(result, bool):
137
+ raise ValueError('plural rule must be a predicate (a comparison), '
138
+ 'not a bare value')
139
+ return result
140
+
141
+
82
142
  def plural_category(lang, n):
83
143
  """'one' or 'other' per the locale's `_meta.plural` CLDR expression."""
84
144
  rule = pack(lang).get('_meta', {}).get('plural', 'n != 1')
85
145
  try:
86
- return 'one' if eval(rule, {'__builtins__': {}}, {'n': n}) else 'other' # noqa: S307
146
+ return 'one' if eval_plural_rule(rule, n) else 'other'
87
147
  except Exception:
88
148
  return 'other'
89
149
 
@@ -9,6 +9,12 @@ sampled and reported. This module does the machine half honestly:
9
9
  report → per-criterion rollup ACROSS the sample (Step 5), sealed with
10
10
  a root hash over the pack seals
11
11
 
12
+ Since a11y-wcagem-report/2 the rollup carries its STATISTICS layer
13
+ (a11ydistrib, the HEGM translation): per-criterion failure prevalence with a
14
+ Wilson interval (what a random unaudited page may hold), and per-page human
15
+ effort as a zero-inflated mixture + seeded bootstrap — intervals over the
16
+ sample, never claims about the site.
17
+
12
18
  What it deliberately does NOT do: claim conformance. The report carries
13
19
  evidence-status per criterion (the worst across the sample wins), the
14
20
  priced human work that remains, and the standard's step trace. Random
@@ -24,6 +30,8 @@ import hashlib
24
30
  import json
25
31
  import sys
26
32
 
33
+ from .a11ydistrib import effort_inference, wilson_interval
34
+
27
35
  # El worst peor gana al agregar samples; never-flagged en TODAS no es pass
28
36
  # (es "ninguna señal saltó en esta sample"), exactamente como el pack.
29
37
  _RANK = {'automated-fail': 0, 'not-run': 1, 'automated-review': 2,
@@ -75,15 +83,28 @@ def validate_plan(plan):
75
83
  f"{'/'.join(_TYPES)} (WCAG-EM 3.1-3.3)")
76
84
  if not m.get('url') and not m.get('file'):
77
85
  return False, f"sample {m['id']}: url o file requeridos"
86
+ if plan.get('estimated_pages') is not None:
87
+ ep = plan['estimated_pages']
88
+ # la proyección es una FIGURA del evaluador, no una medición — pero
89
+ # proyectar sobre menos páginas que la muestra propia es sin sentido
90
+ if not isinstance(ep, int) or isinstance(ep, bool) or ep < len(sample):
91
+ return False, (f'estimated_pages debe ser entero ≥ len(sample) '
92
+ f'({len(sample)}) para proyectar el esfuerzo')
78
93
  return True, ''
79
94
 
80
95
 
81
- def aggregate(plan, packs):
96
+ def aggregate(plan, packs, lang='en', inference_seed=7):
82
97
  """Plan válido + packs sellados → report agregado con sello raíz.
83
98
 
84
99
  Regla de agregado por criterio: el PEOR worst de todas las samples
85
100
  (un fallo en cualquier página muestreada es un fallo del report).
86
101
  agent-verified no borra un fail (misma honestidad que el pack).
102
+
103
+ Desde /2: cada criterio lleva su prevalencia en la muestra con intervalo
104
+ Wilson (qué puede contener una página NO muestreada), y el reporte lleva
105
+ el bloque `inference` del esfuerzo (a11ydistrib, traducción HEGM:
106
+ mezcla cero-inflada + bootstrap sembrado sobre las bandas lo/hi de
107
+ minutos). Estadística sobre la muestra, jamás conformidad.
87
108
  """
88
109
  ok, err = validate_plan(plan)
89
110
  if not ok:
@@ -93,10 +114,15 @@ def aggregate(plan, packs):
93
114
 
94
115
  codes, names, effort = set(), {}, {'MIN': 0, 'MED': 0, 'MAX': 0}
95
116
  worst = {} # code → peor worst
96
- fail_counts = {} # code → cuántas samples fallaron
117
+ fail_counts = {} # code → cuántas SAMPLES fallaron (no filas)
97
118
  for pack in packs:
119
+ seen = set() # un criterio aparece UNA vez por pack; duplicados de un
120
+ # pack manual no deben inflar prevalencia ni esfuerzo (cuentan 1 sample)
98
121
  for c in pack.get('criteria', []):
99
122
  code = c['criterion'].split(' ')[0]
123
+ if code in seen:
124
+ continue
125
+ seen.add(code)
100
126
  codes.add(code)
101
127
  names[code] = c['criterion']
102
128
  st = c['status']
@@ -110,16 +136,41 @@ def aggregate(plan, packs):
110
136
 
111
137
  criteria = []
112
138
  for code in sorted(codes, key=lambda x: tuple(int(n) for n in x.split('.'))):
139
+ k = fail_counts.get(code, 0)
113
140
  row = {'criterion': names[code], 'status': worst[code],
114
- 'samples_failing': fail_counts.get(code, 0),
141
+ 'samples_failing': k,
115
142
  'total_samples': len(packs)}
143
+ # estadística de la muestra: prevalencia observada + banda Wilson
144
+ row['prevalence'] = round(k / len(packs), 4) if packs else 0.0
145
+ row['prevalence_ci95_wilson'] = wilson_interval(k, len(packs))
116
146
  if worst[code] == 'not-flagged':
117
147
  row['note'] = ('no signal fired on ANY sampled page — explicitly '
118
148
  'NOT pass; the human still owns this criterion')
119
149
  criteria.append(row)
120
150
 
151
+ # esfuerzo por página: ambas bandas del rango de minutos por criterio
152
+ # (el agente-verificado ya está pagado, no cuenta — misma regla arriba);
153
+ # un pack manual puede traer la fila duplicada o el rango invertido: se
154
+ # deduplica por código y el rango se normaliza (min/max es idempotente)
155
+ lo_pages, hi_pages = [], []
156
+ for pack in packs:
157
+ seen, lo, hi = set(), 0, 0
158
+ for c in pack.get('criteria', []):
159
+ if c.get('status') == 'agent-verified':
160
+ continue
161
+ code = c['criterion'].split(' ')[0]
162
+ if code in seen:
163
+ continue
164
+ seen.add(code)
165
+ mins = c.get('effort', {}).get('minutes')
166
+ if isinstance(mins, (list, tuple)) and len(mins) == 2:
167
+ lo += min(mins)
168
+ hi += max(mins)
169
+ lo_pages.append(lo)
170
+ hi_pages.append(hi)
171
+
121
172
  report = {
122
- 'format': 'a11y-wcagem-report/1',
173
+ 'format': 'a11y-wcagem-report/2',
123
174
  'method': 'WCAG-EM 2.0 (W3C Group Note, 2026-07-23)',
124
175
  'product': plan['product'],
125
176
  'conformance_target': plan['conformance_target'],
@@ -132,6 +183,9 @@ def aggregate(plan, packs):
132
183
  'summary': {s: sum(1 for c in criteria if c['status'] == s)
133
184
  for s in _RANK},
134
185
  'effort_pending': effort,
186
+ 'inference': effort_inference(
187
+ lo_pages, hi_pages, seed=inference_seed,
188
+ projected_pages=plan.get('estimated_pages'), lang=lang),
135
189
  'packs': [{'sample': m['id'], 'type': m['type'],
136
190
  'sha256': p['sha256'], 'format': p.get('format')}
137
191
  for m, p in zip(plan['sample'], packs)],
@@ -156,20 +210,26 @@ def main(argv):
156
210
  ap.add_argument('--plan', required=True, help='evaluation plan JSON (scope + sample set)')
157
211
  ap.add_argument('--packs', nargs='+', required=True,
158
212
  help='evidence pack JSON per sample, in plan.sample order')
213
+ ap.add_argument('--lang', default='en', choices=['en', 'es'],
214
+ help='inference note language (report data stays English)')
159
215
  ap.add_argument('-o', '--out', default='wcagem-report.json')
160
216
  a = ap.parse_args(argv)
161
217
  plan = json.load(open(a.plan, encoding='utf-8'))
162
218
  packs = [json.load(open(p, encoding='utf-8')) for p in a.packs]
163
219
  try:
164
- report = aggregate(plan, packs)
220
+ report = aggregate(plan, packs, lang=a.lang)
165
221
  except ValueError as e:
166
222
  print(json.dumps({'error': str(e)}))
167
223
  return 2
168
224
  with open(a.out, 'w', encoding='utf-8') as f:
169
225
  json.dump(report, f, ensure_ascii=False, indent=1)
226
+ inf = report['inference']
170
227
  print(json.dumps({'report': a.out, 'sha256': report['sha256'],
171
228
  'criteria': len(report['criteria']),
172
- 'summary': report['summary']}, ensure_ascii=False))
229
+ 'summary': report['summary'],
230
+ 'effort_ci95_envelope_per_page': inf['ci95_mean_envelope'],
231
+ 'projection': inf.get('projection')},
232
+ ensure_ascii=False))
173
233
  return 0
174
234
 
175
235
 
@@ -87,7 +87,7 @@ try:
87
87
  except ImportError:
88
88
  ARIALIVE_JS = None # repo checkout: read the file
89
89
 
90
- VERSION = '5.23.0'
90
+ VERSION = '5.25.0'
91
91
 
92
92
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
93
93
  PARAM_ALIASES = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.23.0",
3
+ "version": "5.25.0",
4
4
  "description": "Zero-dependency WCAG 2.2 accessibility engine (34 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.",
5
5
  "license": "MIT",
6
6
  "repository": {