captchakraken 3.2.1 → 4.1.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.
- package/AGENTS.md +7 -11
- package/LICENSE +165 -145
- package/NOTICE +4 -4
- package/README.md +12 -13
- package/bin/captchakraken.js +25 -0
- package/dist/cli-invocation.d.ts +6 -3
- package/dist/cli-invocation.js +26 -10
- package/dist/humanize.d.ts +37 -1
- package/dist/humanize.js +143 -9
- package/dist/index.d.ts +13 -12
- package/dist/index.js +25 -33
- package/dist/kinds.d.ts +15 -2
- package/dist/kinds.js +12 -4
- package/dist/playwright-types.d.ts +3 -0
- package/dist/selectors.d.ts +93 -11
- package/dist/selectors.js +226 -116
- package/dist/solver.d.ts +94 -12
- package/dist/solver.js +569 -203
- package/dist/types.d.ts +53 -8
- package/dist/verdicts.d.ts +3 -0
- package/dist/verdicts.js +40 -0
- package/package.json +8 -4
- package/python/AGENTS.md +9 -13
- package/python/LICENSE +165 -145
- package/python/NOTICE +4 -4
- package/python/README.md +13 -12
- package/python/pyproject.toml +27 -13
- package/python/src/captchakraken/__init__.py +43 -46
- package/python/src/captchakraken/action_types.py +32 -1
- package/python/src/captchakraken/captchakraken.config.json +416 -0
- package/python/src/captchakraken/cli.py +141 -31
- package/python/src/captchakraken/clipvideo.py +258 -0
- package/python/src/captchakraken/config.py +72 -7
- package/python/src/captchakraken/demo.py +149 -0
- package/python/src/captchakraken/humanize.py +141 -10
- package/python/src/captchakraken/image_processor.py +3 -7
- package/python/src/captchakraken/keyframes.py +96 -14
- package/python/src/captchakraken/kinds.py +14 -2
- package/python/src/captchakraken/models.json +37 -3
- package/python/src/captchakraken/page_solver.py +600 -252
- package/python/src/captchakraken/planner.py +311 -49
- package/python/src/captchakraken/pointer/__init__.py +20 -0
- package/python/src/captchakraken/pointer/detector.py +333 -0
- package/python/src/captchakraken/pointer/elements.py +273 -0
- package/python/src/captchakraken/pointer/heads.py +163 -0
- package/python/src/captchakraken/pointer/layout.py +319 -0
- package/python/src/captchakraken/pointer/marks.py +184 -0
- package/python/src/captchakraken/pointer/server.py +150 -0
- package/python/src/captchakraken/pointer/service.py +553 -0
- package/python/src/captchakraken/pointer/vllm_plugin.py +114 -0
- package/python/src/captchakraken/prompts.py +111 -34
- package/python/src/captchakraken/selectors.py +221 -135
- package/python/src/captchakraken/selfhost.py +423 -0
- package/python/src/captchakraken/server_manager.py +139 -11
- package/python/src/captchakraken/solver.py +169 -88
- package/python/src/captchakraken/tool_calls/board_painted.py +11 -6
- package/python/src/captchakraken/tool_calls/fill_tracker.py +152 -0
- package/python/src/captchakraken/tool_calls/find_checkbox.py +14 -59
- package/python/src/captchakraken/tool_calls/find_grid.py +273 -1191
- package/python/src/captchakraken/tool_calls/slide_tracker.py +1102 -0
- package/python/src/captchakraken/verdicts.py +52 -0
- package/dist/slide-geometry.d.ts +0 -6
- package/dist/slide-geometry.js +0 -38
- package/python/src/captchakraken/tool_calls/track_piece.py +0 -120
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""`captchakraken demo`: solve the vendors' own public demo pages through whatever this install points at.
|
|
2
|
+
|
|
3
|
+
The browser lives in its own small environment under the state directory, so it can never disturb the
|
|
4
|
+
versions the serving stack pins, and the first run needs no setup from anyone.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import List, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
from . import __version__, config, server_manager
|
|
16
|
+
|
|
17
|
+
CAMOUFOX = "camoufox==0.5.9"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Site:
|
|
22
|
+
id: str
|
|
23
|
+
vendor: str
|
|
24
|
+
what: str
|
|
25
|
+
url: str
|
|
26
|
+
settle_ms: int = 2500
|
|
27
|
+
open: Sequence[str] = ()
|
|
28
|
+
ready: Sequence[str] = ()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_GEETEST_OPEN = (".geetest_btn", ".geetest_btn_click", ".geetest_radar_btn", ".geetest_holder")
|
|
32
|
+
_GEETEST_READY = (".geetest_popup_box", ".geetest_popup_window", ".geetest_box", ".geetest_panel")
|
|
33
|
+
|
|
34
|
+
SITES = (
|
|
35
|
+
Site("recaptcha", "reCAPTCHA", "tile grid, dealt until satisfied", "https://www.google.com/recaptcha/api2/demo",
|
|
36
|
+
3000),
|
|
37
|
+
Site("geetest-slide", "GeeTest v4", "slide a piece into its notch",
|
|
38
|
+
"https://gt4.geetest.com/demov4/slide-popup-en.html", 2200, _GEETEST_OPEN, _GEETEST_READY),
|
|
39
|
+
Site("geetest-icon", "GeeTest v4", "click named icons in order",
|
|
40
|
+
"https://gt4.geetest.com/demov4/icon-popup-en.html", 2200, _GEETEST_OPEN, _GEETEST_READY),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _env_dir() -> Path:
|
|
45
|
+
return config.state_dir() / "demo"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _python() -> Path:
|
|
49
|
+
return _env_dir() / "bin" / "python"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _ready(python: Path) -> bool:
|
|
53
|
+
check = ("import captchakraken, camoufox.pkgman as p; "
|
|
54
|
+
f"raise SystemExit(0 if p.installed_verstr() and captchakraken.__version__ == {__version__!r} else 1)")
|
|
55
|
+
return python.exists() and subprocess.run([str(python), "-c", check], capture_output=True).returncode == 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def prepare() -> None:
|
|
59
|
+
"""The environment and the browser, once. Downloads about 700 MB the first time."""
|
|
60
|
+
from . import selfhost
|
|
61
|
+
|
|
62
|
+
python = selfhost.make_venv(_env_dir())
|
|
63
|
+
if _ready(python):
|
|
64
|
+
return
|
|
65
|
+
selfhost.install_client(python)
|
|
66
|
+
subprocess.run([str(python), "-m", "pip", "install", "--quiet", CAMOUFOX], check=True)
|
|
67
|
+
subprocess.run([str(python), "-m", "camoufox", "fetch"], check=True)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _reveal(page, site: Site) -> None:
|
|
71
|
+
for selector in site.open:
|
|
72
|
+
try:
|
|
73
|
+
page.wait_for_selector(selector, state="visible", timeout=8000).click(timeout=4000)
|
|
74
|
+
except Exception:
|
|
75
|
+
continue
|
|
76
|
+
for panel in site.ready:
|
|
77
|
+
try:
|
|
78
|
+
page.wait_for_selector(panel, state="visible", timeout=12_000)
|
|
79
|
+
return
|
|
80
|
+
except Exception:
|
|
81
|
+
continue
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _solve_one(browser, site: Site) -> "tuple[bool, float, str]":
|
|
86
|
+
from .page_solver import PageSolver
|
|
87
|
+
|
|
88
|
+
context = browser.new_context(viewport=None)
|
|
89
|
+
began = time.time()
|
|
90
|
+
try:
|
|
91
|
+
page = context.new_page()
|
|
92
|
+
page.goto(site.url, wait_until="domcontentloaded", timeout=60_000)
|
|
93
|
+
page.wait_for_timeout(site.settle_ms)
|
|
94
|
+
_reveal(page, site)
|
|
95
|
+
began = time.time()
|
|
96
|
+
solved = bool(PageSolver().solve(page).is_solved)
|
|
97
|
+
return solved, time.time() - began, "" if solved else "answered, the vendor did not accept"
|
|
98
|
+
except Exception as e:
|
|
99
|
+
return False, time.time() - began, str(e).splitlines()[0][:90]
|
|
100
|
+
finally:
|
|
101
|
+
try:
|
|
102
|
+
context.close()
|
|
103
|
+
except Exception:
|
|
104
|
+
pass
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def run(picked: List[str], headed: bool) -> int:
|
|
108
|
+
from camoufox.sync_api import Camoufox
|
|
109
|
+
|
|
110
|
+
sites = [s for s in SITES if s.id in picked] if picked else list(SITES)
|
|
111
|
+
if not sites:
|
|
112
|
+
print(f"No such site. Known: {', '.join(s.id for s in SITES)}", file=sys.stderr)
|
|
113
|
+
return 2
|
|
114
|
+
print(f"\n Endpoint: {config.base_url()}\n Model: {config.selfhost().get('title') or config.lora_name()}\n",
|
|
115
|
+
flush=True)
|
|
116
|
+
if config.selfhost_active():
|
|
117
|
+
try:
|
|
118
|
+
server_manager.ensure_server()
|
|
119
|
+
except RuntimeError as e:
|
|
120
|
+
print(f" {e}", file=sys.stderr)
|
|
121
|
+
return 1
|
|
122
|
+
solved = 0
|
|
123
|
+
with Camoufox(headless=not headed, humanize=False, geoip=False, i_know_what_im_doing=True) as browser:
|
|
124
|
+
for site in sites:
|
|
125
|
+
print(f" {site.vendor}: {site.what}\n {site.url}", flush=True)
|
|
126
|
+
ok, seconds, note = _solve_one(browser, site)
|
|
127
|
+
solved += ok
|
|
128
|
+
print(f" \033[32m✓ solved\033[0m in {seconds:.1f}s\n" if ok
|
|
129
|
+
else f" \033[31m✗ {note}\033[0m after {seconds:.1f}s\n", flush=True)
|
|
130
|
+
print(f" {solved}/{len(sites)} solved. Vendors grade each attempt, so an occasional miss is normal.\n")
|
|
131
|
+
return 0 if solved else 1
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
135
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
136
|
+
headed = "--headed" in args
|
|
137
|
+
picked = [a for a in args if not a.startswith("-")]
|
|
138
|
+
if "--list" in args:
|
|
139
|
+
for s in SITES:
|
|
140
|
+
print(f" {s.id:15} {s.vendor:11} {s.url}")
|
|
141
|
+
return 0
|
|
142
|
+
if Path(sys.prefix).resolve() != _env_dir().resolve():
|
|
143
|
+
prepare()
|
|
144
|
+
return subprocess.run([str(_python()), "-m", "captchakraken.demo", *args]).returncode
|
|
145
|
+
return run(picked, headed)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
sys.exit(main())
|
|
@@ -8,10 +8,11 @@ touch mode that dispatches no motion between taps still has to say where the nex
|
|
|
8
8
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
+
import math
|
|
11
12
|
import os
|
|
12
13
|
import random
|
|
13
14
|
import time
|
|
14
|
-
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
15
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
|
15
16
|
|
|
16
17
|
from cursory import generate_trajectory
|
|
17
18
|
|
|
@@ -22,6 +23,8 @@ Point = Tuple[float, float]
|
|
|
22
23
|
# Each device supplies its own table. An unknown kind yields no wait rather than raising, so adding
|
|
23
24
|
# a pause site cannot break a custom humanizer written against an older release.
|
|
24
25
|
PAUSE_KINDS = tuple(PauseKind)
|
|
26
|
+
# How often a held press looks at the widget, in ms: a frame hash per look, so not every frame.
|
|
27
|
+
HOLD_POLL_MS = (180.0, 320.0)
|
|
25
28
|
|
|
26
29
|
|
|
27
30
|
def _delay(ms: float) -> None:
|
|
@@ -38,10 +41,57 @@ def _same_point(a: Point, b: Point) -> bool:
|
|
|
38
41
|
return abs(float(a[0]) - float(b[0])) < 1e-6 and abs(float(a[1]) - float(b[1])) < 1e-6
|
|
39
42
|
|
|
40
43
|
|
|
44
|
+
# What one mouse event may cover. cursory's samples are up to 250 ms and 560 px apart, which the page sees as a
|
|
45
|
+
# cursor that vanishes and reappears: a teleport. A real mouse reports every 8 ms (125 Hz).
|
|
46
|
+
MAX_EVENT_GAP_MS = 8.0
|
|
47
|
+
MAX_EVENT_STEP_PX = 16.0
|
|
48
|
+
# How far a reach may swing off the straight line between its endpoints: a fraction of its length, at least a few
|
|
49
|
+
# pixels. cursory morphs a long recorded movement onto any pair of points, so a 5 px move swung 61 px wide and a
|
|
50
|
+
# 140 px one 300 px.
|
|
51
|
+
MAX_DEVIATION = 0.15
|
|
52
|
+
MIN_DEVIATION_PX = 3.0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _nearest_on_segment(p: Point, a: Point, b: Point) -> Point:
|
|
56
|
+
dx, dy = b[0] - a[0], b[1] - a[1]
|
|
57
|
+
length2 = dx * dx + dy * dy
|
|
58
|
+
if length2 == 0.0:
|
|
59
|
+
return a
|
|
60
|
+
k = max(0.0, min(1.0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length2))
|
|
61
|
+
return a[0] + k * dx, a[1] + k * dy
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _tame(points: List[Point], start: Point, end: Point) -> List[Point]:
|
|
65
|
+
"""Shrink the path's swing off the segment, shape kept, until it stays within MAX_DEVIATION of it."""
|
|
66
|
+
limit = max(MIN_DEVIATION_PX, MAX_DEVIATION * ((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) ** 0.5)
|
|
67
|
+
near = [_nearest_on_segment(p, start, end) for p in points]
|
|
68
|
+
worst = max((((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) ** 0.5 for p, q in zip(points, near)), default=0.0)
|
|
69
|
+
if worst <= limit:
|
|
70
|
+
return points
|
|
71
|
+
k = limit / worst
|
|
72
|
+
return [(q[0] + (p[0] - q[0]) * k, q[1] + (p[1] - q[1]) * k) for p, q in zip(points, near)]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _densify(points: List[Point], timings: List[float]) -> Tuple[List[Point], List[float]]:
|
|
76
|
+
"""Fill every gap wider than one mouse report with evenly timed samples along it."""
|
|
77
|
+
out_p, out_t = points[:1], timings[:1]
|
|
78
|
+
for (a, ta), (b, tb) in zip(zip(points, timings), zip(points[1:], timings[1:])):
|
|
79
|
+
dist = ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** 0.5
|
|
80
|
+
n = max(1, int(-(-(tb - ta) // MAX_EVENT_GAP_MS)), int(-(-dist // MAX_EVENT_STEP_PX)))
|
|
81
|
+
for i in range(1, n + 1):
|
|
82
|
+
f = i / n
|
|
83
|
+
out_p.append((a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f))
|
|
84
|
+
out_t.append(ta + (tb - ta) * f)
|
|
85
|
+
return out_p, out_t
|
|
86
|
+
|
|
87
|
+
|
|
41
88
|
def trajectory(start: Point, end: Point, frequency: int = 60) -> Tuple[List[Point], List[float]]:
|
|
42
|
-
"""A recorded human movement morphed onto the endpoints
|
|
89
|
+
"""A recorded human movement morphed onto the endpoints, held near the line between them and sampled at
|
|
90
|
+
least once per mouse report; timings are cumulative ms."""
|
|
43
91
|
points, timings = generate_trajectory(start, end, frequency=frequency)
|
|
44
|
-
|
|
92
|
+
start, end = (float(start[0]), float(start[1])), (float(end[0]), float(end[1]))
|
|
93
|
+
pts = _tame([(float(x), float(y)) for x, y in points], start, end)
|
|
94
|
+
return _densify(pts, [float(t) for t in timings])
|
|
45
95
|
|
|
46
96
|
|
|
47
97
|
class Humanizer:
|
|
@@ -60,6 +110,11 @@ class Humanizer:
|
|
|
60
110
|
def move(self, page: Any, to: Point) -> None:
|
|
61
111
|
raise NotImplementedError
|
|
62
112
|
|
|
113
|
+
def drift(self, page: Any, to: Point) -> None:
|
|
114
|
+
"""A held hand's pixel of wander. `move` is a reach, and a reach overshoots: on a 1px move it wandered up to
|
|
115
|
+
34px, off a thin bar, which the widget takes for a release."""
|
|
116
|
+
self.move(page, to)
|
|
117
|
+
|
|
63
118
|
def press(self, page: Any) -> None:
|
|
64
119
|
raise NotImplementedError
|
|
65
120
|
|
|
@@ -91,6 +146,36 @@ class Humanizer:
|
|
|
91
146
|
self.release(page)
|
|
92
147
|
|
|
93
148
|
|
|
149
|
+
def hold(human: "Humanizer", page: Any, to: Point, done: Callable[[], bool], max_ms: float) -> bool:
|
|
150
|
+
"""Press at `to` until `done()` says the widget completed, or `max_ms` passes; True when it completed.
|
|
151
|
+
|
|
152
|
+
Built on move/press/release so any humanizer can hold. The hand drifts a pixel or so meanwhile, because a
|
|
153
|
+
press that does not move for seconds is a synthetic one, and the button is released whatever `done` raises.
|
|
154
|
+
"""
|
|
155
|
+
human.move(page, to)
|
|
156
|
+
anchor = human.at
|
|
157
|
+
human.press(page)
|
|
158
|
+
t0 = time.monotonic()
|
|
159
|
+
try:
|
|
160
|
+
while True:
|
|
161
|
+
_delay(random.uniform(*HOLD_POLL_MS))
|
|
162
|
+
try:
|
|
163
|
+
getattr(human, "drift", human.move)(page, (anchor[0] + random.gauss(0.0, 0.8),
|
|
164
|
+
anchor[1] + random.gauss(0.0, 0.8)))
|
|
165
|
+
except Exception:
|
|
166
|
+
pass
|
|
167
|
+
if done():
|
|
168
|
+
return True
|
|
169
|
+
if (time.monotonic() - t0) * 1000.0 >= max_ms:
|
|
170
|
+
return False
|
|
171
|
+
finally:
|
|
172
|
+
human.release(page)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# How much longer than the bare round trip a step takes when the browser re-draws it as a path of its own.
|
|
176
|
+
BROWSER_PATH_MS = 100.0
|
|
177
|
+
|
|
178
|
+
|
|
94
179
|
class MouseHumanizer(Humanizer):
|
|
95
180
|
name = HumanizationMode.MOUSE
|
|
96
181
|
hovers = True
|
|
@@ -104,11 +189,13 @@ class MouseHumanizer(Humanizer):
|
|
|
104
189
|
self._viewport_cache: Optional[Dict[str, float]] = None
|
|
105
190
|
self._down = False
|
|
106
191
|
self._cursor_seeded = False
|
|
192
|
+
self._browser_draws_path: Optional[bool] = None
|
|
107
193
|
|
|
108
194
|
def reset(self, page: Any) -> None:
|
|
109
195
|
self._viewport_cache = None
|
|
110
196
|
self._cursor_seeded = False
|
|
111
197
|
self._down = False
|
|
198
|
+
self._browser_draws_path = None
|
|
112
199
|
|
|
113
200
|
def _viewport(self, page: Any) -> Optional[Dict[str, float]]:
|
|
114
201
|
"""The window to keep the cursor inside; None under camoufox, which reports no viewport."""
|
|
@@ -140,22 +227,60 @@ class MouseHumanizer(Humanizer):
|
|
|
140
227
|
except Exception:
|
|
141
228
|
pass
|
|
142
229
|
|
|
230
|
+
def _clamp(self, page: Any, point: Point) -> Point:
|
|
231
|
+
# Clamp only when the viewport is known: a guessed edge coordinate deadlocks camoufox's juggler.
|
|
232
|
+
x, y = float(point[0]), float(point[1])
|
|
233
|
+
viewport = self._viewport(page)
|
|
234
|
+
if viewport is None:
|
|
235
|
+
return x, y
|
|
236
|
+
return max(1.0, min(x, viewport["width"] - 1.0)), max(1.0, min(y, viewport["height"] - 1.0))
|
|
237
|
+
|
|
238
|
+
def _measure_browser_path(self, page: Any, to: Point) -> bool:
|
|
239
|
+
"""Whether the browser draws its own path for every mouse.move(), as camoufox's humanize does.
|
|
240
|
+
|
|
241
|
+
Ours on top has every sample re-drawn: a 1px step took 190ms there against 1ms, and one GeeTest slider 82s
|
|
242
|
+
against 13s. One short step towards `to`, timed against a zero-length move (the bare round trip, so a remote
|
|
243
|
+
browser is not mistaken for one), tells them apart with no movement the page could single out.
|
|
244
|
+
"""
|
|
245
|
+
x0, y0 = self._clamp(page, self.at)
|
|
246
|
+
d = math.hypot(to[0] - x0, to[1] - y0)
|
|
247
|
+
step = self._clamp(page, to if d <= 3 else (x0 + 3 * (to[0] - x0) / d, y0 + 3 * (to[1] - y0) / d))
|
|
248
|
+
try:
|
|
249
|
+
page.mouse.move(x0, y0)
|
|
250
|
+
t = time.monotonic()
|
|
251
|
+
page.mouse.move(x0, y0)
|
|
252
|
+
round_trip = time.monotonic() - t
|
|
253
|
+
t = time.monotonic()
|
|
254
|
+
page.mouse.move(*step)
|
|
255
|
+
except Exception as exc:
|
|
256
|
+
if "Target closed" in str(exc) or "Session closed" in str(exc):
|
|
257
|
+
_log("could not move mouse; page or session closed")
|
|
258
|
+
return False
|
|
259
|
+
self.at = step
|
|
260
|
+
drawn = (time.monotonic() - t - round_trip) * 1000.0 > BROWSER_PATH_MS
|
|
261
|
+
if drawn:
|
|
262
|
+
_log("the browser draws its own pointer paths (camoufox humanize); handing it one move per gesture")
|
|
263
|
+
return drawn
|
|
264
|
+
|
|
143
265
|
def move(self, page: Any, to: Point) -> None:
|
|
144
266
|
self._seed_cursor(page)
|
|
145
267
|
if _same_point(self.at, to):
|
|
146
268
|
return
|
|
269
|
+
if self._browser_draws_path is None:
|
|
270
|
+
self._browser_draws_path = self._measure_browser_path(page, to)
|
|
271
|
+
if self._browser_draws_path:
|
|
272
|
+
self._trace(page, [to], [0.0])
|
|
273
|
+
return
|
|
147
274
|
points, timings = trajectory(self.at, to, self._frequency)
|
|
148
275
|
self._trace(page, points, timings)
|
|
149
276
|
|
|
277
|
+
def drift(self, page: Any, to: Point) -> None:
|
|
278
|
+
self._trace(page, [to], [0.0])
|
|
279
|
+
|
|
150
280
|
def _trace(self, page: Any, points: Sequence[Point], timings: Sequence[float]) -> None:
|
|
151
|
-
# Clamp only when the viewport is known: a guessed edge coordinate deadlocks camoufox's juggler.
|
|
152
|
-
viewport = self._viewport(page)
|
|
153
281
|
start = time.monotonic() * 1000.0
|
|
154
|
-
for
|
|
155
|
-
x, y =
|
|
156
|
-
if viewport is not None:
|
|
157
|
-
x = max(1.0, min(x, viewport["width"] - 1.0))
|
|
158
|
-
y = max(1.0, min(y, viewport["height"] - 1.0))
|
|
282
|
+
for point, t in zip(points, timings):
|
|
283
|
+
x, y = self._clamp(page, point)
|
|
159
284
|
try:
|
|
160
285
|
page.mouse.move(x, y)
|
|
161
286
|
except Exception as exc:
|
|
@@ -395,6 +520,12 @@ class MobileHumanizer(Humanizer):
|
|
|
395
520
|
for i, (x, y) in enumerate(points)])
|
|
396
521
|
self.at = to
|
|
397
522
|
|
|
523
|
+
def drift(self, page: Any, to: Point) -> None:
|
|
524
|
+
to = (float(to[0]), float(to[1]))
|
|
525
|
+
if self._down:
|
|
526
|
+
self._touch(page).move([(to[0], to[1], 0.0)])
|
|
527
|
+
self.at = to
|
|
528
|
+
|
|
398
529
|
def press(self, page: Any) -> None:
|
|
399
530
|
self._touch(page).down(*self.at)
|
|
400
531
|
self._down = True
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""The frame-diff primitive every movement check in both ports shares."""
|
|
2
2
|
|
|
3
|
-
import
|
|
3
|
+
from .keyframes import frame_diff_ratio, read_frame
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
class ImageProcessor:
|
|
@@ -11,14 +11,10 @@ class ImageProcessor:
|
|
|
11
11
|
Split from `detect_movement` so callers can report the number: GeeTest's permanent background shimmer
|
|
12
12
|
sits close enough to the default threshold to fire the freshness re-solve on nearly every inference.
|
|
13
13
|
"""
|
|
14
|
-
img1, img2 =
|
|
14
|
+
img1, img2 = read_frame(image1_path), read_frame(image2_path)
|
|
15
15
|
if img1 is None or img2 is None:
|
|
16
16
|
return 0.0
|
|
17
|
-
|
|
18
|
-
return 1.0
|
|
19
|
-
gray = cv2.cvtColor(cv2.absdiff(img1, img2), cv2.COLOR_BGR2GRAY)
|
|
20
|
-
_, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
|
|
21
|
-
return cv2.countNonZero(thresh) / float(thresh.shape[0] * thresh.shape[1])
|
|
17
|
+
return frame_diff_ratio(img1, img2)
|
|
22
18
|
|
|
23
19
|
@staticmethod
|
|
24
20
|
def detect_movement(image1_path: str, image2_path: str, threshold: float = 0.005) -> bool:
|
|
@@ -9,12 +9,13 @@ from __future__ import annotations
|
|
|
9
9
|
|
|
10
10
|
import json
|
|
11
11
|
import os
|
|
12
|
+
from contextvars import ContextVar
|
|
12
13
|
from dataclasses import dataclass, field
|
|
13
14
|
from pathlib import Path
|
|
14
15
|
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
15
16
|
|
|
16
|
-
import cv2
|
|
17
17
|
import numpy as np
|
|
18
|
+
from PIL import Image, ImageOps
|
|
18
19
|
|
|
19
20
|
from .kinds import KeyframeMode
|
|
20
21
|
|
|
@@ -38,6 +39,11 @@ DEFAULT_MIN_STEADY_COVERAGE = 0.5
|
|
|
38
39
|
# The one pixel threshold shared with every other movement check in the project.
|
|
39
40
|
_PIXEL_DELTA = 30
|
|
40
41
|
|
|
42
|
+
# Grey = (B, G, R) . weights >> 15, rounded: OpenCV's fixed-point BGR2GRAY, which every threshold above was
|
|
43
|
+
# measured through. Equal to it on all 2^24 colours. Elementwise, not a matrix product: BLAS threads on a busy
|
|
44
|
+
# machine made the product 20x slower than the arithmetic.
|
|
45
|
+
_GRAY_WEIGHTS = (3735, 19235, 9798)
|
|
46
|
+
|
|
41
47
|
# One constant for both choosing the label's frame and the live wait: the two must ask the same question.
|
|
42
48
|
MATCH_REGION_HALF = 0.06
|
|
43
49
|
|
|
@@ -147,17 +153,66 @@ def frame_diff_ratio(a: np.ndarray, b: np.ndarray) -> float:
|
|
|
147
153
|
return 1.0
|
|
148
154
|
if a.shape != b.shape:
|
|
149
155
|
return 1.0
|
|
150
|
-
diff =
|
|
151
|
-
|
|
152
|
-
diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
|
|
153
|
-
_, thr = cv2.threshold(diff, _PIXEL_DELTA, 255, cv2.THRESH_BINARY)
|
|
154
|
-
h, w = thr.shape[:2]
|
|
156
|
+
diff = np.maximum(a, b) - np.minimum(a, b)
|
|
157
|
+
h, w = diff.shape[:2]
|
|
155
158
|
if h * w == 0:
|
|
156
159
|
return 1.0
|
|
157
|
-
|
|
160
|
+
# Grey > delta, compared before the shift: the same pixels, one pass fewer over the frame.
|
|
161
|
+
moved = _scaled_luma(diff) >= (_PIXEL_DELTA + 1) << 15 if diff.ndim == 3 else diff > _PIXEL_DELTA
|
|
162
|
+
return int(np.count_nonzero(moved)) / float(h * w)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _scaled_luma(frame: np.ndarray) -> np.ndarray:
|
|
166
|
+
"""A BGR uint8 frame's luma times 2^15, rounding offset included."""
|
|
167
|
+
luma = np.multiply(frame[..., 0], _GRAY_WEIGHTS[0], dtype=np.uint32)
|
|
168
|
+
luma += np.multiply(frame[..., 1], _GRAY_WEIGHTS[1], dtype=np.uint32)
|
|
169
|
+
luma += np.multiply(frame[..., 2], _GRAY_WEIGHTS[2], dtype=np.uint32)
|
|
170
|
+
luma += 1 << 14
|
|
171
|
+
return luma
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def to_gray(frame: np.ndarray) -> np.ndarray:
|
|
175
|
+
"""A BGR uint8 frame's luma, as uint8."""
|
|
176
|
+
return (_scaled_luma(frame) >> 15).astype(np.uint8)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def read_frame(path: str | os.PathLike) -> Optional[np.ndarray]:
|
|
180
|
+
"""The image at `path` as an (H, W, 3) BGR uint8 array, or None if it cannot be decoded.
|
|
181
|
+
|
|
182
|
+
BGR because every frame in the project is: recordings, keyframes and the files they are written to.
|
|
183
|
+
"""
|
|
184
|
+
try:
|
|
185
|
+
with Image.open(path) as img:
|
|
186
|
+
rgb = np.asarray(ImageOps.exif_transpose(img).convert("RGB"))
|
|
187
|
+
except OSError:
|
|
188
|
+
return None
|
|
189
|
+
return np.ascontiguousarray(rgb[..., ::-1])
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def write_frame(path: str | os.PathLike, frame: np.ndarray) -> None:
|
|
193
|
+
"""Write a BGR (or single-channel) uint8 frame; the format follows the extension."""
|
|
194
|
+
Image.fromarray(frame[..., ::-1] if frame.ndim == 3 else frame).save(path)
|
|
158
195
|
|
|
159
196
|
|
|
160
197
|
|
|
198
|
+
#: The diffs already measured during the extraction in progress, keyed by the two frames' identities.
|
|
199
|
+
#: A 100-frame clip asks ~8,000 diffs of ~1,100 distinct pairs: the medoid, merge and dedup passes keep
|
|
200
|
+
#: re-comparing the same screens. `extract_keyframes` holds every frame alive for the duration, so an
|
|
201
|
+
#: id cannot be reused while it is a key.
|
|
202
|
+
_PAIR_CACHE: ContextVar[Optional[Dict[Tuple[int, int], float]]] = ContextVar("_PAIR_CACHE", default=None)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _pair_diff(a: np.ndarray, b: np.ndarray) -> float:
|
|
206
|
+
"""`frame_diff_ratio`, remembered for the extraction in progress (the diff is symmetric)."""
|
|
207
|
+
cache = _PAIR_CACHE.get()
|
|
208
|
+
if cache is None:
|
|
209
|
+
return frame_diff_ratio(a, b)
|
|
210
|
+
key = (id(a), id(b)) if id(a) <= id(b) else (id(b), id(a))
|
|
211
|
+
if key not in cache:
|
|
212
|
+
cache[key] = frame_diff_ratio(a, b)
|
|
213
|
+
return cache[key]
|
|
214
|
+
|
|
215
|
+
|
|
161
216
|
def _anchor_runs(frames: Sequence[np.ndarray], steady_ratio: float) -> List[Tuple[int, int]]:
|
|
162
217
|
"""Anchored on the run's first frame: a slow pan has every consecutive diff under the threshold."""
|
|
163
218
|
runs: List[Tuple[int, int]] = []
|
|
@@ -165,7 +220,7 @@ def _anchor_runs(frames: Sequence[np.ndarray], steady_ratio: float) -> List[Tupl
|
|
|
165
220
|
n = len(frames)
|
|
166
221
|
while i < n:
|
|
167
222
|
j = i
|
|
168
|
-
while j + 1 < n and
|
|
223
|
+
while j + 1 < n and _pair_diff(frames[i], frames[j + 1]) <= steady_ratio:
|
|
169
224
|
j += 1
|
|
170
225
|
runs.append((i, j))
|
|
171
226
|
i = j + 1
|
|
@@ -177,7 +232,7 @@ def _medoid(frames: Sequence[np.ndarray], indices: Sequence[int]) -> int:
|
|
|
177
232
|
return indices[0]
|
|
178
233
|
best_idx, best_cost = indices[0], float("inf")
|
|
179
234
|
for a in indices:
|
|
180
|
-
cost = sum(
|
|
235
|
+
cost = sum(_pair_diff(frames[a], frames[b]) for b in indices if b != a)
|
|
181
236
|
if cost < best_cost:
|
|
182
237
|
best_idx, best_cost = a, cost
|
|
183
238
|
return best_idx
|
|
@@ -208,7 +263,7 @@ def _distinct_indices(
|
|
|
208
263
|
|
|
209
264
|
def is_new(i: int) -> bool:
|
|
210
265
|
return not any(
|
|
211
|
-
|
|
266
|
+
_pair_diff(frames[i], frames[k]) <= params.steady_ratio for k in kept
|
|
212
267
|
)
|
|
213
268
|
|
|
214
269
|
for i in candidates:
|
|
@@ -241,7 +296,7 @@ def _steady_screens(
|
|
|
241
296
|
for s, e in holds:
|
|
242
297
|
rep = _medoid(frames, list(range(s, e + 1)))
|
|
243
298
|
for k, existing in enumerate(state_reps):
|
|
244
|
-
if
|
|
299
|
+
if _pair_diff(frames[rep], frames[existing]) <= params.steady_ratio:
|
|
245
300
|
hold_state.append(k)
|
|
246
301
|
break
|
|
247
302
|
else:
|
|
@@ -278,7 +333,7 @@ def _detect_cycle(
|
|
|
278
333
|
|
|
279
334
|
for a in range(len(state_reps)):
|
|
280
335
|
for b in range(a + 1, len(state_reps)):
|
|
281
|
-
if
|
|
336
|
+
if _pair_diff(frames[state_reps[a]], frames[state_reps[b]]) < params.distinct_ratio:
|
|
282
337
|
return None
|
|
283
338
|
|
|
284
339
|
per_frame = [-1] * n
|
|
@@ -306,7 +361,7 @@ def _drop_smeared(
|
|
|
306
361
|
for start, end in holds:
|
|
307
362
|
rep = _medoid(frames, list(range(start, end + 1)))
|
|
308
363
|
for k, existing in enumerate(reps):
|
|
309
|
-
if
|
|
364
|
+
if _pair_diff(frames[rep], frames[existing]) <= params.steady_ratio:
|
|
310
365
|
state_of_hold.append(k)
|
|
311
366
|
break
|
|
312
367
|
else:
|
|
@@ -342,8 +397,19 @@ def extract_keyframes(
|
|
|
342
397
|
fps: float = 10.0,
|
|
343
398
|
params: Optional[KeyframeParams] = None,
|
|
344
399
|
) -> KeyframeSet:
|
|
400
|
+
# A list, so each frame is one object that lives as long as the cache keyed on its id
|
|
401
|
+
# (indexing a 4-D array would make a new, collectable view per access).
|
|
402
|
+
frames = list(frames)
|
|
345
403
|
if not frames:
|
|
346
404
|
raise ValueError("no frames to extract keyframes from")
|
|
405
|
+
token = _PAIR_CACHE.set({})
|
|
406
|
+
try:
|
|
407
|
+
return _extract_keyframes(frames, fps, params)
|
|
408
|
+
finally:
|
|
409
|
+
_PAIR_CACHE.reset(token)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _extract_keyframes(frames: Sequence[np.ndarray], fps: float, params: Optional[KeyframeParams]) -> KeyframeSet:
|
|
347
413
|
p = params or KeyframeParams()
|
|
348
414
|
n = len(frames)
|
|
349
415
|
|
|
@@ -412,7 +478,7 @@ def write_keyframes(
|
|
|
412
478
|
target = out / name
|
|
413
479
|
if kf.image is None:
|
|
414
480
|
raise ValueError(f"keyframe {kf.number} has no image to write")
|
|
415
|
-
|
|
481
|
+
write_frame(target, kf.image)
|
|
416
482
|
paths.append(target)
|
|
417
483
|
names.append(name)
|
|
418
484
|
|
|
@@ -421,4 +487,20 @@ def write_keyframes(
|
|
|
421
487
|
return paths
|
|
422
488
|
|
|
423
489
|
|
|
490
|
+
def number_for_source_index(kfset: KeyframeSet, source_index: int) -> int:
|
|
491
|
+
"""The keyframe a given source frame belongs to (1-based), by POSITION.
|
|
492
|
+
|
|
493
|
+
Exact in cycle mode (the frame's own state), else the nearest keyframe in time. A transition
|
|
494
|
+
frame (state -1) has no state of its own, so where the pixels are at hand, matching by
|
|
495
|
+
appearance around the action point is the better question.
|
|
496
|
+
"""
|
|
497
|
+
if not kfset.keyframes:
|
|
498
|
+
raise ValueError("keyframe set is empty")
|
|
499
|
+
if kfset.mode == KeyframeMode.CYCLE and 0 <= source_index < len(kfset.frame_states):
|
|
500
|
+
state = kfset.frame_states[source_index]
|
|
501
|
+
if state >= 0:
|
|
502
|
+
return state + 1
|
|
503
|
+
return min(kfset.keyframes, key=lambda k: abs(k.source_index - source_index)).number
|
|
504
|
+
|
|
505
|
+
|
|
424
506
|
|
|
@@ -3,7 +3,7 @@ from enum import StrEnum
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
class Vendor(StrEnum):
|
|
6
|
-
"""`puzzle_source` everywhere. UNKNOWN must stay permissive:
|
|
6
|
+
"""`puzzle_source` everywhere. UNKNOWN must stay permissive: the CLI, scripts and the offline grader report it."""
|
|
7
7
|
|
|
8
8
|
HCAPTCHA = "hcaptcha"
|
|
9
9
|
RECAPTCHA = "recaptcha"
|
|
@@ -16,6 +16,12 @@ class Vendor(StrEnum):
|
|
|
16
16
|
PROSOPO = "prosopo"
|
|
17
17
|
MTCAPTCHA = "mtcaptcha"
|
|
18
18
|
BOTDETECT = "botdetect"
|
|
19
|
+
HUMAN = "human"
|
|
20
|
+
AWSWAF = "awswaf"
|
|
21
|
+
CAPTCHAFOX = "captchafox"
|
|
22
|
+
DINGXIANG = "dingxiang"
|
|
23
|
+
FUNCAPTCHA = "funcaptcha"
|
|
24
|
+
PROTON = "proton"
|
|
19
25
|
UNKNOWN = "unknown"
|
|
20
26
|
|
|
21
27
|
|
|
@@ -25,6 +31,9 @@ class ActionKind(StrEnum):
|
|
|
25
31
|
TYPE = "type"
|
|
26
32
|
WAIT = "wait"
|
|
27
33
|
DONE = "done"
|
|
34
|
+
HOLD = "hold"
|
|
35
|
+
REFRESH = "refresh"
|
|
36
|
+
SLIDE = "slide"
|
|
28
37
|
|
|
29
38
|
|
|
30
39
|
class PixelAnswerKind(StrEnum):
|
|
@@ -34,6 +43,8 @@ class PixelAnswerKind(StrEnum):
|
|
|
34
43
|
DRAG = "drag"
|
|
35
44
|
SLIDE = "slide"
|
|
36
45
|
TYPE = "type"
|
|
46
|
+
HOLD = "hold"
|
|
47
|
+
REFRESH = "refresh"
|
|
37
48
|
|
|
38
49
|
|
|
39
50
|
class RetryMode(StrEnum):
|
|
@@ -126,7 +137,8 @@ class Phase(StrEnum):
|
|
|
126
137
|
GRID_LOAD = "grid-load"
|
|
127
138
|
FADE_WAIT = "fade-wait"
|
|
128
139
|
BOARD_PAINT = "board-paint"
|
|
129
|
-
|
|
140
|
+
BOARD_IMAGES = "board-images"
|
|
141
|
+
HCAPTCHA_IMAGES = "board-images" # the old name; an alias of BOARD_IMAGES
|
|
130
142
|
AWAIT_NEXT_ROUND = "await-next-round"
|
|
131
143
|
AWAIT_VERDICT = "await-verdict"
|
|
132
144
|
POST_SUBMIT_DELAY = "post-submit-delay"
|