captchakraken 4.0.0 → 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 +2 -2
- package/README.md +3 -3
- package/bin/captchakraken.js +25 -0
- package/dist/solver.d.ts +2 -0
- package/dist/solver.js +7 -0
- package/dist/verdicts.js +34 -0
- package/package.json +5 -1
- package/python/AGENTS.md +2 -2
- package/python/README.md +3 -3
- package/python/pyproject.toml +1 -1
- package/python/src/captchakraken/__init__.py +1 -1
- package/python/src/captchakraken/cli.py +75 -1
- package/python/src/captchakraken/config.py +72 -7
- package/python/src/captchakraken/demo.py +149 -0
- package/python/src/captchakraken/models.json +9 -0
- package/python/src/captchakraken/page_solver.py +5 -1
- package/python/src/captchakraken/planner.py +13 -2
- package/python/src/captchakraken/pointer/server.py +5 -1
- package/python/src/captchakraken/pointer/vllm_plugin.py +9 -4
- package/python/src/captchakraken/selfhost.py +423 -0
- package/python/src/captchakraken/server_manager.py +124 -14
- package/python/src/captchakraken/verdicts.py +36 -0
package/AGENTS.md
CHANGED
|
@@ -94,8 +94,8 @@ where one exists. Retrying a `403` that means "no licence" will never succeed.
|
|
|
94
94
|
Quote it as written; do not derive, round, or convert anything, and do not
|
|
95
95
|
read a static-image rate as a promise about a browser run.
|
|
96
96
|
- **Never print an API key** into a transcript, a log, or a commit. Use
|
|
97
|
-
`create_api_key`, which writes it to disk instead.
|
|
98
|
-
`.env` hold keys and are never committed.
|
|
97
|
+
`create_api_key`, which writes it to disk instead. `~/.captchakraken/selfhost.json`
|
|
98
|
+
and `.env` hold keys and are never committed.
|
|
99
99
|
- **Midnight V2 4B Q4 is the default self-hosted and hosted model.** The v2
|
|
100
100
|
weights are downloadable under LGPL-3.0-only. Older clients keep using their
|
|
101
101
|
registered chat-completion model because the protocols are not interchangeable.
|
package/README.md
CHANGED
|
@@ -49,8 +49,8 @@ inference client work out of the box. It ships **no browser** — bring your own
|
|
|
49
49
|
Playwright-compatible launcher (camoufox and patchright both work).
|
|
50
50
|
|
|
51
51
|
- Skip the Python bootstrap: `CAPTCHA_KRAKEN_SKIP_PYTHON_SETUP=1`
|
|
52
|
-
- To **self-host** the model, run
|
|
53
|
-
Otherwise point `VLLM_BASE_URL` at a server you already run.
|
|
52
|
+
- To **self-host** the model, run `npx captchakraken fetch` (installs vLLM + weights
|
|
53
|
+
and starts the server). Otherwise point `VLLM_BASE_URL` at a server you already run.
|
|
54
54
|
|
|
55
55
|
## No GPU? Use the hosted API
|
|
56
56
|
|
|
@@ -158,7 +158,7 @@ Full details, including writing your own humanizer:
|
|
|
158
158
|
| `CAPTCHA_BASE_MODEL` | Merged v2 weights vLLM loads | `CaptchaKraken/MidnightV2-4B-q4` |
|
|
159
159
|
| `CAPTCHA_LORA_ADAPTER` | Model repository (HF id or path) | `CaptchaKraken/MidnightV2-4B-q4` |
|
|
160
160
|
| `CAPTCHA_LORA_NAME` | Served model name sent as `model` | `captcha-pointer` |
|
|
161
|
-
| `CAPTCHA_POINTER_DETECTOR` | CNN element detector |
|
|
161
|
+
| `CAPTCHA_POINTER_DETECTOR` | CNN element detector | set by `captchakraken fetch` |
|
|
162
162
|
| `CAPTCHA_KRAKEN_AUTOSTART` | `0` never auto-starts a local server | `1` |
|
|
163
163
|
| `CAPTCHA_KRAKEN_PYTHON` | Interpreter used for the bundled engine | the package's venv, else `python3` |
|
|
164
164
|
| `CAPTCHA_KRAKEN_SKIP_PYTHON_SETUP` | `1` skips the `postinstall` bootstrap | unset |
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx captchakraken fetch`, `start`, `stop`, `demo`: the Python engine's command, from its bundled environment.
|
|
3
|
+
const { spawnSync } = require('node:child_process');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
const root = path.resolve(__dirname, '..');
|
|
8
|
+
const python = path.join(root, 'python', '.venv', 'bin', 'python');
|
|
9
|
+
const windowsPython = path.join(root, 'python', '.venv', 'Scripts', 'python.exe');
|
|
10
|
+
|
|
11
|
+
function engine() {
|
|
12
|
+
return [python, windowsPython].find((p) => fs.existsSync(p));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// A package manager that skips install scripts leaves the environment for now.
|
|
16
|
+
if (!engine()) {
|
|
17
|
+
spawnSync(process.execPath, [path.join(root, 'scripts', 'setup-python.js')], { stdio: 'inherit' });
|
|
18
|
+
}
|
|
19
|
+
const found = engine();
|
|
20
|
+
if (!found) {
|
|
21
|
+
console.error('[captchakraken] The Python engine is not installed. This needs Python 3.10 or newer.');
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
const { status, signal } = spawnSync(found, ['-m', 'captchakraken.cli', ...process.argv.slice(2)], { stdio: 'inherit' });
|
|
25
|
+
process.exit(status ?? (signal ? 1 : 0));
|
package/dist/solver.d.ts
CHANGED
|
@@ -235,6 +235,8 @@ export declare class CaptchaKrakenSolver {
|
|
|
235
235
|
private askTimeoutMs;
|
|
236
236
|
/** One-shot CLI tool call; `{}` on any failure so polling callers keep going. */
|
|
237
237
|
private runCliTool;
|
|
238
|
+
/** Loading a model takes as long as the whole solve budget, so a cold server must not spend it. A stopped one says so on the first request. */
|
|
239
|
+
private wakeLocalServer;
|
|
238
240
|
/** Start the persistent CV worker once; false when it cannot start, so callers fall back to one-shot spawns. */
|
|
239
241
|
private ensureCvWorker;
|
|
240
242
|
private cvWorkerRequest;
|
package/dist/solver.js
CHANGED
|
@@ -421,6 +421,7 @@ class CaptchaKrakenSolver {
|
|
|
421
421
|
this.budget = new timing_1.PhaseBudget();
|
|
422
422
|
this.verdicts = null;
|
|
423
423
|
let solvedForReport = false;
|
|
424
|
+
await this.wakeLocalServer();
|
|
424
425
|
try {
|
|
425
426
|
const result = await this.solveImpl(page);
|
|
426
427
|
if (result)
|
|
@@ -1437,6 +1438,12 @@ class CaptchaKrakenSolver {
|
|
|
1437
1438
|
return {};
|
|
1438
1439
|
}
|
|
1439
1440
|
}
|
|
1441
|
+
/** Loading a model takes as long as the whole solve budget, so a cold server must not spend it. A stopped one says so on the first request. */
|
|
1442
|
+
async wakeLocalServer() {
|
|
1443
|
+
const stateDir = process.env.CAPTCHA_KRAKEN_STATE_DIR || path.join(os.homedir(), '.captchakraken');
|
|
1444
|
+
if (fs.existsSync(path.join(stateDir, 'selfhost.json')))
|
|
1445
|
+
await this.runCliTool(['server', 'ensure']);
|
|
1446
|
+
}
|
|
1440
1447
|
/** Start the persistent CV worker once; false when it cannot start, so callers fall back to one-shot spawns. */
|
|
1441
1448
|
ensureCvWorker() {
|
|
1442
1449
|
if (this.cvWorkerReady)
|
package/dist/verdicts.js
CHANGED
|
@@ -47,6 +47,36 @@ const jsonpResult = (body) => {
|
|
|
47
47
|
const result = data?.status === 'success' ? data.data?.result : undefined;
|
|
48
48
|
return result === 'success' ? kinds_1.Verdict.ACCEPTED : result === 'fail' ? kinds_1.Verdict.REJECTED : null;
|
|
49
49
|
};
|
|
50
|
+
/**
|
|
51
|
+
* `{"errorCode": "0", "ticket": ...}` when taken; `{"errorCode": "50", "ticket": ""}` when a wrong slide is refused.
|
|
52
|
+
* Any other code (rate limits, expired sessions) has not been recorded, so the DOM judges it.
|
|
53
|
+
*/
|
|
54
|
+
const tencentTicket = (body) => {
|
|
55
|
+
const data = parse(body);
|
|
56
|
+
if (!data || typeof data !== 'object')
|
|
57
|
+
return null;
|
|
58
|
+
const code = String(data.errorCode);
|
|
59
|
+
if (code === '0' && data.ticket)
|
|
60
|
+
return kinds_1.Verdict.ACCEPTED;
|
|
61
|
+
return code === '50' && !data.ticket ? kinds_1.Verdict.REJECTED : null;
|
|
62
|
+
};
|
|
63
|
+
/** `callback({"data": {"result": true, ...}, "error": 0})` when taken, `"result": false` with `"error": 0` when refused. */
|
|
64
|
+
const yidunCheck = (body) => {
|
|
65
|
+
const start = body.indexOf('(');
|
|
66
|
+
const end = body.lastIndexOf(')');
|
|
67
|
+
const data = (start >= 0 && start < end ? parse(body.slice(start + 1, end)) : null);
|
|
68
|
+
if (!data || data.error !== 0)
|
|
69
|
+
return null;
|
|
70
|
+
const result = data.data?.result;
|
|
71
|
+
return result === true ? kinds_1.Verdict.ACCEPTED : result === false ? kinds_1.Verdict.REJECTED : null;
|
|
72
|
+
};
|
|
73
|
+
/** `solved: true` when taken; `solved: false` with `time_end` set when the session ended refused. */
|
|
74
|
+
const arkoseAnswer = (body) => {
|
|
75
|
+
const data = parse(body);
|
|
76
|
+
if (data?.solved === true)
|
|
77
|
+
return kinds_1.Verdict.ACCEPTED;
|
|
78
|
+
return data?.solved === false && data.time_end != null ? kinds_1.Verdict.REJECTED : null;
|
|
79
|
+
};
|
|
50
80
|
const urlOnly = () => kinds_1.Verdict.NEW_CHALLENGE;
|
|
51
81
|
/** Only a vendor listed here has a readable answer; the rest are judged by the DOM done-signals. */
|
|
52
82
|
exports.VERDICT_ENDPOINTS = {
|
|
@@ -63,6 +93,10 @@ exports.VERDICT_ENDPOINTS = {
|
|
|
63
93
|
{ marker: 'geetest.com/verify', read: jsonpResult },
|
|
64
94
|
{ marker: 'geetest.com/load', read: urlOnly },
|
|
65
95
|
],
|
|
96
|
+
[kinds_1.Vendor.TENCENT]: [{ marker: '/cap_union_new_verify', read: tencentTicket }],
|
|
97
|
+
[kinds_1.Vendor.YIDUN]: [{ marker: 'dun.163.com/api/v3/check', read: yidunCheck }],
|
|
98
|
+
// Sites serve this from their own hostnames, so the path is what identifies it.
|
|
99
|
+
[kinds_1.Vendor.FUNCAPTCHA]: [{ marker: '/fc/ca/', read: arkoseAnswer }],
|
|
66
100
|
};
|
|
67
101
|
/** The vendor and endpoint whose marker the URL carries, so a listener reads only the bodies it can judge. */
|
|
68
102
|
function endpointFor(url) {
|
package/package.json
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "captchakraken",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"description": "Captcha solver for Playwright and Puppeteer. Finds the captcha, reads it with the v2 pointer model, and clicks, drags, slides or types through to a token \u2014 reCAPTCHA, GeeTest, NetEase Yidun, Tencent, Lemin, Prosopo, Turnstile and distorted text. Hosted API or self-hosted.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
+
"bin": {
|
|
8
|
+
"captchakraken": "bin/captchakraken.js"
|
|
9
|
+
},
|
|
7
10
|
"files": [
|
|
11
|
+
"bin",
|
|
8
12
|
"dist",
|
|
9
13
|
"NOTICE",
|
|
10
14
|
"python",
|
package/python/AGENTS.md
CHANGED
|
@@ -109,8 +109,8 @@ generation and the weights drift apart.
|
|
|
109
109
|
Quote it as written; do not derive, round, or convert anything, and do not
|
|
110
110
|
read a static-image rate as a promise about a browser run.
|
|
111
111
|
- **Never print an API key** into a transcript, a log, or a commit. Use
|
|
112
|
-
`create_api_key`, which writes it to disk instead.
|
|
113
|
-
`.env` hold keys and are never committed.
|
|
112
|
+
`create_api_key`, which writes it to disk instead. `~/.captchakraken/selfhost.json`
|
|
113
|
+
and `.env` hold keys and are never committed.
|
|
114
114
|
- **Midnight V2 4B Q4 is the default self-hosted and hosted model.** The v2
|
|
115
115
|
weights are downloadable under LGPL-3.0-only. Older clients keep using their
|
|
116
116
|
registered chat-completion model because the protocols are not interchangeable.
|
package/python/README.md
CHANGED
|
@@ -63,9 +63,9 @@ pip install "captchakraken[serve]" # + the serving stack (vLLM/torch) to self-
|
|
|
63
63
|
|
|
64
64
|
The base install is lightweight — everything you need to solve captchas against
|
|
65
65
|
a vLLM server (local or remote). The `[serve]` extra pulls the heavy stack only
|
|
66
|
-
if you want to run the model yourself.
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
if you want to run the model yourself. To skip all of that, `pipx run captchakraken
|
|
67
|
+
fetch` asks which model and GPU you want, then installs, downloads and starts it,
|
|
68
|
+
and `captchakraken demo` tries it.
|
|
69
69
|
|
|
70
70
|
## No GPU? Use the hosted API
|
|
71
71
|
|
package/python/pyproject.toml
CHANGED
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "captchakraken"
|
|
7
|
-
version = "4.
|
|
7
|
+
version = "4.1.0"
|
|
8
8
|
description = "Captcha-solving engine and CLI: a v2 pointer model and CNN element detector for image grids, click and drag puzzles, sliders, distorted text and animated challenges. Hosted API or self-hosted on vLLM."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -320,20 +320,90 @@ def _server(args):
|
|
|
320
320
|
try:
|
|
321
321
|
if action == "start":
|
|
322
322
|
return server_manager.start(background=True)
|
|
323
|
+
if action == "ensure":
|
|
324
|
+
server_manager.ensure_server()
|
|
325
|
+
return {"status": "running"}
|
|
323
326
|
if action == "run":
|
|
324
327
|
server_manager.run_foreground()
|
|
325
328
|
if action == "stop":
|
|
326
329
|
return server_manager.stop()
|
|
327
330
|
if action == "status":
|
|
328
331
|
return server_manager.status()
|
|
329
|
-
_fail(f"unknown server action {action!r} (use start|stop|status|run)", 2)
|
|
332
|
+
_fail(f"unknown server action {action!r} (use start|ensure|stop|status|run)", 2)
|
|
330
333
|
except SystemExit:
|
|
331
334
|
raise
|
|
332
335
|
except Exception as e:
|
|
333
336
|
_fail(str(e))
|
|
334
337
|
|
|
335
338
|
|
|
339
|
+
def _print_server_result(result: dict) -> Any:
|
|
340
|
+
from . import server_manager
|
|
341
|
+
|
|
342
|
+
state = result.get("status")
|
|
343
|
+
if state in ("running", "already-running"):
|
|
344
|
+
print(f"Running at {result['base_url']}")
|
|
345
|
+
elif state == "stopped":
|
|
346
|
+
print("Stopped. It stays off until: captchakraken start")
|
|
347
|
+
elif state == "not-running":
|
|
348
|
+
print("Already stopped. It stays off until: captchakraken start")
|
|
349
|
+
else:
|
|
350
|
+
print(f"The server did not come up. Last lines of {server_manager.LOG_FILE}:\n{server_manager.log_tail()}",
|
|
351
|
+
file=sys.stderr)
|
|
352
|
+
sys.exit(1)
|
|
353
|
+
return _SELF_PRINTED
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _start(args):
|
|
357
|
+
from . import config, server_manager
|
|
358
|
+
|
|
359
|
+
if not config.selfhost():
|
|
360
|
+
_fail("Nothing is set up yet. Run: captchakraken fetch")
|
|
361
|
+
print(f"Starting {config.selfhost().get('title')}...", flush=True)
|
|
362
|
+
return _print_server_result(server_manager.start(background=True))
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _stop(args):
|
|
366
|
+
from . import server_manager
|
|
367
|
+
|
|
368
|
+
return _print_server_result(server_manager.stop())
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _status(args):
|
|
372
|
+
from . import server_manager
|
|
373
|
+
|
|
374
|
+
return server_manager.status()
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _demo(args):
|
|
378
|
+
from . import demo
|
|
379
|
+
|
|
380
|
+
sys.exit(demo.main(args))
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
_LEGACY_FETCH_FLAGS = {"--weights-only", "--engine-only", "--no-restart", "--dry-run"}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _fetch_setup(args):
|
|
387
|
+
from . import selfhost
|
|
388
|
+
|
|
389
|
+
parser = argparse.ArgumentParser(prog="captchakraken fetch",
|
|
390
|
+
description="Choose a model, a GPU and a startup mode, then install and start it.")
|
|
391
|
+
parser.add_argument("--yes", "-y", action="store_true", help="ask nothing: previous choices, then the defaults")
|
|
392
|
+
parser.add_argument("--model", default=None, help="with --yes: " + ", ".join(
|
|
393
|
+
m.repo.split("/")[-1] for m in selfhost.MODELS))
|
|
394
|
+
parser.add_argument("--gpu", type=int, default=None, help="with --yes: the nvidia-smi GPU index")
|
|
395
|
+
parser.add_argument("--startup", default=None, choices=[selfhost.ALWAYS_ON, selfhost.FIRST_SOLVE],
|
|
396
|
+
help="with --yes: always on, or start on the first solve")
|
|
397
|
+
opts = parser.parse_args(args)
|
|
398
|
+
if not opts.yes and (opts.model or opts.gpu is not None or opts.startup):
|
|
399
|
+
opts.yes = True
|
|
400
|
+
sys.exit(selfhost.fetch(yes=opts.yes, model=opts.model, gpu=opts.gpu, startup=opts.startup))
|
|
401
|
+
|
|
402
|
+
|
|
336
403
|
def _fetch(args):
|
|
404
|
+
if not _LEGACY_FETCH_FLAGS & set(args):
|
|
405
|
+
return _fetch_setup(args)
|
|
406
|
+
|
|
337
407
|
from . import updater
|
|
338
408
|
|
|
339
409
|
flags = set(args)
|
|
@@ -368,6 +438,10 @@ COMMANDS: Dict[str, Callable[[List[str]], Any]] = {
|
|
|
368
438
|
"serve": _serve,
|
|
369
439
|
"solve-animated": _solve_animated,
|
|
370
440
|
"server": _server,
|
|
441
|
+
"start": _start,
|
|
442
|
+
"stop": _stop,
|
|
443
|
+
"status": _status,
|
|
444
|
+
"demo": _demo,
|
|
371
445
|
"fetch": _fetch,
|
|
372
446
|
"update": _fetch,
|
|
373
447
|
}
|
|
@@ -13,10 +13,56 @@ def pinned() -> Dict[str, Any]:
|
|
|
13
13
|
return json.load(f)
|
|
14
14
|
|
|
15
15
|
|
|
16
|
+
def selfhost_path() -> Path:
|
|
17
|
+
return state_dir() / "selfhost.json"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def runtime_dir() -> Path:
|
|
21
|
+
"""The serving stack `captchakraken fetch` installs."""
|
|
22
|
+
return state_dir() / "runtime"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@lru_cache(maxsize=1)
|
|
26
|
+
def _selfhost_cached(path: str, mtime_ns: int) -> Dict[str, Any]:
|
|
27
|
+
try:
|
|
28
|
+
with open(path, encoding="utf-8") as f:
|
|
29
|
+
values = json.load(f)
|
|
30
|
+
except (OSError, ValueError):
|
|
31
|
+
return {}
|
|
32
|
+
return values if isinstance(values, dict) else {}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def selfhost() -> Dict[str, Any]:
|
|
36
|
+
"""What `captchakraken fetch` chose, or nothing. Read through the file's mtime: every config call lands here."""
|
|
37
|
+
path = selfhost_path()
|
|
38
|
+
try:
|
|
39
|
+
return _selfhost_cached(str(path), path.stat().st_mtime_ns)
|
|
40
|
+
except OSError:
|
|
41
|
+
return {}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
selfhost.cache_clear = _selfhost_cached.cache_clear # type: ignore[attr-defined]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _selfhost_url(values: Dict[str, Any]) -> str:
|
|
48
|
+
return f"http://127.0.0.1:{values.get('port')}/v1"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def selfhost_active() -> Dict[str, Any]:
|
|
52
|
+
"""`selfhost()` unless the caller pointed this process at another endpoint, which then owns every other setting."""
|
|
53
|
+
values = selfhost()
|
|
54
|
+
if not values:
|
|
55
|
+
return {}
|
|
56
|
+
explicit = os.getenv("VLLM_BASE_URL")
|
|
57
|
+
return values if not explicit or explicit.rstrip("/") == _selfhost_url(values) else {}
|
|
58
|
+
|
|
59
|
+
|
|
16
60
|
def base_url() -> str:
|
|
17
|
-
"""Env, then the credentials file, then localhost: a camoufox user who signed up through the MCP had a valid key and no endpoint, so every solve dialled a local port."""
|
|
61
|
+
"""Env, then what `fetch` set up, then the credentials file, then localhost: a camoufox user who signed up through the MCP had a valid key and no endpoint, so every solve dialled a local port."""
|
|
62
|
+
active = selfhost_active()
|
|
18
63
|
return (
|
|
19
64
|
os.getenv("VLLM_BASE_URL")
|
|
65
|
+
or (_selfhost_url(active) if active else "")
|
|
20
66
|
or _base_url_from_credentials_file()
|
|
21
67
|
or f"http://localhost:{port()}/v1"
|
|
22
68
|
)
|
|
@@ -100,8 +146,10 @@ def _base_url_from_credentials_file() -> str:
|
|
|
100
146
|
|
|
101
147
|
|
|
102
148
|
def api_key() -> str:
|
|
149
|
+
# The local server's key first: a hosted key left in the environment could only earn a 401 from it.
|
|
103
150
|
return (
|
|
104
|
-
|
|
151
|
+
selfhost_active().get("key")
|
|
152
|
+
or os.getenv("CAPTCHA_KRAKEN_API_KEY")
|
|
105
153
|
or os.getenv("VLLM_API_KEY")
|
|
106
154
|
or _key_from_credentials_file()
|
|
107
155
|
or "EMPTY"
|
|
@@ -115,7 +163,7 @@ def _registry_default(field: str) -> Optional[str]:
|
|
|
115
163
|
|
|
116
164
|
models = prompts.registered_models()
|
|
117
165
|
entry = None
|
|
118
|
-
pin = os.getenv("CAPTCHA_LORA_ADAPTER") or os.getenv("CAPTCHA_LORA_NAME")
|
|
166
|
+
pin = os.getenv("CAPTCHA_LORA_ADAPTER") or os.getenv("CAPTCHA_LORA_NAME") or selfhost_active().get("model")
|
|
119
167
|
if pin:
|
|
120
168
|
entry = models.get(prompts.canonical_model_id(pin) or "")
|
|
121
169
|
if entry is None:
|
|
@@ -127,14 +175,14 @@ def _registry_default(field: str) -> Optional[str]:
|
|
|
127
175
|
|
|
128
176
|
|
|
129
177
|
def base_model() -> str:
|
|
130
|
-
return os.getenv("CAPTCHA_BASE_MODEL") or _registry_default("base_model") \
|
|
178
|
+
return os.getenv("CAPTCHA_BASE_MODEL") or selfhost_active().get("model") or _registry_default("base_model") \
|
|
131
179
|
or pinned()["base_model"]
|
|
132
180
|
|
|
133
181
|
|
|
134
182
|
def lora_adapter() -> str:
|
|
135
183
|
from . import prompts
|
|
136
184
|
|
|
137
|
-
return (os.getenv("CAPTCHA_LORA_ADAPTER") or prompts.latest_model()
|
|
185
|
+
return (os.getenv("CAPTCHA_LORA_ADAPTER") or selfhost_active().get("model") or prompts.latest_model()
|
|
138
186
|
or pinned()["lora_adapter"])
|
|
139
187
|
|
|
140
188
|
|
|
@@ -148,6 +196,8 @@ def lora_name() -> str:
|
|
|
148
196
|
pin = os.getenv("CAPTCHA_LORA_NAME")
|
|
149
197
|
if pin:
|
|
150
198
|
return pin
|
|
199
|
+
if selfhost_active():
|
|
200
|
+
return _registry_default("lora_name") or pinned()["lora_name"]
|
|
151
201
|
if is_hosted_endpoint():
|
|
152
202
|
hosted = _hosted_default_name()
|
|
153
203
|
if hosted:
|
|
@@ -178,11 +228,26 @@ def _hosted_default_name() -> Optional[str]:
|
|
|
178
228
|
|
|
179
229
|
|
|
180
230
|
def port() -> int:
|
|
181
|
-
return int(os.getenv("VLLM_PORT"
|
|
231
|
+
return int(os.getenv("VLLM_PORT") or selfhost().get("port") or 8000)
|
|
182
232
|
|
|
183
233
|
|
|
184
234
|
def gpu_memory_utilization() -> float:
|
|
185
|
-
return float(os.getenv("VLLM_GPU_MEMORY_UTILIZATION"
|
|
235
|
+
return float(os.getenv("VLLM_GPU_MEMORY_UTILIZATION") or selfhost_active().get("gpu_memory_utilization") or 0.80)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def max_cudagraph_capture_size() -> Optional[int]:
|
|
239
|
+
"""vLLM reserves memory for a compiled graph per batch size up to this; unset leaves vLLM's own default."""
|
|
240
|
+
value = os.getenv("VLLM_MAX_CUDAGRAPH_CAPTURE_SIZE", "").strip() or selfhost_active().get("max_cudagraph_capture_size")
|
|
241
|
+
return int(value) if value else None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def serve_model() -> str:
|
|
245
|
+
"""What the server loads: `fetch`'s download directory, which needs no Hub, or the repo id."""
|
|
246
|
+
return os.getenv("CAPTCHA_BASE_MODEL") or selfhost_active().get("model_path") or base_model()
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def pointer_detector() -> Optional[str]:
|
|
250
|
+
return os.getenv("CAPTCHA_POINTER_DETECTOR") or selfhost_active().get("detector")
|
|
186
251
|
|
|
187
252
|
|
|
188
253
|
def max_model_len() -> int:
|
|
@@ -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())
|
|
@@ -156,6 +156,15 @@
|
|
|
156
156
|
},
|
|
157
157
|
"note": "Midnight V2 4B, GPTQ W4A16, with the pointer heads. The default self-hosted and hosted model. The server owns the fixed prompt and reads the answer from one prefill at /v1/pointer."
|
|
158
158
|
},
|
|
159
|
+
"CaptchaKraken/TwilightV2-2B": {
|
|
160
|
+
"prompt_version": "4",
|
|
161
|
+
"kind": "merged",
|
|
162
|
+
"base_model": "CaptchaKraken/TwilightV2-2B",
|
|
163
|
+
"lora_revision": "main",
|
|
164
|
+
"lora_name": "captcha-pointer",
|
|
165
|
+
"pixel_budget": {"min": 4096, "max": 518400},
|
|
166
|
+
"note": "Twilight V2 2B at bf16. The smaller model."
|
|
167
|
+
},
|
|
159
168
|
"CaptchaKraken/MidnightV2-4B": {
|
|
160
169
|
"prompt_version": "4",
|
|
161
170
|
"kind": "merged",
|
|
@@ -19,12 +19,13 @@ from contextlib import contextmanager
|
|
|
19
19
|
from dataclasses import InitVar, dataclass, field
|
|
20
20
|
from typing import AbstractSet, Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple, Union
|
|
21
21
|
|
|
22
|
-
from . import planner
|
|
22
|
+
from . import config, planner
|
|
23
23
|
from .action_types import CaptchaAction
|
|
24
24
|
from .humanize import Humanizer, hold, resolve as resolve_humanizer
|
|
25
25
|
from .kinds import (ActionKind, FrameRole, HumanizationMode, KeyframeMode, PauseKind, Phase, PromptFamily,
|
|
26
26
|
RecaptchaBanner, RetryMode, SettleVerdict, Vendor, Verdict)
|
|
27
27
|
from .selectors import DEFAULT_CONFIG_PATH, DEFAULT_TABLE, SelectorTable, VendorSelectors, WidgetProbe
|
|
28
|
+
from .server_manager import ensure_server
|
|
28
29
|
from .solver import AnimatedRecording, CaptchaSolver, UnsupportedCaptchaError, cut_recording
|
|
29
30
|
from .timing import PhaseBudget, timings_enabled
|
|
30
31
|
from .verdicts import RoundVerdict, VerdictLog
|
|
@@ -2374,6 +2375,9 @@ class PageSolver:
|
|
|
2374
2375
|
return CaptchaWatcher(solver=self, page=page, **options)
|
|
2375
2376
|
|
|
2376
2377
|
def solve(self, page: Any) -> SolveResult:
|
|
2378
|
+
# Loading a model takes as long as the whole solve budget, so a cold server must not spend it.
|
|
2379
|
+
if config.selfhost_active():
|
|
2380
|
+
ensure_server(config.base_url())
|
|
2377
2381
|
start = _now()
|
|
2378
2382
|
usage: List[Dict[str, Any]] = []
|
|
2379
2383
|
self._last_submit_frame_hash = None
|