captchakraken 4.2.0 → 5.0.0-beta.42
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/README.md +0 -1
- package/dist/index.d.ts +1 -1
- package/dist/kinds.d.ts +1 -0
- package/dist/kinds.js +1 -0
- package/dist/playwright-types.d.ts +4 -0
- package/dist/puppeteer-adapter.d.ts +2 -0
- package/dist/puppeteer-adapter.js +34 -2
- package/dist/selectors.d.ts +22 -11
- package/dist/selectors.js +9 -19
- package/dist/solver.d.ts +49 -4
- package/dist/solver.js +177 -47
- package/package.json +2 -2
- package/python/AGENTS.md +5 -4
- package/python/README.md +3 -6
- package/python/pyproject.toml +6 -9
- package/python/src/captchakraken/__init__.py +1 -1
- package/python/src/captchakraken/captchakraken.config.json +43 -9
- package/python/src/captchakraken/cli.py +2 -47
- package/python/src/captchakraken/config.py +0 -4
- package/python/src/captchakraken/kinds.py +1 -0
- package/python/src/captchakraken/models.json +15 -14
- package/python/src/captchakraken/page_solver.py +168 -49
- package/python/src/captchakraken/pointer/__init__.py +7 -9
- package/python/src/captchakraken/pointer/elements.py +1 -1
- package/python/src/captchakraken/pointer/server.py +13 -17
- package/python/src/captchakraken/pointer/service.py +35 -324
- package/python/src/captchakraken/prompts.py +3 -4
- package/python/src/captchakraken/selectors.py +19 -17
- package/python/src/captchakraken/selfhost.py +9 -16
- package/python/src/captchakraken/server_manager.py +0 -4
- package/python/src/captchakraken/solver.py +4 -25
- package/python/src/captchakraken/tool_calls/find_checkbox.py +150 -13
- package/python/src/captchakraken/tool_calls/find_grid.py +6 -132
- package/python/src/captchakraken/updater.py +57 -27
- package/python/src/captchakraken/pointer/detector.py +0 -333
|
@@ -43,6 +43,9 @@ class VendorSelectors:
|
|
|
43
43
|
fresh: Optional[str] = None
|
|
44
44
|
# Inside the challenge frame: the pictures a board is made of; the driver waits for each to have painted.
|
|
45
45
|
images: Sequence[str] = ()
|
|
46
|
+
# Inside the challenge frame: the tiles of the board's grid, in reading order. Where each one is placed is read
|
|
47
|
+
# from the DOM, to click it and to watch it reload.
|
|
48
|
+
tiles: Sequence[str] = ()
|
|
46
49
|
# Inside the widget: the vendor's own submit control, tried after the generic text probes.
|
|
47
50
|
submit: Sequence[str] = ()
|
|
48
51
|
# Inside the challenge frame: verdict banners and what each means.
|
|
@@ -55,6 +58,12 @@ class VendorSelectors:
|
|
|
55
58
|
text_input: Sequence[str] = ()
|
|
56
59
|
# Inside the widget: the knob a slide must start on; a drag from the piece moves nothing.
|
|
57
60
|
slider_handle: Sequence[str] = ()
|
|
61
|
+
# Beside the widget (a sibling of it, or of its parent): a strip the vendor draws outside the widget element that
|
|
62
|
+
# every board carries, such as Yidun's prompt and slider bar. The shot takes it in.
|
|
63
|
+
bar: Sequence[str] = ()
|
|
64
|
+
# Inside the widget's frame or a frame nested in it: the board itself, when the widget frame pads it (Proton's
|
|
65
|
+
# 682x600 frame around its 370x534 `.protonCaptchaContainer`). The shot is this element.
|
|
66
|
+
board: Sequence[str] = ()
|
|
58
67
|
# Inside the widget: the piece, measured to steer the slide and dragged directly when there is no track.
|
|
59
68
|
piece: Sequence[str] = ()
|
|
60
69
|
# Inside the widget: the control that deals a new puzzle, pressed when the model answers `refresh`.
|
|
@@ -74,7 +83,7 @@ ConfigSource = Union[str, "os.PathLike[str]", Mapping[str, Any]]
|
|
|
74
83
|
|
|
75
84
|
_FIELDS = {f.name: f for f in fields(VendorSelectors)}
|
|
76
85
|
_ONE = {"response", "checked", "accepted", "fresh"}
|
|
77
|
-
_GENERIC = ("submit_text", "text_input", "slider_handle", "piece")
|
|
86
|
+
_GENERIC = ("submit_text", "text_input", "slider_handle", "piece", "feedback")
|
|
78
87
|
|
|
79
88
|
|
|
80
89
|
class SelectorConfigError(ValueError):
|
|
@@ -140,28 +149,18 @@ def _entry(where: str, raw: Any, hosts_required: bool = True) -> VendorSelectors
|
|
|
140
149
|
return VendorSelectors(**kw)
|
|
141
150
|
|
|
142
151
|
|
|
143
|
-
#: The element detector a config may choose (see `pointer.detector`).
|
|
144
|
-
DETECTOR_CHOICES = ("auto", "standard", "lite")
|
|
145
|
-
|
|
146
|
-
|
|
147
152
|
class SelectorConfig(NamedTuple):
|
|
148
|
-
"""A loaded config: the caller's own entry, every vendor's in detection order, the generic fallbacks
|
|
149
|
-
element detector runs."""
|
|
153
|
+
"""A loaded config: the caller's own entry, every vendor's in detection order, and the generic fallbacks."""
|
|
150
154
|
custom: Optional[VendorSelectors]
|
|
151
155
|
vendors: Mapping[Vendor, VendorSelectors]
|
|
152
156
|
generic: Mapping[str, Tuple[str, ...]]
|
|
153
|
-
detector: str = "auto"
|
|
154
157
|
|
|
155
158
|
|
|
156
159
|
def _parse(name: str, doc: Mapping[str, Any], base: Optional[SelectorConfig]) -> SelectorConfig:
|
|
157
160
|
for key in doc:
|
|
161
|
+
# `detector` chose an element detector the client no longer has; a config written for one still loads.
|
|
158
162
|
if not key.startswith("_") and key not in ("detector", "custom", "vendors", "generic"):
|
|
159
|
-
raise SelectorConfigError(f"{name}: {key}: not a config key (
|
|
160
|
-
detector = base.detector if base else "auto"
|
|
161
|
-
if "detector" in doc:
|
|
162
|
-
if not isinstance(doc["detector"], str) or doc["detector"].strip().lower() not in DETECTOR_CHOICES:
|
|
163
|
-
raise SelectorConfigError(f"{name}: detector: {doc['detector']!r} is not one of {', '.join(DETECTOR_CHOICES)}")
|
|
164
|
-
detector = doc["detector"].strip().lower()
|
|
163
|
+
raise SelectorConfigError(f"{name}: {key}: not a config key (custom, vendors, generic)")
|
|
165
164
|
custom = base.custom if base else None
|
|
166
165
|
if "custom" in doc:
|
|
167
166
|
custom = None if doc["custom"] is None else _entry(f"{name}: custom", doc["custom"], hosts_required=False)
|
|
@@ -193,7 +192,7 @@ def _parse(name: str, doc: Mapping[str, Any], base: Optional[SelectorConfig]) ->
|
|
|
193
192
|
generic[key] = _strings(f"{name}: generic.{key}", value)
|
|
194
193
|
if base is None and set(generic) != set(_GENERIC):
|
|
195
194
|
raise SelectorConfigError(f"{name}: generic: missing {sorted(set(_GENERIC) - set(generic))}")
|
|
196
|
-
return SelectorConfig(custom, vendors, generic
|
|
195
|
+
return SelectorConfig(custom, vendors, generic)
|
|
197
196
|
|
|
198
197
|
|
|
199
198
|
def load_config(source: Optional[ConfigSource] = None) -> SelectorConfig:
|
|
@@ -257,8 +256,8 @@ class SelectorTable:
|
|
|
257
256
|
self.response: Sequence[str] = tuple(s.response for _, s in self.vendors if s.response)
|
|
258
257
|
self.accepted: Sequence[str] = tuple(s.accepted for _, s in self.vendors if s.accepted)
|
|
259
258
|
# A real Verify/Next/Submit/Skip/Confirm first; the vendor-named controls are fallbacks.
|
|
260
|
-
self.
|
|
261
|
-
|
|
259
|
+
self.submit_vendor: Sequence[str] = self._of_every_vendor("submit")
|
|
260
|
+
self.submit: Sequence[str] = (*map(submit_by_text, loaded.generic["submit_text"]), *self.submit_vendor)
|
|
262
261
|
# Vendor-named first, generic last: the driver takes the first visible match, and a generic selector
|
|
263
262
|
# reached before the vendor's own is how a captcha's answer ends up in a login form's username box.
|
|
264
263
|
self.text_input_vendor: Sequence[str] = self._of_every_vendor("text_input")
|
|
@@ -267,6 +266,9 @@ class SelectorTable:
|
|
|
267
266
|
self.slider_handle: Sequence[str] = (*self._of_every_vendor("slider_handle"), *loaded.generic["slider_handle"])
|
|
268
267
|
self.refresh: Sequence[str] = self._of_every_vendor("refresh")
|
|
269
268
|
self.piece: Sequence[str] = (*self._of_every_vendor("piece"), *loaded.generic["piece"])
|
|
269
|
+
# The verdict messages a widget shows over its board: every vendor's banners, then the generic ones.
|
|
270
|
+
self.feedback: Sequence[str] = (*(sel for _, v in self.vendors for sel, _kind in v.banners),
|
|
271
|
+
*loaded.generic["feedback"])
|
|
270
272
|
|
|
271
273
|
def _of_every_vendor(self, key: str) -> Sequence[str]:
|
|
272
274
|
assert key in {f.name for f in fields(VendorSelectors)}
|
|
@@ -20,9 +20,6 @@ from typing import Callable, List, NamedTuple, Optional, Sequence
|
|
|
20
20
|
|
|
21
21
|
from . import __version__, config, server_manager
|
|
22
22
|
|
|
23
|
-
DETECTOR_REPO = "CaptchaKraken/CaptchaKrakenV2-CNN-large"
|
|
24
|
-
DETECTOR_FILE = "detector_r18.pt"
|
|
25
|
-
|
|
26
23
|
ALWAYS_ON = "always"
|
|
27
24
|
FIRST_SOLVE = "first-solve"
|
|
28
25
|
|
|
@@ -241,18 +238,15 @@ def install_client(python: Path, extra: str = "") -> None:
|
|
|
241
238
|
|
|
242
239
|
_DOWNLOAD = """
|
|
243
240
|
import sys
|
|
244
|
-
from huggingface_hub import
|
|
241
|
+
from huggingface_hub import snapshot_download
|
|
245
242
|
print(snapshot_download(sys.argv[1]))
|
|
246
|
-
print(hf_hub_download(sys.argv[2], sys.argv[3]))
|
|
247
243
|
"""
|
|
248
244
|
|
|
249
245
|
|
|
250
|
-
def download(python: Path, repo: str) ->
|
|
251
|
-
"""
|
|
252
|
-
out = subprocess.run([str(python), "-c", _DOWNLOAD, repo,
|
|
253
|
-
|
|
254
|
-
model_path, detector = out.stdout.strip().splitlines()[-2:]
|
|
255
|
-
return model_path, detector
|
|
246
|
+
def download(python: Path, repo: str) -> str:
|
|
247
|
+
"""The model directory. Stored as a path so a server never asks the Hub again."""
|
|
248
|
+
out = subprocess.run([str(python), "-c", _DOWNLOAD, repo], stdout=subprocess.PIPE, text=True, check=True)
|
|
249
|
+
return out.stdout.strip().splitlines()[-1]
|
|
256
250
|
|
|
257
251
|
|
|
258
252
|
def free_port(start: int = 8000) -> int:
|
|
@@ -267,13 +261,12 @@ def free_port(start: int = 8000) -> int:
|
|
|
267
261
|
raise RuntimeError(f"No free port between {start} and {start + 99}.")
|
|
268
262
|
|
|
269
263
|
|
|
270
|
-
def settings(choice: Choice, model_path: str,
|
|
264
|
+
def settings(choice: Choice, model_path: str, saved: dict) -> dict:
|
|
271
265
|
small = choice.gpu.total_mib < SMALL_CARD_MIB
|
|
272
266
|
return {
|
|
273
267
|
"model": choice.model.repo,
|
|
274
268
|
"title": choice.model.title,
|
|
275
269
|
"model_path": model_path,
|
|
276
|
-
"detector": detector,
|
|
277
270
|
"gpu": choice.gpu.index,
|
|
278
271
|
"gpu_name": choice.gpu.name,
|
|
279
272
|
"startup": choice.startup,
|
|
@@ -332,10 +325,10 @@ def install(choice: Choice, saved: dict) -> dict:
|
|
|
332
325
|
python = make_venv(config.runtime_dir())
|
|
333
326
|
install_client(python, "[serve]")
|
|
334
327
|
|
|
335
|
-
_step(f"Downloading {choice.model.title}
|
|
336
|
-
model_path
|
|
328
|
+
_step(f"Downloading {choice.model.title}")
|
|
329
|
+
model_path = download(python, choice.model.repo)
|
|
337
330
|
|
|
338
|
-
values = settings(choice, model_path,
|
|
331
|
+
values = settings(choice, model_path, saved)
|
|
339
332
|
write_settings(values)
|
|
340
333
|
config.selfhost.cache_clear()
|
|
341
334
|
|
|
@@ -88,14 +88,10 @@ def build_serve_command() -> "list[str]":
|
|
|
88
88
|
from . import prompts
|
|
89
89
|
|
|
90
90
|
if prompts.resolve(config.lora_adapter()).pointer:
|
|
91
|
-
detector = config.pointer_detector()
|
|
92
|
-
if not detector:
|
|
93
|
-
raise RuntimeError("No detector is set up for the pointer server. Run: captchakraken fetch")
|
|
94
91
|
capture = config.max_cudagraph_capture_size()
|
|
95
92
|
return [
|
|
96
93
|
_serve_python(), "-m", "captchakraken.pointer.server",
|
|
97
94
|
"--model", config.serve_model(),
|
|
98
|
-
"--detector", detector,
|
|
99
95
|
"--host", os.getenv("CAPTCHA_POINTER_HOST", "127.0.0.1"),
|
|
100
96
|
"--port", str(config.port()),
|
|
101
97
|
"--gpu-memory-utilization", str(config.gpu_memory_utilization()),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Image in, actions out: the
|
|
1
|
+
"""Image in, actions out: the model, for one still or one recorded animation."""
|
|
2
2
|
|
|
3
3
|
import os
|
|
4
4
|
import sys
|
|
@@ -26,19 +26,12 @@ from .keyframes import KeyframeSet, extract_keyframes, number_for_source_index,
|
|
|
26
26
|
from .kinds import ActionKind, PixelAnswerKind, PromptFamily, RetryMode, Vendor
|
|
27
27
|
from .planner import ActionPlanner
|
|
28
28
|
from .tool_calls.find_checkbox import find_checkbox
|
|
29
|
-
from .tool_calls.find_grid import detect_selected_cells,
|
|
29
|
+
from .tool_calls.find_grid import detect_selected_cells, get_numbered_grid_overlay
|
|
30
30
|
|
|
31
31
|
DEBUG = os.getenv("CAPTCHA_DEBUG", "0") == "1"
|
|
32
32
|
# ~1.2% ≈ ±6px on a 512px challenge.
|
|
33
33
|
_PIXEL_BOX_HALF = float(os.getenv("CAPTCHA_PIXEL_BOX_HALF", "0.012"))
|
|
34
34
|
|
|
35
|
-
# The grid expert was trained on reCAPTCHA's 3x3 and 4x4 and hCaptcha's 3x3 and nothing else, so only those
|
|
36
|
-
# boards are asked as grids; every other vendor's grid goes to the pixel expert, which was trained on them. A
|
|
37
|
-
# caller that names no vendor (the CLI, a script) gets the expert for any 3x3 or 4x4, which is what those boards
|
|
38
|
-
# most often are.
|
|
39
|
-
GRID_CELL_SHAPES = {9: (3, 3), 16: (4, 4)}
|
|
40
|
-
VENDOR_GRID_CELLS: dict[Vendor, frozenset[int]] = {Vendor.HCAPTCHA: frozenset({9}), Vendor.RECAPTCHA: frozenset({9, 16})}
|
|
41
|
-
|
|
42
35
|
|
|
43
36
|
def _debug(message: str) -> None:
|
|
44
37
|
if DEBUG:
|
|
@@ -85,12 +78,6 @@ def _first_frame(path: str) -> Image.Image:
|
|
|
85
78
|
raise ValueError(f"Could not read video frame from {path}") from exc
|
|
86
79
|
|
|
87
80
|
|
|
88
|
-
def _grid_dims(n_cells: int, puzzle_source: Vendor = Vendor.UNKNOWN):
|
|
89
|
-
vendor = Vendor(puzzle_source)
|
|
90
|
-
allowed = frozenset(GRID_CELL_SHAPES) if vendor == Vendor.UNKNOWN else VENDOR_GRID_CELLS.get(vendor, frozenset())
|
|
91
|
-
return GRID_CELL_SHAPES[n_cells] if n_cells in allowed else None
|
|
92
|
-
|
|
93
|
-
|
|
94
81
|
class CaptchaSolver:
|
|
95
82
|
def __init__(self, model: Optional[str] = None, provider: str = "captchaKrakenApi",
|
|
96
83
|
api_key: Optional[str] = None, expert: Optional[PromptFamily] = None):
|
|
@@ -116,7 +103,6 @@ class CaptchaSolver:
|
|
|
116
103
|
img_w, img_h = self._image_size
|
|
117
104
|
|
|
118
105
|
if text_mode:
|
|
119
|
-
# A typed captcha's boxed glyphs are exactly the lattice find_grid looks for, so skip it.
|
|
120
106
|
try:
|
|
121
107
|
actions = self._solve_pixel(image_path, text_mode=True)
|
|
122
108
|
except ValueError as exc:
|
|
@@ -125,15 +111,8 @@ class CaptchaSolver:
|
|
|
125
111
|
return actions
|
|
126
112
|
raise UnsupportedCaptchaError("Could not read the text captcha")
|
|
127
113
|
|
|
128
|
-
#
|
|
129
|
-
#
|
|
130
|
-
grid_boxes = [] if self.planner.prompts.pointer else find_grid(image_path)
|
|
131
|
-
dims = _grid_dims(len(grid_boxes), puzzle_source) if grid_boxes else None
|
|
132
|
-
if dims:
|
|
133
|
-
return self._solve_grid(image_path, grid_boxes, dims[0], dims[1], retry_mode=retry_mode)
|
|
134
|
-
if grid_boxes:
|
|
135
|
-
_debug(f"find_grid returned {len(grid_boxes)} cells; not solving as a grid")
|
|
136
|
-
|
|
114
|
+
# A board alone carries no grid: its cells are read from the vendor's DOM (`PageSolver`, which asks the grid
|
|
115
|
+
# expert itself), so here a grid is a board like any other and its answer is points.
|
|
137
116
|
if not self.planner.prompts.pointer:
|
|
138
117
|
checkbox = find_checkbox(image_path)
|
|
139
118
|
if checkbox:
|
|
@@ -1,21 +1,158 @@
|
|
|
1
1
|
"""Where the driver clicks first, before any model runs: the tick box of a vendor's
|
|
2
|
-
checkbox widget,
|
|
3
|
-
|
|
2
|
+
checkbox widget, found in a screenshot of the widget with plain pixel arithmetic.
|
|
3
|
+
|
|
4
|
+
An unticked tick box is a square of one flat colour (white, near-black or the
|
|
5
|
+
widget's own background) closed in by an outline. So: mark every pixel whose
|
|
6
|
+
neighbours are the same shade, split those into connected regions, and keep a
|
|
7
|
+
region that fills a square, does not touch the screenshot's edge, and is big
|
|
8
|
+
next to the widget. A ticked box has a check mark inside, so it is not flat; a
|
|
9
|
+
spinner or a passed badge is round, so it does not fill its square; a letter
|
|
10
|
+
like ロ is a square too, but a small one. The largest square left is the box.
|
|
11
|
+
|
|
12
|
+
Neither a false positive nor a false negative raises. Measured on the widgets in
|
|
13
|
+
`tests/fixtures/checkbox/` (reCAPTCHA, hCaptcha, Turnstile and CaptchaFox, light
|
|
14
|
+
and dark, 1x to 2x, in a language none of the thresholds were tuned against).
|
|
15
|
+
"""
|
|
4
16
|
|
|
5
17
|
from typing import Optional, Tuple
|
|
6
18
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
MIN_SCORE = 0.6
|
|
19
|
+
import numpy as np
|
|
20
|
+
from PIL import Image
|
|
21
|
+
from scipy import ndimage
|
|
11
22
|
|
|
23
|
+
#: A pixel is flat when its grey level differs from its neighbours (two apart, on
|
|
24
|
+
#: each axis) by less than this. Outlines and antialiased glyph edges are well above it.
|
|
25
|
+
FLAT_GRADIENT = 24.0
|
|
26
|
+
#: The flat region must cover this share of its bounding square: a round spinner
|
|
27
|
+
#: or badge covers pi/4 of it.
|
|
28
|
+
MIN_FILL = 0.88
|
|
29
|
+
#: A box whose flat inside bleeds out through one low-contrast edge (hCaptcha's dark
|
|
30
|
+
#: theme: the bottom outline is nearly the panel's shade, so a ragged tail hangs off
|
|
31
|
+
#: the square and fill drops to 0.87) still has a solid core: most rows run nearly
|
|
32
|
+
#: edge to edge and almost every column is mostly filled. A disc does neither (about
|
|
33
|
+
#: 0.31 of its rows and 0.60 of its columns), nor does a spinner arc or a badge (0).
|
|
34
|
+
MIN_FILL_SOLID_CORE = 0.80
|
|
35
|
+
SOLID_ROW_FILL, MIN_SOLID_ROWS = 0.95, 0.65
|
|
36
|
+
SOLID_COL_FILL, MIN_SOLID_COLS = 0.80, 0.90
|
|
37
|
+
#: A tick box is painted one colour: its inside spans at most this many grey levels
|
|
38
|
+
#: (5th to 95th percentile). A smooth patch of photo (sky, asphalt, a pail's side)
|
|
39
|
+
#: is flat by the gradient test yet spans tens of levels; every tick box measured
|
|
40
|
+
#: spans 0.
|
|
41
|
+
MAX_SPREAD = 8.0
|
|
42
|
+
#: The box sits at the widget's leading edge (left, or right in a right-to-left
|
|
43
|
+
#: locale), inset from it by this many box-widths. A flat square further in, or one
|
|
44
|
+
#: flush against the edge, is part of a puzzle: a grid tile, a slider handle.
|
|
45
|
+
LEADING_INSET = (0.3, 1.2)
|
|
46
|
+
#: Around the box is the widget's own flat panel: on at least MIN_PANEL_SIDES sides,
|
|
47
|
+
#: PANEL_SHARE of a band just outside the outline sits within MAX_SPREAD grey levels
|
|
48
|
+
#: of the band's median. A share, not a range: a label or a test key's warning may
|
|
49
|
+
#: crowd a side (live 2026-11-13, German and Russian widgets). Every tick box
|
|
50
|
+
#: measured has a second side at least 0.87 flat; a drag card on a puzzle's tray
|
|
51
|
+
#: reaches 0.81, a cartoon-grid tile 0.60.
|
|
52
|
+
PANEL_BAND = (0.25, 0.30)
|
|
53
|
+
MIN_PANEL_SIDES = 2
|
|
54
|
+
PANEL_SHARE = 0.85
|
|
55
|
+
#: A tick box is painted a neutral shade (white, near-black, grey): the median of
|
|
56
|
+
#: max(R,G,B) - min(R,G,B) inside it is 0 on every widget measured. A puzzle's
|
|
57
|
+
#: flat coloured tile (a road piece, a red cube face) is well above this.
|
|
58
|
+
MAX_CHROMA = 24
|
|
59
|
+
#: An unticked box is empty: whatever its flat inside encloses (a check mark, a
|
|
60
|
+
#: drag card's drawing, a dot on a counting card) may cover at most this share of it.
|
|
61
|
+
MAX_ENCLOSED = 0.01
|
|
62
|
+
#: Width over height, both ways.
|
|
63
|
+
MAX_ASPECT = 1.25
|
|
64
|
+
#: The box's inside, as a share of the widget's height. Every tick box measured is
|
|
65
|
+
#: at least 0.16 of it; a letter of the widget's text is at most 0.06.
|
|
66
|
+
MIN_SIDE_OF_HEIGHT = 0.10
|
|
67
|
+
#: A flat region larger than this share of the height is a panel, not a box.
|
|
68
|
+
MAX_SIDE_OF_HEIGHT = 0.60
|
|
69
|
+
#: Nor more than this share of the width: the widest measured is hCaptcha's compact
|
|
70
|
+
#: card at 0.19, and a tile of a 4x4 puzzle grid is a quarter of its board.
|
|
71
|
+
MAX_SIDE_OF_WIDTH = 0.23
|
|
72
|
+
#: Smaller than this many pixels is a glyph or a speck, whatever the widget's size.
|
|
73
|
+
MIN_SIDE_PX = 12
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _flat(grey: np.ndarray) -> np.ndarray:
|
|
77
|
+
gx = np.zeros_like(grey)
|
|
78
|
+
gy = np.zeros_like(grey)
|
|
79
|
+
gx[:, 1:-1] = grey[:, 2:] - grey[:, :-2]
|
|
80
|
+
gy[1:-1] = grey[2:] - grey[:-2]
|
|
81
|
+
return np.hypot(gx, gy) < FLAT_GRADIENT
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _fills_its_square(mask: np.ndarray) -> bool:
|
|
85
|
+
fill = mask.mean()
|
|
86
|
+
if fill >= MIN_FILL:
|
|
87
|
+
return True
|
|
88
|
+
return (fill >= MIN_FILL_SOLID_CORE
|
|
89
|
+
and (mask.mean(axis=1) >= SOLID_ROW_FILL).mean() >= MIN_SOLID_ROWS
|
|
90
|
+
and (mask.mean(axis=0) >= SOLID_COL_FILL).mean() >= MIN_SOLID_COLS)
|
|
12
91
|
|
|
13
|
-
def find_checkbox(image_path: str) -> Optional[Tuple[int, int, int, int]]:
|
|
14
|
-
"""(x, y, w, h) of the most confident tick box in pixels, or None."""
|
|
15
|
-
from ..pointer.detector import detect_file
|
|
16
92
|
|
|
17
|
-
|
|
18
|
-
|
|
93
|
+
def _at_leading_edge(x0: int, x1: int, side: float, w_img: int) -> bool:
|
|
94
|
+
lo, hi = LEADING_INSET
|
|
95
|
+
return any(lo * side <= inset <= hi * side for inset in (x0, w_img - x1))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _sits_on_a_panel(grey: np.ndarray, x0: int, y0: int, x1: int, y1: int, side: float) -> bool:
|
|
99
|
+
o = max(2, int(round(PANEL_BAND[0] * side)))
|
|
100
|
+
k = max(3, int(round(PANEL_BAND[1] * side)))
|
|
101
|
+
X0, Y0, X1, Y1 = max(0, x0 - o), max(0, y0 - o), x1 + o, y1 + o
|
|
102
|
+
flat_sides = 0
|
|
103
|
+
for band in (grey[max(0, Y0 - k):Y0, X0:X1], grey[Y1:Y1 + k, X0:X1],
|
|
104
|
+
grey[Y0:Y1, max(0, X0 - k):X0], grey[Y0:Y1, X1:X1 + k]):
|
|
105
|
+
if band.size and np.mean(np.abs(band - np.median(band)) <= MAX_SPREAD) >= PANEL_SHARE:
|
|
106
|
+
flat_sides += 1
|
|
107
|
+
return flat_sides >= MIN_PANEL_SIDES
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def find_checkbox(image_path: str) -> Optional[Tuple[int, int, int, int]]:
|
|
111
|
+
"""(x, y, w, h) of the tick box in pixels, or None."""
|
|
112
|
+
try:
|
|
113
|
+
with Image.open(image_path) as im:
|
|
114
|
+
rgb = np.asarray(im.convert("RGB"), np.int16)
|
|
115
|
+
grey = np.asarray(Image.fromarray(rgb.astype(np.uint8)).convert("L"), np.float32)
|
|
116
|
+
except Exception:
|
|
117
|
+
return None
|
|
118
|
+
h_img, w_img = grey.shape
|
|
119
|
+
if h_img < 3 or w_img < 3:
|
|
120
|
+
return None
|
|
121
|
+
labels, _ = ndimage.label(_flat(grey))
|
|
122
|
+
best = None
|
|
123
|
+
for i, sl in enumerate(ndimage.find_objects(labels), 1):
|
|
124
|
+
if sl is None:
|
|
125
|
+
continue
|
|
126
|
+
y0, y1, x0, x1 = sl[0].start, sl[0].stop, sl[1].start, sl[1].stop
|
|
127
|
+
if y0 == 0 or x0 == 0 or y1 == h_img or x1 == w_img:
|
|
128
|
+
continue
|
|
129
|
+
w, h = x1 - x0, y1 - y0
|
|
130
|
+
side = (w + h) / 2
|
|
131
|
+
if min(w, h) < MIN_SIDE_PX or not 1 / MAX_ASPECT <= w / h <= MAX_ASPECT:
|
|
132
|
+
continue
|
|
133
|
+
if not MIN_SIDE_OF_HEIGHT * h_img <= side <= MAX_SIDE_OF_HEIGHT * h_img:
|
|
134
|
+
continue
|
|
135
|
+
if side > MAX_SIDE_OF_WIDTH * w_img:
|
|
136
|
+
continue
|
|
137
|
+
inside = labels[sl] == i
|
|
138
|
+
if not _fills_its_square(inside):
|
|
139
|
+
continue
|
|
140
|
+
if ndimage.binary_fill_holes(inside).sum() - inside.sum() > MAX_ENCLOSED * inside.size:
|
|
141
|
+
continue
|
|
142
|
+
shade = grey[sl][inside]
|
|
143
|
+
if np.percentile(shade, 95) - np.percentile(shade, 5) > MAX_SPREAD:
|
|
144
|
+
continue
|
|
145
|
+
paint = rgb[sl][inside]
|
|
146
|
+
if np.median(paint.max(axis=1) - paint.min(axis=1)) > MAX_CHROMA:
|
|
147
|
+
continue
|
|
148
|
+
if not _at_leading_edge(x0, x1, side, w_img) or not _sits_on_a_panel(grey, x0, y0, x1, y1, side):
|
|
149
|
+
continue
|
|
150
|
+
if best is None or side > best[0]:
|
|
151
|
+
best = (side, x0, y0, w, h)
|
|
152
|
+
if best is None:
|
|
19
153
|
return None
|
|
20
|
-
|
|
21
|
-
|
|
154
|
+
# The flat inside stops a pixel or two short of the outline; grow it back to the box.
|
|
155
|
+
side, x0, y0, w, h = best
|
|
156
|
+
pad = int(round(0.06 * side)) + 1
|
|
157
|
+
x0, y0 = max(0, x0 - pad), max(0, y0 - pad)
|
|
158
|
+
return x0, y0, min(w_img - x0, w + 2 * pad), min(h_img - y0, h + 2 * pad)
|
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""The state of each tile of a board's grid, read from pixels.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
a
|
|
6
|
-
|
|
7
|
-
tiles is simply not a `grid` to it.
|
|
8
|
-
|
|
9
|
-
The rest reads pixels inside cells the grid has already given: a vendor's
|
|
10
|
-
"selected" mark, a tile still loading, an empty slot, a tile fading in.
|
|
3
|
+
The grid itself comes from the vendor's DOM (`PageSolver._dom_grid`): where the
|
|
4
|
+
challenge frame placed each tile. Given those cells, this reads the pixels inside
|
|
5
|
+
them: a vendor's "selected" mark, a tile still loading, an empty slot, a tile
|
|
6
|
+
fading in.
|
|
11
7
|
"""
|
|
12
8
|
|
|
13
9
|
from __future__ import annotations
|
|
14
10
|
|
|
15
11
|
import tempfile
|
|
16
|
-
from typing import List, Optional,
|
|
12
|
+
from typing import List, Optional, Tuple
|
|
17
13
|
|
|
18
14
|
import numpy as np
|
|
19
15
|
from PIL import Image
|
|
@@ -24,128 +20,6 @@ from ..overlay import add_overlays_to_image
|
|
|
24
20
|
|
|
25
21
|
Box = Tuple[int, int, int, int]
|
|
26
22
|
|
|
27
|
-
#: Below these the detector is guessing: measured on real captures, every true
|
|
28
|
-
#: grid and its cells score above them and no not-grid board's grid does.
|
|
29
|
-
GRID_MIN_SCORE = 0.5
|
|
30
|
-
CELL_MIN_SCORE = 0.5
|
|
31
|
-
#: A row starts where a cell's top sits more than this share of a cell below the row's.
|
|
32
|
-
ROW_BREAK = 0.5
|
|
33
|
-
#: A tile is a cell whatever else it looks like: a flat-coloured tile (a blank one
|
|
34
|
-
#: mid-fade, a plain colour) reads as a jigsaw piece (`draggable`) or an `item`.
|
|
35
|
-
#: Inside the grid, one the size of the cells (within this share) that no cell box
|
|
36
|
-
#: already covers fills its slot.
|
|
37
|
-
TILE_CLASSES = ("draggable", "item")
|
|
38
|
-
TILE_SIZE_TOL = 0.25
|
|
39
|
-
#: A lattice the detector saw most of: when its cells do not form whole rows (a
|
|
40
|
-
#: gutter it missed merges two tiles, a faint one splits none), a grid box whose
|
|
41
|
-
#: slots are this share filled, every row and column with at least one, is the
|
|
42
|
-
#: lattice. Two real reCAPTCHA 4x4 photo boards came back with 14 and 17 cells.
|
|
43
|
-
LATTICE_MIN_FILLED = 0.75
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
def _iou(a: Sequence[float], b: Sequence[float]) -> float:
|
|
47
|
-
ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
|
|
48
|
-
iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
|
|
49
|
-
inter = ix * iy
|
|
50
|
-
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
|
|
51
|
-
return inter / union if union > 0 else 0.0
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def _with_tiles(cells: List[List[float]], tiles: List[List[float]]) -> List[List[float]]:
|
|
55
|
-
"""`cells` plus every tile the size of a cell that no cell (or tile already taken) overlaps."""
|
|
56
|
-
if not cells:
|
|
57
|
-
return cells
|
|
58
|
-
w = float(np.median([c[2] - c[0] for c in cells]))
|
|
59
|
-
h = float(np.median([c[3] - c[1] for c in cells]))
|
|
60
|
-
out = list(cells)
|
|
61
|
-
for t in tiles:
|
|
62
|
-
if abs((t[2] - t[0]) - w) <= TILE_SIZE_TOL * w and abs((t[3] - t[1]) - h) <= TILE_SIZE_TOL * h \
|
|
63
|
-
and all(_iou(t, c) < 0.3 for c in out):
|
|
64
|
-
out.append(t)
|
|
65
|
-
return out
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
def _cells_in(grid: Sequence[float], cells: List[List[float]]) -> List[List[float]]:
|
|
69
|
-
x0, y0, x1, y1 = grid
|
|
70
|
-
return [c for c in cells if x0 <= (c[0] + c[2]) / 2 <= x1 and y0 <= (c[1] + c[3]) / 2 <= y1]
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
def _rows(cells: List[List[float]]) -> List[List[List[float]]]:
|
|
74
|
-
"""Cells grouped into rows, top to bottom, each row left to right."""
|
|
75
|
-
h = float(np.median([c[3] - c[1] for c in cells]))
|
|
76
|
-
rows: List[List[List[float]]] = []
|
|
77
|
-
for c in sorted(cells, key=lambda c: c[1]):
|
|
78
|
-
if rows and c[1] - rows[-1][0][1] <= ROW_BREAK * h:
|
|
79
|
-
rows[-1].append(c)
|
|
80
|
-
else:
|
|
81
|
-
rows.append([c])
|
|
82
|
-
return [sorted(r, key=lambda c: c[0]) for r in rows]
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
def _lattice(grid: Sequence[float], cells: List[List[float]]) -> Optional[List[List[float]]]:
|
|
86
|
-
"""The rows x columns lattice `cells` mostly fill inside `grid`, each slot at its
|
|
87
|
-
column's and row's median edges; None when they do not fill one."""
|
|
88
|
-
w = float(np.median([c[2] - c[0] for c in cells]))
|
|
89
|
-
h = float(np.median([c[3] - c[1] for c in cells]))
|
|
90
|
-
gx0, gy0, gx1, gy1 = grid
|
|
91
|
-
centres = [((c[0] + c[2]) / 2, (c[1] + c[3]) / 2) for c in cells]
|
|
92
|
-
|
|
93
|
-
def pitch(axis: int, size: float, other: float) -> Optional[float]:
|
|
94
|
-
"""Median step to the next cell along `axis`, so gutters of any width count."""
|
|
95
|
-
steps = [min((q[axis] - p[axis] for q in centres
|
|
96
|
-
if q[axis] - p[axis] > 0.5 * size and abs(q[1 - axis] - p[1 - axis]) < 0.5 * other),
|
|
97
|
-
default=None) for p in centres]
|
|
98
|
-
steps = [d for d in steps if d is not None]
|
|
99
|
-
return float(np.median(steps)) if steps else None
|
|
100
|
-
px, py = pitch(0, w, h), pitch(1, h, w)
|
|
101
|
-
if px is None or py is None:
|
|
102
|
-
return None
|
|
103
|
-
cols, rows = int(round((gx1 - gx0 - w) / px)) + 1, int(round((gy1 - gy0 - h) / py)) + 1
|
|
104
|
-
if cols < 2 or rows < 2:
|
|
105
|
-
return None
|
|
106
|
-
# Slot k along an axis is centred at the grid edge + half a cell + k pitches.
|
|
107
|
-
sx, sy = gx0 + ((gx1 - gx0) - (cols - 1) * px - w) / 2, gy0 + ((gy1 - gy0) - (rows - 1) * py - h) / 2
|
|
108
|
-
slot = {}
|
|
109
|
-
for c in cells:
|
|
110
|
-
cw, ch = c[2] - c[0], c[3] - c[1]
|
|
111
|
-
if abs(cw - w) > TILE_SIZE_TOL * w or abs(ch - h) > TILE_SIZE_TOL * h:
|
|
112
|
-
continue # two tiles read as one, or a piece of one
|
|
113
|
-
k = (int(round(((c[1] + c[3]) / 2 - sy - h / 2) / py)), int(round(((c[0] + c[2]) / 2 - sx - w / 2) / px)))
|
|
114
|
-
if not (0 <= k[0] < rows and 0 <= k[1] < cols):
|
|
115
|
-
continue
|
|
116
|
-
slot.setdefault(k, c)
|
|
117
|
-
if len(slot) < LATTICE_MIN_FILLED * rows * cols \
|
|
118
|
-
or {r for r, _ in slot} != set(range(rows)) or {c for _, c in slot} != set(range(cols)):
|
|
119
|
-
return None
|
|
120
|
-
xs = [(float(np.median([c[0] for (_, j), c in slot.items() if j == col])),
|
|
121
|
-
float(np.median([c[2] for (_, j), c in slot.items() if j == col]))) for col in range(cols)]
|
|
122
|
-
ys = [(float(np.median([c[1] for (i, _), c in slot.items() if i == row])),
|
|
123
|
-
float(np.median([c[3] for (i, _), c in slot.items() if i == row]))) for row in range(rows)]
|
|
124
|
-
return [[xs[j][0], ys[i][0], xs[j][1], ys[i][1]] for i in range(rows) for j in range(cols)]
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def find_grid(image_path: str) -> Optional[List[Box]]:
|
|
128
|
-
"""The cells of the board's grid in reading order, as (x0, y0, x1, y1) pixels;
|
|
129
|
-
None when the board has no grid, or its cells do not form whole rows of one length."""
|
|
130
|
-
from ..pointer.detector import detect_file
|
|
131
|
-
|
|
132
|
-
dets = detect_file(image_path)
|
|
133
|
-
grids = [d for d in dets if d["class"] == "grid" and d["score"] >= GRID_MIN_SCORE]
|
|
134
|
-
if not grids:
|
|
135
|
-
return None
|
|
136
|
-
grid = max(grids, key=lambda d: d["score"])["box"]
|
|
137
|
-
cells = _cells_in(grid, [d["box"] for d in dets if d["class"] == "cell" and d["score"] >= CELL_MIN_SCORE])
|
|
138
|
-
cells = _with_tiles(cells, _cells_in(grid, [d["box"] for d in dets
|
|
139
|
-
if d["class"] in TILE_CLASSES and d["score"] >= CELL_MIN_SCORE]))
|
|
140
|
-
if len(cells) < 4:
|
|
141
|
-
return None
|
|
142
|
-
rows = _rows(cells)
|
|
143
|
-
if len(rows) < 2 or len({len(r) for r in rows}) != 1 or len(rows[0]) < 2:
|
|
144
|
-
lattice = _lattice(grid, cells)
|
|
145
|
-
return None if lattice is None else [tuple(int(round(v)) for v in c) for c in lattice]
|
|
146
|
-
return [tuple(int(round(v)) for v in c) for r in rows for c in r]
|
|
147
|
-
|
|
148
|
-
|
|
149
23
|
# ── colour ──────────────────────────────────────────────────────────────
|
|
150
24
|
|
|
151
25
|
def _read_rgb(image_path: str) -> Optional[np.ndarray]:
|