@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,536 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""A11Y Contrast Toolkit — shared core (CLI, skill and MCP). Bilingual es/en.
|
|
3
|
+
|
|
4
|
+
1. Flat color pair → ratios and 1.4.3 / 1.4.6 / 1.4.11 verdicts
|
|
5
|
+
2. Text over image → pixel-by-pixel sampling of the text area
|
|
6
|
+
|
|
7
|
+
Zero dependencies: Pillow if present, else `sips` (macOS); PPM always.
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
contrast.py pair "#ffffff" "#000000" [--lang es]
|
|
11
|
+
contrast.py image photo.jpg --text "#ffffff" [--region 120,40,420,90] [--sample 4] [--lang es]
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import re
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
import os
|
|
22
|
+
from . import a11yi18n
|
|
23
|
+
|
|
24
|
+
T = a11yi18n.pair('contrast') # locales/<lang>.json — community-editable
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _t(lang):
|
|
28
|
+
return T.get(lang, T['es'])
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------- colores ---
|
|
31
|
+
|
|
32
|
+
# Nombres CSS (X11/CSS Color Module Level 4), 148 entradas
|
|
33
|
+
_NAMES = '''
|
|
34
|
+
aliceblue:f0f8ff antiquewhite:faebd7 aqua:00ffff aquamarine:7fffd4 azure:f0ffff
|
|
35
|
+
beige:f5f5dc bisque:ffe4c4 black:000000 blanchedalmond:ffebcd blue:0000ff
|
|
36
|
+
blueviolet:8a2be2 brown:a52a2a burlywood:deb887 cadetblue:5f9ea0 chartreuse:7fff00
|
|
37
|
+
chocolate:d2691e coral:ff7f50 cornflowerblue:6495ed cornsilk:fff8dc crimson:dc143c
|
|
38
|
+
cyan:00ffff darkblue:00008b darkcyan:008b8b darkgoldenrod:b8860b darkgray:a9a9a9
|
|
39
|
+
darkgreen:006400 darkgrey:a9a9a9 darkkhaki:bdb76b darkmagenta:8b008b
|
|
40
|
+
darkolivegreen:556b2f darkorange:ff8c00 darkorchid:9932cc darkred:8b0000
|
|
41
|
+
darksalmon:e9967a darkseagreen:8fbc8f darkslateblue:483d8b darkslategray:2f4f4f
|
|
42
|
+
darkslategrey:2f4f4f darkturquoise:00ced1 darkviolet:9400d3 deeppink:ff1493
|
|
43
|
+
deepskyblue:00bfff dimgray:696969 dimgrey:696969 dodgerblue:1e90ff firebrick:b22222
|
|
44
|
+
floralwhite:fffaf0 forestgreen:228b22 fuchsia:ff00ff gainsboro:dcdcdc ghostwhite:f8f8ff
|
|
45
|
+
gold:ffd700 goldenrod:daa520 gray:808080 green:008000 greenyellow:adff2f grey:808080
|
|
46
|
+
honeydew:f0fff0 hotpink:ff69b4 indianred:cd5c5c indigo:4b0082 ivory:fffff0
|
|
47
|
+
khaki:f0e68c lavender:e6e6fa lavenderblush:fff0f5 lawngreen:7cfc00
|
|
48
|
+
lemonchiffon:fffacd lightblue:add8e6 lightcoral:f08080 lightcyan:e0ffff
|
|
49
|
+
lightgoldenrodyellow:fafad2 lightgray:d3d3d3 lightgreen:90ee90 lightgrey:d3d3d3
|
|
50
|
+
lightpink:ffb6c1 lightsalmon:ffa07a lightseagreen:20b2aa lightskyblue:87cefa
|
|
51
|
+
lightslategray:778899 lightslategrey:778899 lightsteelblue:b0c4de lightyellow:ffffe0
|
|
52
|
+
lime:00ff00 limegreen:32cd32 linen:faf0e6 magenta:ff00ff maroon:800000
|
|
53
|
+
mediumaquamarine:66cdaa mediumblue:0000cd mediumorchid:ba55d3 mediumpurple:9370db
|
|
54
|
+
mediumseagreen:3cb371 mediumslateblue:7b68ee mediumspringgreen:00fa9a
|
|
55
|
+
mediumturquoise:48d1cc mediumvioletred:c71585 midnightblue:191970 mintcream:f5fffa
|
|
56
|
+
mistyrose:ffe4e1 moccasin:ffe4b5 navajowhite:ffdead navy:000080 oldlace:fdf5e6
|
|
57
|
+
olive:808000 olivedrab:6b8e23 orange:ffa500 orangered:ff4500 orchid:da70d6
|
|
58
|
+
palegoldenrod:eee8aa palegreen:98fb98 paleturquoise:afeeee palevioletred:db7093
|
|
59
|
+
papayawhip:ffefd5 peachpuff:ffdab9 peru:cd853f pink:ffc0cb plum:dda0dd
|
|
60
|
+
powderblue:b0e0e6 purple:800080 rebeccapurple:663399 red:ff0000 rosybrown:bc8f8f
|
|
61
|
+
royalblue:4169e1 saddlebrown:8b4513 salmon:fa8072 sandybrown:f4a460 seagreen:2e8b57
|
|
62
|
+
seashell:fff5ee sienna:a0522d silver:c0c0c0 skyblue:87ceeb slateblue:6a5acd
|
|
63
|
+
slategray:708090 slategrey:708090 snow:fffafa springgreen:00ff7f steelblue:4682b4
|
|
64
|
+
tan:d2b48c teal:008080 thistle:d8bfd8 tomato:ff6347 turquoise:40e0d0 violet:ee82ee
|
|
65
|
+
wheat:f5deb3 white:ffffff whitesmoke:f5f5f5 yellow:ffff00 yellowgreen:9acd32
|
|
66
|
+
'''
|
|
67
|
+
COLOR_NAMES = {n: h for n, h in (par.split(':') for par in _NAMES.split())}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _hsl_a_rgb(h, s, l):
|
|
71
|
+
"""h [0,360), s/l [0,1] → (r,g,b) 0-255."""
|
|
72
|
+
h = (h % 360) / 360.0
|
|
73
|
+
def f(n):
|
|
74
|
+
k = (n + h * 12) % 12
|
|
75
|
+
a = s * min(l, 1 - l)
|
|
76
|
+
return round(255 * (l - a * max(-1, min(k - 3, 9 - k, 1))))
|
|
77
|
+
return f(0), f(8), f(4)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parse_color(s):
|
|
81
|
+
"""'#rgb' | '#rrggbb' | '#rrggbbaa' | rgb()/rgba() | hsl()/hsla() | nombre CSS
|
|
82
|
+
→ dict r,g,b (y 'a' si hay alfa). Acepta comas o espacios como separadores.
|
|
83
|
+
None si no válido."""
|
|
84
|
+
t = s.strip().lower()
|
|
85
|
+
m = re.fullmatch(r'#?([0-9a-f]{3})', t)
|
|
86
|
+
if m:
|
|
87
|
+
h = m.group(1)
|
|
88
|
+
return {'r': int(h[0] * 2, 16), 'g': int(h[1] * 2, 16), 'b': int(h[2] * 2, 16)}
|
|
89
|
+
m = re.fullmatch(r'#?([0-9a-f]{6})', t)
|
|
90
|
+
if m:
|
|
91
|
+
h = m.group(1)
|
|
92
|
+
return {'r': int(h[0:2], 16), 'g': int(h[2:4], 16), 'b': int(h[4:6], 16)}
|
|
93
|
+
m = re.fullmatch(r'#?([0-9a-f]{8})', t)
|
|
94
|
+
if m:
|
|
95
|
+
h = m.group(1)
|
|
96
|
+
return {'r': int(h[0:2], 16), 'g': int(h[2:4], 16), 'b': int(h[4:6], 16),
|
|
97
|
+
'a': int(h[6:8], 16) / 255.0}
|
|
98
|
+
# rgb()/rgba()/hsl()/hsla() con comas o espacios (sintaxis CSS moderna)
|
|
99
|
+
m = re.fullmatch(r'(rgba?|hsla?)\(\s*([^)]*)\)', t)
|
|
100
|
+
if m:
|
|
101
|
+
body = m.group(2)
|
|
102
|
+
alfa_ext = None
|
|
103
|
+
if '/' in body:
|
|
104
|
+
body, alfa_ext = re.split(r'\s*/\s*', body, 1)
|
|
105
|
+
parts = [p for p in (x.strip() for x in re.split(r'[\s,]+', body)) if p]
|
|
106
|
+
kind, v = m.group(1), parts
|
|
107
|
+
if kind.startswith('rgb'):
|
|
108
|
+
if len(v) < 3:
|
|
109
|
+
return None
|
|
110
|
+
def _channel(x):
|
|
111
|
+
if x.endswith('%'):
|
|
112
|
+
return max(0, min(255, round(float(x[:-1]) * 2.55)))
|
|
113
|
+
return max(0, min(255, int(float(x))))
|
|
114
|
+
c = {'r': _channel(v[0]), 'g': _channel(v[1]), 'b': _channel(v[2])}
|
|
115
|
+
if len(v) >= 4:
|
|
116
|
+
c['a'] = max(0.0, min(1.0, float(v[3].rstrip('%')) / (100 if v[3].endswith('%') else 1)))
|
|
117
|
+
elif alfa_ext:
|
|
118
|
+
c['a'] = max(0.0, min(1.0, float(alfa_ext.strip().rstrip('%')) / (100 if alfa_ext.strip().endswith('%') else 1)))
|
|
119
|
+
return c
|
|
120
|
+
if len(v) < 3:
|
|
121
|
+
return None
|
|
122
|
+
h_ = float(v[0].rstrip('deg')) % 360
|
|
123
|
+
s_ = max(0.0, min(1.0, float(v[1].rstrip('%')) / 100.0))
|
|
124
|
+
l_ = max(0.0, min(1.0, float(v[2].rstrip('%')) / 100.0))
|
|
125
|
+
r, g, b = _hsl_a_rgb(h_, s_, l_)
|
|
126
|
+
c = {'r': max(0, min(255, r)), 'g': max(0, min(255, g)),
|
|
127
|
+
'b': max(0, min(255, b))}
|
|
128
|
+
if len(v) >= 4:
|
|
129
|
+
c['a'] = max(0.0, min(1.0, float(v[3].rstrip('%')) / (100 if v[3].endswith('%') else 1)))
|
|
130
|
+
return c
|
|
131
|
+
if t in COLOR_NAMES:
|
|
132
|
+
h = COLOR_NAMES[t]
|
|
133
|
+
return {'r': int(h[0:2], 16), 'g': int(h[2:4], 16), 'b': int(h[4:6], 16)}
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
WHITE = {'r': 255, 'g': 255, 'b': 255}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def composite(c, bg):
|
|
141
|
+
"""Compone c (con alfa) sobre fondo opaco → dict opaco r,g,b."""
|
|
142
|
+
a = c.get('a', 1.0)
|
|
143
|
+
return {'r': round(c['r'] * a + bg['r'] * (1 - a)),
|
|
144
|
+
'g': round(c['g'] * a + bg['g'] * (1 - a)),
|
|
145
|
+
'b': round(c['b'] * a + bg['b'] * (1 - a))}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def hexs(c):
|
|
149
|
+
# defensa: canales fuera de [0,255] (parse malformado) → acotados, hex válido
|
|
150
|
+
return '#%02x%02x%02x' % (max(0, min(255, c['r'])),
|
|
151
|
+
max(0, min(255, c['g'])),
|
|
152
|
+
max(0, min(255, c['b'])))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _lin(v):
|
|
156
|
+
c = v / 255.0
|
|
157
|
+
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def luminance(c):
|
|
161
|
+
return 0.2126 * _lin(c['r']) + 0.7152 * _lin(c['g']) + 0.0722 * _lin(c['b'])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def ratio(fg, bg):
|
|
165
|
+
l1, l2 = sorted((luminance(fg), luminance(bg)), reverse=True)
|
|
166
|
+
return (l1 + 0.05) / (l2 + 0.05)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def verdicts(r, lang='en'):
|
|
170
|
+
return [
|
|
171
|
+
{'criterion': n, 'level': lvl, 'threshold': u, 'passes': r >= u}
|
|
172
|
+
for n, lvl, u in _t(lang)['criteria']
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def suggest(fg, bg, target=4.5, lang='en'):
|
|
177
|
+
"""Color opaco más cercano (distancia RGB) al original que cumple el objetivo.
|
|
178
|
+
|
|
179
|
+
Prueba mezclas hacia blanco y hacia negro y elige la de menor distancia real,
|
|
180
|
+
con búsqueda fina de 400 pasos."""
|
|
181
|
+
t9 = _t(lang)
|
|
182
|
+
fg0 = composite(fg, bg) if fg.get('a', 1) < 1 else fg
|
|
183
|
+
if ratio(fg0, bg) >= target:
|
|
184
|
+
return None
|
|
185
|
+
best = None
|
|
186
|
+
for white in (True, False):
|
|
187
|
+
o = (255, 255, 255) if white else (0, 0, 0)
|
|
188
|
+
for step in range(1, 401):
|
|
189
|
+
tt = step / 400
|
|
190
|
+
c = {'r': round(fg0['r'] + (o[0] - fg0['r']) * tt),
|
|
191
|
+
'g': round(fg0['g'] + (o[1] - fg0['g']) * tt),
|
|
192
|
+
'b': round(fg0['b'] + (o[2] - fg0['b']) * tt)}
|
|
193
|
+
if ratio(c, bg) >= target:
|
|
194
|
+
d = (c['r'] - fg0['r']) ** 2 + (c['g'] - fg0['g']) ** 2 + (c['b'] - fg0['b']) ** 2
|
|
195
|
+
if best is None or d < best['_d']:
|
|
196
|
+
best = {'color': hexs(c), 'ratio': round(ratio(c, bg), 2),
|
|
197
|
+
'action': t9['lightening'] if white else t9['darkening'],
|
|
198
|
+
'step': tt, '_d': d}
|
|
199
|
+
break
|
|
200
|
+
if best:
|
|
201
|
+
del best['_d']
|
|
202
|
+
return best
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def pair(fg_s, bg_s, with_suggestion=True, lang='en'):
|
|
206
|
+
fg, bg = parse_color(fg_s), parse_color(bg_s)
|
|
207
|
+
if not fg or not bg:
|
|
208
|
+
return {'error': _t(lang)['invalid_color']}
|
|
209
|
+
alpha_note = None
|
|
210
|
+
if bg.get('a', 1) < 1:
|
|
211
|
+
bg = composite(bg, WHITE)
|
|
212
|
+
alpha_note = hexs(bg)
|
|
213
|
+
if fg.get('a', 1) < 1:
|
|
214
|
+
fg = composite(fg, bg)
|
|
215
|
+
alpha_note = hexs(fg)
|
|
216
|
+
r = ratio(fg, bg)
|
|
217
|
+
out = {
|
|
218
|
+
'text': hexs(fg), 'background': hexs(bg),
|
|
219
|
+
'ratio': round(r, 2),
|
|
220
|
+
'verdicts': verdicts(r, lang),
|
|
221
|
+
}
|
|
222
|
+
if alpha_note:
|
|
223
|
+
out['effective_color'] = alpha_note
|
|
224
|
+
if with_suggestion and r < 4.5:
|
|
225
|
+
s = suggest(fg, bg, 4.5, lang)
|
|
226
|
+
if s:
|
|
227
|
+
out['aa_suggestion'] = s
|
|
228
|
+
return out
|
|
229
|
+
|
|
230
|
+
# ---------------------------------------------------------------- imagen ----
|
|
231
|
+
|
|
232
|
+
def _load_ppm(path):
|
|
233
|
+
with open(path, 'rb') as f:
|
|
234
|
+
data = f.read()
|
|
235
|
+
if not data.startswith(b'P6'):
|
|
236
|
+
raise ValueError('no es PPM P6')
|
|
237
|
+
pos = 2
|
|
238
|
+
fields = []
|
|
239
|
+
while len(fields) < 3:
|
|
240
|
+
while pos < len(data) and data[pos:pos + 1].isspace():
|
|
241
|
+
if data[pos:pos + 2] == b'\r\n':
|
|
242
|
+
pos += 2
|
|
243
|
+
else:
|
|
244
|
+
pos += 1
|
|
245
|
+
if data[pos:pos + 1] == b'#':
|
|
246
|
+
while data[pos:pos + 1] not in (b'\n', b''):
|
|
247
|
+
pos += 1
|
|
248
|
+
continue
|
|
249
|
+
start = pos
|
|
250
|
+
while pos < len(data) and not data[pos:pos + 1].isspace():
|
|
251
|
+
pos += 1
|
|
252
|
+
fields.append(int(data[start:pos]))
|
|
253
|
+
# tras maxval: saltar UN fin de línea (\n o \r\n) — con CRLF un solo
|
|
254
|
+
# byte desplazaría TODOS los píxeles (salida plausible y falsa)
|
|
255
|
+
if data[pos:pos + 2] == b'\r\n':
|
|
256
|
+
pos += 2
|
|
257
|
+
else:
|
|
258
|
+
pos += 1
|
|
259
|
+
w, h, _maxv = fields
|
|
260
|
+
return w, h, data[pos:pos + w * h * 3]
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def load_image(path):
|
|
264
|
+
# .ppm → parser propio: PIL desplaza los píxeles cuando el header lleva
|
|
265
|
+
# CRLF (el \n del fin de línea entra como primer byte de la imagen)
|
|
266
|
+
if path.lower().endswith('.ppm'):
|
|
267
|
+
return _load_ppm(path)
|
|
268
|
+
try:
|
|
269
|
+
from PIL import Image
|
|
270
|
+
im = Image.open(path).convert('RGB')
|
|
271
|
+
return im.width, im.height, im.tobytes()
|
|
272
|
+
except ImportError:
|
|
273
|
+
pass
|
|
274
|
+
if not shutil.which('sips'):
|
|
275
|
+
raise RuntimeError('need Pillow (pip install pillow) or macOS (sips)')
|
|
276
|
+
with tempfile.NamedTemporaryFile(suffix='.ppm', delete=False) as tf:
|
|
277
|
+
tmp = tf.name
|
|
278
|
+
try:
|
|
279
|
+
subprocess.run(['sips', '-s', 'format', 'ppm', path, '--out', tmp],
|
|
280
|
+
check=True, capture_output=True)
|
|
281
|
+
return _load_ppm(tmp)
|
|
282
|
+
finally:
|
|
283
|
+
os.unlink(tmp)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _percentile(vals, p):
|
|
287
|
+
if not vals:
|
|
288
|
+
return None
|
|
289
|
+
s = sorted(vals)
|
|
290
|
+
k = min(len(s) - 1, max(0, int(round((p / 100.0) * (len(s) - 1)))))
|
|
291
|
+
return s[k]
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# ---------------------------------------------------------------- PNG puro ---
|
|
295
|
+
# Playwright devuelve capturas PNG; sin Pillow no hay forma de leerlas, así que
|
|
296
|
+
# el core decodifica PNG por sí mismo (zero-dep): IHDR/PLTE/IEND, filtros 0-4,
|
|
297
|
+
# color types 0/2/3/6 a 8 bits. Lo que no sepa → ValueError con mensaje claro.
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def decode_png(data):
|
|
301
|
+
"""Bytes PNG → (ancho, alto, bytes RGB). Sin dependencias.
|
|
302
|
+
|
|
303
|
+
Soporta color types 0 (gris), 2 (RGB), 3 (paleta) y 6 (RGBA) a 8 bits;
|
|
304
|
+
el alfa se compone sobre blanco (las capturas de navegador son opacas).
|
|
305
|
+
Lanza ValueError si el PNG está fuera de ese soporte (p. ej. 16 bits)."""
|
|
306
|
+
import struct
|
|
307
|
+
import zlib
|
|
308
|
+
if data[:8] != b'\x89PNG\r\n\x1a\n':
|
|
309
|
+
raise ValueError('not a PNG file')
|
|
310
|
+
pos, idat, w, h, bd, ct, plte = 8, b'', 0, 0, 0, 0, None
|
|
311
|
+
while pos < len(data):
|
|
312
|
+
ln = struct.unpack('>I', data[pos:pos + 4])[0]
|
|
313
|
+
kind = data[pos + 4:pos + 8]
|
|
314
|
+
body = data[pos + 8:pos + 8 + ln]
|
|
315
|
+
if kind == b'IHDR':
|
|
316
|
+
w, h, bd, ct = struct.unpack('>IIBB', body[:10])
|
|
317
|
+
elif kind == b'IDAT':
|
|
318
|
+
idat += body
|
|
319
|
+
elif kind == b'PLTE':
|
|
320
|
+
plte = body
|
|
321
|
+
elif kind == b'IEND':
|
|
322
|
+
break
|
|
323
|
+
pos += 12 + ln
|
|
324
|
+
if bd != 8:
|
|
325
|
+
raise ValueError(f'PNG bit depth {bd} unsupported (8-bit only)')
|
|
326
|
+
channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(ct)
|
|
327
|
+
if channels is None:
|
|
328
|
+
raise ValueError(f'PNG color type {ct} unsupported')
|
|
329
|
+
if ct == 3 and not plte:
|
|
330
|
+
raise ValueError('PNG palette without PLTE chunk')
|
|
331
|
+
raw = zlib.decompress(idat)
|
|
332
|
+
step = w * channels
|
|
333
|
+
rows = []
|
|
334
|
+
for y in range(h):
|
|
335
|
+
base = y * (step + 1)
|
|
336
|
+
filter = raw[base]
|
|
337
|
+
f = bytearray(raw[base + 1:base + 1 + step])
|
|
338
|
+
prev = rows[-1] if rows else bytearray(step)
|
|
339
|
+
for i in range(step):
|
|
340
|
+
a = f[i - channels] if i >= channels else 0
|
|
341
|
+
b = prev[i]
|
|
342
|
+
c = prev[i - channels] if i >= channels else 0
|
|
343
|
+
if filter == 1:
|
|
344
|
+
f[i] = (f[i] + a) & 255
|
|
345
|
+
elif filter == 2:
|
|
346
|
+
f[i] = (f[i] + b) & 255
|
|
347
|
+
elif filter == 3:
|
|
348
|
+
f[i] = (f[i] + ((a + b) >> 1)) & 255
|
|
349
|
+
elif filter == 4:
|
|
350
|
+
p = a + b - c
|
|
351
|
+
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
|
352
|
+
pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
|
|
353
|
+
f[i] = (f[i] + pr) & 255
|
|
354
|
+
rows.append(f)
|
|
355
|
+
out = bytearray(w * h * 3)
|
|
356
|
+
for y in range(h):
|
|
357
|
+
f = rows[y]
|
|
358
|
+
for x in range(w):
|
|
359
|
+
o = x * channels
|
|
360
|
+
if ct == 0:
|
|
361
|
+
r = g = b = f[o]
|
|
362
|
+
elif ct == 2:
|
|
363
|
+
r, g, b = f[o], f[o + 1], f[o + 2]
|
|
364
|
+
elif ct == 3:
|
|
365
|
+
i = f[o] * 3
|
|
366
|
+
r, g, b = plte[i], plte[i + 1], plte[i + 2]
|
|
367
|
+
else: # ct 6
|
|
368
|
+
r, g, b, al = f[o], f[o + 1], f[o + 2], f[o + 3]
|
|
369
|
+
if al < 255:
|
|
370
|
+
r = (r * al + 255 * (255 - al)) // 255
|
|
371
|
+
g = (g * al + 255 * (255 - al)) // 255
|
|
372
|
+
b = (b * al + 255 * (255 - al)) // 255
|
|
373
|
+
p = (y * w + x) * 3
|
|
374
|
+
out[p], out[p + 1], out[p + 2] = r, g, b
|
|
375
|
+
return w, h, bytes(out)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def sample_rgb(w, h, rgb, text_color, sample=4, exclude_text=False):
|
|
379
|
+
"""Núcleo de muestreo compartido: bytes RGB + color de texto opaco → métricas.
|
|
380
|
+
|
|
381
|
+
excluir_texto=True salta los píxeles próximos al color del texto (distancia
|
|
382
|
+
RGB < 40): así, al capturar un elemento ENTERO (captura de navegador), se
|
|
383
|
+
mide el FONDO real y no el propio texto (que siempre fallaría 1:1). Cuando
|
|
384
|
+
se excluye >90% de la región no hay fondo medible → None.
|
|
385
|
+
Incluye la rejilla 3×3 de zona hostil cuando la región es ≥99×99."""
|
|
386
|
+
l_text = luminance(text_color)
|
|
387
|
+
tr, tg, tb = text_color['r'], text_color['g'], text_color['b']
|
|
388
|
+
ratios = []
|
|
389
|
+
excluded = 0
|
|
390
|
+
use_grid = w >= 99 and h >= 99
|
|
391
|
+
cells = [[0, 0] for _ in range(9)]
|
|
392
|
+
for j in range(0, h, sample):
|
|
393
|
+
row = j * w
|
|
394
|
+
cy = (j * 3) // h if use_grid else 0
|
|
395
|
+
for i in range(0, w, sample):
|
|
396
|
+
o = (row + i) * 3
|
|
397
|
+
if exclude_text and ((rgb[o] - tr) ** 2 + (rgb[o + 1] - tg) ** 2
|
|
398
|
+
+ (rgb[o + 2] - tb) ** 2) < 1600:
|
|
399
|
+
excluded += 1
|
|
400
|
+
continue
|
|
401
|
+
lpix = (0.2126 * _lin(rgb[o]) + 0.7152 * _lin(rgb[o + 1])
|
|
402
|
+
+ 0.0722 * _lin(rgb[o + 2]))
|
|
403
|
+
l1, l2 = (l_text, lpix) if l_text > lpix else (lpix, l_text)
|
|
404
|
+
r = (l1 + 0.05) / (l2 + 0.05)
|
|
405
|
+
ratios.append(r)
|
|
406
|
+
if use_grid:
|
|
407
|
+
cx = (i * 3) // w
|
|
408
|
+
cells[cy * 3 + cx][1] += 1
|
|
409
|
+
if r >= 4.5:
|
|
410
|
+
cells[cy * 3 + cx][0] += 1
|
|
411
|
+
if not ratios:
|
|
412
|
+
return None
|
|
413
|
+
if exclude_text and excluded / max(1, len(ratios) + excluded) > 0.9:
|
|
414
|
+
return None
|
|
415
|
+
passes45 = sum(1 for v in ratios if v >= 4.5)
|
|
416
|
+
passes30 = sum(1 for v in ratios if v >= 3.0)
|
|
417
|
+
out = {
|
|
418
|
+
'worst_ratio': round(min(ratios), 2),
|
|
419
|
+
'median_ratio': round(_percentile(ratios, 50), 2),
|
|
420
|
+
'p95_ratio': round(_percentile(ratios, 95), 2),
|
|
421
|
+
'area_passes_aa_normal_text_4_5': round(100.0 * passes45 / len(ratios), 1),
|
|
422
|
+
'area_passes_aa_min_3_0': round(100.0 * passes30 / len(ratios), 1),
|
|
423
|
+
'sampled_pixels': len(ratios),
|
|
424
|
+
}
|
|
425
|
+
if exclude_text:
|
|
426
|
+
out['excluded_text_pixels'] = excluded
|
|
427
|
+
if use_grid:
|
|
428
|
+
worst = min(range(9), key=lambda k: (cells[k][0] / cells[k][1]) if cells[k][1] else 1)
|
|
429
|
+
py_, px_ = worst // 3, worst % 3
|
|
430
|
+
out['worst_zone'] = {
|
|
431
|
+
'cell': f'{["top","middle","bottom"][py_]}-{["left","center","right"][px_]}',
|
|
432
|
+
'x': (w * px_) // 3, 'y': (h * py_) // 3,
|
|
433
|
+
'width': w // 3, 'height': h // 3,
|
|
434
|
+
'pct_passes_aa': round(100.0 * cells[worst][0] / cells[worst][1], 1) if cells[worst][1] else None,
|
|
435
|
+
}
|
|
436
|
+
return out
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def image_contrast(path, text_color, region=None, sample=4, lang='en'):
|
|
440
|
+
t9 = _t(lang)
|
|
441
|
+
c = parse_color(text_color)
|
|
442
|
+
if not c:
|
|
443
|
+
return {'error': t9['invalid_color']}
|
|
444
|
+
if c.get('a', 1) < 1:
|
|
445
|
+
return {'error': t9['opaque_text']}
|
|
446
|
+
if region:
|
|
447
|
+
try:
|
|
448
|
+
x, y, rw, rh = (int(v) for v in region.split(','))
|
|
449
|
+
except ValueError:
|
|
450
|
+
return {'error': t9['invalid_region']}
|
|
451
|
+
try:
|
|
452
|
+
w, h, rgb = load_image(path)
|
|
453
|
+
except Exception as e: # noqa: BLE001
|
|
454
|
+
return {'error': f'{t9["load_error"]}: {e}'}
|
|
455
|
+
if region:
|
|
456
|
+
x, y = max(0, x), max(0, y)
|
|
457
|
+
rw = min(rw, w - x)
|
|
458
|
+
rh = min(rh, h - y)
|
|
459
|
+
if rw <= 0 or rh <= 0:
|
|
460
|
+
return {'error': t9['region_outside']}
|
|
461
|
+
else:
|
|
462
|
+
x, y, rw, rh = 0, 0, w, h
|
|
463
|
+
|
|
464
|
+
sample = max(1, int(sample))
|
|
465
|
+
# Guardián de rendimiento: regiones gigantes aumentan el paso automáticamente.
|
|
466
|
+
budget = 2_000_000
|
|
467
|
+
if (rw // sample) * (rh // sample) > budget:
|
|
468
|
+
sample = max(sample, int(((rw * rh) / budget) ** 0.5) + 1)
|
|
469
|
+
clip = bytearray(rw * rh * 3)
|
|
470
|
+
for j in range(rh):
|
|
471
|
+
clip[j * rw * 3:(j + 1) * rw * 3] = rgb[(y + j) * w * 3 + x * 3:
|
|
472
|
+
(y + j) * w * 3 + (x + rw) * 3]
|
|
473
|
+
m = sample_rgb(rw, rh, bytes(clip), c, sample)
|
|
474
|
+
if not m:
|
|
475
|
+
return {'error': t9['no_pixels']}
|
|
476
|
+
|
|
477
|
+
out = {
|
|
478
|
+
'image': os.path.basename(path),
|
|
479
|
+
'text_color': hexs(c),
|
|
480
|
+
'region': {'x': x, 'y': y, 'width': rw, 'height': rh,
|
|
481
|
+
'sampled_pixels': m.pop('sampled_pixels'), 'step': sample},
|
|
482
|
+
'worst_ratio': m['worst_ratio'],
|
|
483
|
+
'median_ratio': m['median_ratio'],
|
|
484
|
+
'p95_ratio': m['p95_ratio'],
|
|
485
|
+
'area_passes_aa_normal_text_4_5': m['area_passes_aa_normal_text_4_5'],
|
|
486
|
+
'area_passes_aa_min_3_0': m['area_passes_aa_min_3_0'],
|
|
487
|
+
'interpretation': t9['interp'],
|
|
488
|
+
}
|
|
489
|
+
if 'worst_zone' in m:
|
|
490
|
+
out['worst_zone'] = m['worst_zone']
|
|
491
|
+
return out
|
|
492
|
+
|
|
493
|
+
# ---------------------------------------------------------------- CLI -------
|
|
494
|
+
|
|
495
|
+
def main(argv):
|
|
496
|
+
if len(argv) < 1 or argv[0] not in ('pair', 'image'):
|
|
497
|
+
print(__doc__)
|
|
498
|
+
return 1
|
|
499
|
+
lang = 'en'
|
|
500
|
+
flags = {}
|
|
501
|
+
positional = []
|
|
502
|
+
i = 1
|
|
503
|
+
while i < len(argv):
|
|
504
|
+
v = argv[i]
|
|
505
|
+
if v == '--lang' and i + 1 < len(argv):
|
|
506
|
+
lang = argv[i + 1]
|
|
507
|
+
i += 1
|
|
508
|
+
elif v in ('--region', '--sample', '--text'):
|
|
509
|
+
if i + 1 >= len(argv):
|
|
510
|
+
print(f'missing value for {v}')
|
|
511
|
+
return 1
|
|
512
|
+
flags[v] = argv[i + 1]
|
|
513
|
+
i += 1
|
|
514
|
+
elif v == '--suggest':
|
|
515
|
+
flags['--suggest'] = True
|
|
516
|
+
else:
|
|
517
|
+
positional.append(v)
|
|
518
|
+
i += 1
|
|
519
|
+
if argv[0] == 'pair':
|
|
520
|
+
if len(positional) < 2:
|
|
521
|
+
print('usage: contrast.py pair "#text" "#background" [--lang es|en]')
|
|
522
|
+
return 1
|
|
523
|
+
res = pair(positional[0], positional[1], with_suggestion=True, lang=lang)
|
|
524
|
+
else:
|
|
525
|
+
if not positional or '--text' not in flags:
|
|
526
|
+
print('usage: contrast.py image photo.jpg --text "#ffffff" [--region x,y,w,h] [--sample N] [--lang es|en]')
|
|
527
|
+
return 1
|
|
528
|
+
res = image_contrast(positional[0], flags['--text'],
|
|
529
|
+
region=flags.get('--region'),
|
|
530
|
+
sample=flags.get('--sample', 4), lang=lang)
|
|
531
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
532
|
+
return 0
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
if __name__ == '__main__':
|
|
536
|
+
sys.exit(main(sys.argv[1:]))
|