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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""The `captchakraken` CLI: one-shot solves, the
|
|
1
|
+
"""The `captchakraken` CLI: one-shot solves, the detector tool calls, the CV worker, and server management.
|
|
2
2
|
|
|
3
3
|
`captchakraken image.png [model] [api_provider] [api_key] [--puzzle-source ...]` solves one still.
|
|
4
4
|
Exit codes: 1 failure, 2 unsupported puzzle, 3 the hosted API refused.
|
|
@@ -16,7 +16,6 @@ from .errors import CaptchaKrakenAPIError
|
|
|
16
16
|
from .kinds import Outcome, PromptFamily, RetryMode, Vendor
|
|
17
17
|
from .solver import CaptchaSolver, UnsupportedCaptchaError
|
|
18
18
|
|
|
19
|
-
|
|
20
19
|
_SELF_PRINTED = object()
|
|
21
20
|
|
|
22
21
|
|
|
@@ -59,12 +58,10 @@ def match_region(ref: str, live: str, cx: float, cy: float, tolerance: Optional[
|
|
|
59
58
|
|
|
60
59
|
The neighbourhood only: a whole-frame match would need every unrelated sprite to align and would essentially never open.
|
|
61
60
|
"""
|
|
62
|
-
import
|
|
63
|
-
|
|
64
|
-
from .keyframes import MATCH_REGION_TOLERANCE, region_box, region_diff_ratio
|
|
61
|
+
from .keyframes import MATCH_REGION_TOLERANCE, read_frame, region_box, region_diff_ratio
|
|
65
62
|
|
|
66
63
|
tol = MATCH_REGION_TOLERANCE if tolerance is None else float(tolerance)
|
|
67
|
-
a, b =
|
|
64
|
+
a, b = read_frame(ref), read_frame(live)
|
|
68
65
|
if a is None or b is None:
|
|
69
66
|
return {"match": False, "diff": 1.0, "error": "unreadable image"}
|
|
70
67
|
d = region_diff_ratio(a, b, region_box(a.shape[1::-1], (cx, cy)))
|
|
@@ -77,12 +74,36 @@ def board_painted(image: str, floor=None, box=None) -> dict:
|
|
|
77
74
|
return board_is_painted(image, floor, box)
|
|
78
75
|
|
|
79
76
|
|
|
80
|
-
def
|
|
81
|
-
|
|
77
|
+
def slide_step(req: dict) -> dict:
|
|
78
|
+
"""One look of the slide loop (`tool_calls/slide_tracker.py`); a lost or unseen object is `{"error"}`, never a
|
|
79
|
+
position, so the driver releases rather than steering by a guess."""
|
|
80
|
+
from .tool_calls.slide_tracker import TrackingError
|
|
81
|
+
from .tool_calls.slide_tracker import slide_step as step
|
|
82
|
+
|
|
83
|
+
def pt(v):
|
|
84
|
+
return None if v is None else (float(v[0]), float(v[1]))
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
return step(req["first"], req["probe"], req["current"], probe_s=req["probe_s"], s=req["s"],
|
|
88
|
+
goal=pt(req["goal"]), seed=pt(req.get("seed")), handle=pt(req.get("handle")),
|
|
89
|
+
bounds=tuple(req["bounds"]) if req.get("bounds") else None,
|
|
90
|
+
history=req.get("history") or (), tol=float(req.get("tol") or 2.0))
|
|
91
|
+
except TrackingError as e:
|
|
92
|
+
return {"error": str(e)}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def fill_step(req: dict) -> dict:
|
|
96
|
+
"""One look at a held widget's fill (`tool_calls/fill_tracker.py`); an unreadable line is `{"error"}`, never a
|
|
97
|
+
release, so the driver keeps holding on the widget's own signals."""
|
|
98
|
+
from .tool_calls.fill_tracker import FillError
|
|
99
|
+
from .tool_calls.fill_tracker import fill_step as step
|
|
82
100
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
101
|
+
try:
|
|
102
|
+
return step(req["first"], req["current"], start=tuple(req["start"]), end=tuple(req["end"]), t=float(req["t"]),
|
|
103
|
+
history=req.get("history") or (), poll_s=float(req.get("poll_s") or 0.25),
|
|
104
|
+
tol=float(req.get("tol") or 2.0), first_t=req.get("first_t"))
|
|
105
|
+
except FillError as e:
|
|
106
|
+
return {"error": str(e)}
|
|
86
107
|
|
|
87
108
|
|
|
88
109
|
def _find_grid(args):
|
|
@@ -164,10 +185,16 @@ def _board_painted(args):
|
|
|
164
185
|
return board_painted(args[0], float(args[1]) if len(args) > 1 else None)
|
|
165
186
|
|
|
166
187
|
|
|
167
|
-
def
|
|
168
|
-
_need(args,
|
|
169
|
-
|
|
170
|
-
|
|
188
|
+
def _slide_step(args):
|
|
189
|
+
_need(args, 1, "slide-step request.json (or the JSON itself)")
|
|
190
|
+
raw = args[0]
|
|
191
|
+
return slide_step(json.loads(open(raw).read() if os.path.exists(raw) else raw))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _fill_step(args):
|
|
195
|
+
_need(args, 1, "fill-step request.json (or the JSON itself)")
|
|
196
|
+
raw = args[0]
|
|
197
|
+
return fill_step(json.loads(open(raw).read() if os.path.exists(raw) else raw))
|
|
171
198
|
|
|
172
199
|
|
|
173
200
|
def _report_outcome(args):
|
|
@@ -212,8 +239,10 @@ def _serve(args):
|
|
|
212
239
|
return board_painted(req["image"], req.get("floor"), req.get("box"))
|
|
213
240
|
if cmd == "find-checkbox":
|
|
214
241
|
return find_checkbox(req["image"])
|
|
215
|
-
if cmd == "
|
|
216
|
-
return
|
|
242
|
+
if cmd == "slide-step":
|
|
243
|
+
return slide_step(req)
|
|
244
|
+
if cmd == "fill-step":
|
|
245
|
+
return fill_step(req)
|
|
217
246
|
raise ValueError(f"unknown cmd: {cmd!r}")
|
|
218
247
|
|
|
219
248
|
sys.stdout.write(json.dumps({"ready": True}) + "\n")
|
|
@@ -249,7 +278,7 @@ def _run_solve(query: Callable[[], dict]) -> None:
|
|
|
249
278
|
|
|
250
279
|
|
|
251
280
|
def _solve_animated(args):
|
|
252
|
-
"""
|
|
281
|
+
"""Solve a recorded burst (zero-padded PNGs in `--frames-dir`) as the model's prompt generation asks it."""
|
|
253
282
|
import glob
|
|
254
283
|
|
|
255
284
|
parser = argparse.ArgumentParser(prog="captchakraken solve-animated")
|
|
@@ -264,20 +293,21 @@ def _solve_animated(args):
|
|
|
264
293
|
_fail(f"no frames in {opts.frames_dir}")
|
|
265
294
|
|
|
266
295
|
def query():
|
|
267
|
-
import
|
|
296
|
+
from .keyframes import read_frame
|
|
297
|
+
from .solver import cut_recording
|
|
268
298
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
imgs = [im for im in (cv2.imread(p) for p in frames) if im is not None]
|
|
299
|
+
imgs = [im for im in (read_frame(p) for p in frames) if im is not None]
|
|
272
300
|
if not imgs:
|
|
273
301
|
_fail("no frame decoded")
|
|
274
|
-
|
|
275
|
-
paths = [os.path.abspath(p) for p in write_keyframes(kfset, os.path.join(opts.frames_dir, "keyframes"), stem="challenge")]
|
|
302
|
+
recording = cut_recording(imgs, float(opts.fps), os.path.abspath(os.path.join(opts.frames_dir, "keyframes")))
|
|
276
303
|
solver = CaptchaSolver(model=opts.model, api_key=opts.api_key, expert=opts.expert)
|
|
277
|
-
result = solver.
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
"
|
|
304
|
+
result = solver.solve_animated(recording)
|
|
305
|
+
kfset = recording.keyframes
|
|
306
|
+
return {"actions": [a.model_dump() for a in result],
|
|
307
|
+
"fallbacks": [[a.model_dump() for a in plan] for plan in solver.pointer_fallback_actions()],
|
|
308
|
+
"token_usage": solver.planner.token_usage,
|
|
309
|
+
"keyframes": recording.keyframe_paths, "keyframe_mode": kfset.mode,
|
|
310
|
+
"steady_screens": kfset.steady_screens, "source_frames": len(imgs)}
|
|
281
311
|
|
|
282
312
|
_run_solve(query)
|
|
283
313
|
return _SELF_PRINTED
|
|
@@ -290,20 +320,90 @@ def _server(args):
|
|
|
290
320
|
try:
|
|
291
321
|
if action == "start":
|
|
292
322
|
return server_manager.start(background=True)
|
|
323
|
+
if action == "ensure":
|
|
324
|
+
server_manager.ensure_server()
|
|
325
|
+
return {"status": "running"}
|
|
293
326
|
if action == "run":
|
|
294
327
|
server_manager.run_foreground()
|
|
295
328
|
if action == "stop":
|
|
296
329
|
return server_manager.stop()
|
|
297
330
|
if action == "status":
|
|
298
331
|
return server_manager.status()
|
|
299
|
-
_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)
|
|
300
333
|
except SystemExit:
|
|
301
334
|
raise
|
|
302
335
|
except Exception as e:
|
|
303
336
|
_fail(str(e))
|
|
304
337
|
|
|
305
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
|
+
|
|
306
403
|
def _fetch(args):
|
|
404
|
+
if not _LEGACY_FETCH_FLAGS & set(args):
|
|
405
|
+
return _fetch_setup(args)
|
|
406
|
+
|
|
307
407
|
from . import updater
|
|
308
408
|
|
|
309
409
|
flags = set(args)
|
|
@@ -332,11 +432,16 @@ COMMANDS: Dict[str, Callable[[List[str]], Any]] = {
|
|
|
332
432
|
"grid-cell-states-fixed": _grid_cell_states_fixed,
|
|
333
433
|
"match-region": _match_region,
|
|
334
434
|
"board-painted": _board_painted,
|
|
335
|
-
"
|
|
435
|
+
"slide-step": _slide_step,
|
|
436
|
+
"fill-step": _fill_step,
|
|
336
437
|
"report-outcome": _report_outcome,
|
|
337
438
|
"serve": _serve,
|
|
338
439
|
"solve-animated": _solve_animated,
|
|
339
440
|
"server": _server,
|
|
441
|
+
"start": _start,
|
|
442
|
+
"stop": _stop,
|
|
443
|
+
"status": _status,
|
|
444
|
+
"demo": _demo,
|
|
340
445
|
"fetch": _fetch,
|
|
341
446
|
"update": _fetch,
|
|
342
447
|
}
|
|
@@ -371,15 +476,20 @@ def main():
|
|
|
371
476
|
help="Force one expert of a routed model. Also CAPTCHA_EXPERT.")
|
|
372
477
|
parser.add_argument("--text-mode", action="store_true",
|
|
373
478
|
help="The widget has a text box, so the answer is typed rather than clicked.")
|
|
479
|
+
parser.add_argument("--history", action="append", default=[],
|
|
480
|
+
help="An earlier screen of the same paged puzzle, oldest first (repeatable).")
|
|
374
481
|
args = parser.parse_args()
|
|
375
482
|
_image(args.image_path)
|
|
376
483
|
|
|
377
484
|
def query():
|
|
378
485
|
solver = CaptchaSolver(model=args.model, api_key=args.api_key, expert=args.expert)
|
|
486
|
+
solver.planner.pointer_history = list(args.history)
|
|
379
487
|
result = solver.solve(args.image_path, puzzle_source=args.puzzle_source,
|
|
380
488
|
retry_mode=args.retry_mode, text_mode=args.text_mode)
|
|
381
489
|
actions = [a.model_dump() for a in result] if isinstance(result, list) else result.model_dump()
|
|
382
|
-
return {"actions": actions,
|
|
490
|
+
return {"actions": actions,
|
|
491
|
+
"fallbacks": [[a.model_dump() for a in plan] for plan in solver.pointer_fallback_actions()],
|
|
492
|
+
"token_usage": solver.planner.token_usage}
|
|
383
493
|
|
|
384
494
|
_run_solve(query)
|
|
385
495
|
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Turn a recorded captcha clip into the frames the model watches as video.
|
|
2
|
+
|
|
3
|
+
Models on prompt generation 3 and later see an animated captcha through the video pathway rather than as
|
|
4
|
+
numbered stills: every two consecutive frames share one temporal patch, so motion reaches the vision encoder
|
|
5
|
+
directly. The frames travel as a JPEG sequence (`data:video/jpeg;base64,f0,f1,...`), so no codec is involved
|
|
6
|
+
and the server does not resample them. The model labels its answer with the time printed before a frame
|
|
7
|
+
pair (`"t": 1.3`), and `time_to_index` turns that back into the recorded frame the driver waits for.
|
|
8
|
+
|
|
9
|
+
A verbatim port of the module the model was trained with: if this copy trimmed, sampled or sized a clip
|
|
10
|
+
differently, the time the model answers with would name a different moment than the one it watched.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import io
|
|
16
|
+
import math
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import List, Optional, Sequence, Tuple
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from PIL import Image
|
|
22
|
+
|
|
23
|
+
from .keyframes import to_gray
|
|
24
|
+
|
|
25
|
+
#: Bump when the cutting LOGIC changes in a way the constants below do not show;
|
|
26
|
+
#: cached frame sets carry it and are re-cut on mismatch (`clips.materialize_video`).
|
|
27
|
+
CUT_VERSION = 3
|
|
28
|
+
FPS = 5.0
|
|
29
|
+
MAX_FRAMES = 32
|
|
30
|
+
JPEG_QUALITY = 90
|
|
31
|
+
SIZE_FACTOR = 64
|
|
32
|
+
TEMPORAL_PATCH = 2
|
|
33
|
+
LOOP_RATIO = 0.5
|
|
34
|
+
LOOP_MIN_PERIOD_S = 0.6
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class ClipVideo:
|
|
39
|
+
frames: List[np.ndarray]
|
|
40
|
+
source_indices: List[int]
|
|
41
|
+
source_fps: float
|
|
42
|
+
period: Optional[int] = None
|
|
43
|
+
fps: float = FPS
|
|
44
|
+
timestamps: List[float] = field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
def __post_init__(self) -> None:
|
|
47
|
+
if not self.timestamps:
|
|
48
|
+
self.timestamps = pair_timestamps(len(self.frames), self.fps)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def frame_size(height: int, width: int, max_pixels: int) -> Tuple[int, int]:
|
|
52
|
+
"""(H, W): multiples of SIZE_FACTOR, area <= max_pixels.
|
|
53
|
+
|
|
54
|
+
The largest such frame whose aspect is within ~10% of the clip's; the closest
|
|
55
|
+
aspect only when none is. Most area first, because a 64-grid rarely hits the
|
|
56
|
+
exact aspect and a perfect-aspect frame half the size is a worse picture.
|
|
57
|
+
"""
|
|
58
|
+
aspect = height / width
|
|
59
|
+
cands = [(h, w) for h in range(SIZE_FACTOR, 4097, SIZE_FACTOR)
|
|
60
|
+
for w in range(SIZE_FACTOR, 4097, SIZE_FACTOR) if h * w <= max_pixels]
|
|
61
|
+
if not cands:
|
|
62
|
+
return SIZE_FACTOR, SIZE_FACTOR
|
|
63
|
+
err = {c: abs(math.log((c[0] / c[1]) / aspect)) for c in cands}
|
|
64
|
+
close = [c for c in cands if err[c] <= 0.1]
|
|
65
|
+
if close:
|
|
66
|
+
return max(close, key=lambda c: (c[0] * c[1], -err[c]))
|
|
67
|
+
return min(cands, key=lambda c: (err[c], -c[0] * c[1]))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def find_period(frames: Sequence[np.ndarray], source_fps: float) -> Optional[int]:
|
|
71
|
+
"""The period P (in source frames) at which the WHOLE clip repeats, or None.
|
|
72
|
+
|
|
73
|
+
The frame is split into 8x8 blocks. For every block that moves, frames P apart
|
|
74
|
+
must differ by less than LOOP_RATIO of what neighbouring frames differ by in
|
|
75
|
+
that block. Requiring every moving block (not the frame average) matters: one
|
|
76
|
+
object out of step with the others means the clip does NOT loop, and trimming
|
|
77
|
+
it would lose that object's other phase. A false "no loop" only costs tokens.
|
|
78
|
+
"""
|
|
79
|
+
blocks = 8
|
|
80
|
+
g = np.stack([resize_linear(to_gray(f), 128, 128).astype(np.float32) for f in frames])
|
|
81
|
+
n = len(g)
|
|
82
|
+
|
|
83
|
+
def per_block(d: np.ndarray) -> np.ndarray:
|
|
84
|
+
return d.reshape(d.shape[0], blocks, 128 // blocks, blocks, 128 // blocks).mean((2, 4)).mean(0)
|
|
85
|
+
|
|
86
|
+
step = per_block(np.abs(np.diff(g, axis=0)))
|
|
87
|
+
active = step > max(0.25 * float(step.max()), 0.3)
|
|
88
|
+
if not active.any():
|
|
89
|
+
return None
|
|
90
|
+
best_p, best_r = None, LOOP_RATIO
|
|
91
|
+
for p in range(max(2, int(round(LOOP_MIN_PERIOD_S * source_fps))), n - 2):
|
|
92
|
+
r = float((per_block(np.abs(g[p:] - g[:-p]))[active] / step[active]).max())
|
|
93
|
+
if r < best_r:
|
|
94
|
+
best_p, best_r = p, r
|
|
95
|
+
return best_p
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def pair_timestamps(n_frames: int, fps: float = FPS) -> List[float]:
|
|
99
|
+
"""The `<x.x seconds>` Qwen prints before each frame pair, as floats."""
|
|
100
|
+
n = n_frames + (n_frames % TEMPORAL_PATCH)
|
|
101
|
+
return [round((2 * k + 0.5) / fps, 1) for k in range(n // TEMPORAL_PATCH)]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def sample_indices(n_source: int, source_fps: float, period: Optional[int]) -> List[int]:
|
|
105
|
+
window = period if period else n_source
|
|
106
|
+
step = source_fps / FPS
|
|
107
|
+
idx = [int(round(i * step)) for i in range(int(math.floor((window - 1) / step)) + 1)]
|
|
108
|
+
idx = [i for i in idx if i < window] or [0]
|
|
109
|
+
if len(idx) > MAX_FRAMES:
|
|
110
|
+
idx = [int(round(x)) for x in np.linspace(0, window - 1, MAX_FRAMES)]
|
|
111
|
+
if len(idx) % TEMPORAL_PATCH:
|
|
112
|
+
nxt = min(idx[-1] + max(1, int(round(step))), n_source - 1)
|
|
113
|
+
idx.append(nxt)
|
|
114
|
+
return idx
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def clip_video(frames: Sequence[np.ndarray], source_fps: float, *, max_pixels: int) -> ClipVideo:
|
|
118
|
+
"""The frames the model watches, resized and in order, plus where each came from."""
|
|
119
|
+
if not frames:
|
|
120
|
+
raise ValueError("empty clip")
|
|
121
|
+
source_fps = float(source_fps) if source_fps and source_fps > 0 else 10.0
|
|
122
|
+
period = find_period(frames, source_fps) if len(frames) > 4 else None
|
|
123
|
+
idx = sample_indices(len(frames), source_fps, period)
|
|
124
|
+
h, w = frame_size(frames[0].shape[0], frames[0].shape[1], max_pixels)
|
|
125
|
+
out = [resize_area(frames[i], w, h) for i in idx]
|
|
126
|
+
return ClipVideo(frames=out, source_indices=idx, source_fps=source_fps, period=period)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# The resizes below reproduce OpenCV's uint8 INTER_LINEAR and INTER_AREA bit for bit, because the model was
|
|
130
|
+
# trained on frames OpenCV cut: the same pixels in means the same period found and the same picture watched.
|
|
131
|
+
|
|
132
|
+
def _linear_taps(src: int, dst: int, area: bool,
|
|
133
|
+
clamp: bool) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
134
|
+
"""Along one axis: the two source pixels each output pixel blends, and their 11-bit weights.
|
|
135
|
+
|
|
136
|
+
`area` is INTER_AREA's upscaling rule. Only the horizontal pass clamps its weight at the edges; the vertical
|
|
137
|
+
pass blends the clamped edge row with itself, whose rounded weights need not sum to 2048.
|
|
138
|
+
"""
|
|
139
|
+
inv = dst / src
|
|
140
|
+
d = np.arange(dst)
|
|
141
|
+
if area:
|
|
142
|
+
s = np.floor(d * (1.0 / inv)).astype(np.int64)
|
|
143
|
+
f = ((d + 1) - (s + 1) * inv).astype(np.float32)
|
|
144
|
+
f = np.where(f <= 0, np.float32(0), f - np.floor(f))
|
|
145
|
+
else:
|
|
146
|
+
f = ((d + 0.5) * (1.0 / inv) - 0.5).astype(np.float32)
|
|
147
|
+
s = np.floor(f).astype(np.int64)
|
|
148
|
+
f = f - s.astype(np.float32)
|
|
149
|
+
if clamp:
|
|
150
|
+
edge = (s < 0) | (s >= src - 1)
|
|
151
|
+
f[edge] = 0
|
|
152
|
+
s = np.clip(s, 0, src - 1)
|
|
153
|
+
w1 = np.rint(f * np.float32(2048)).astype(np.int32)
|
|
154
|
+
w0 = np.rint((np.float32(1) - f) * np.float32(2048)).astype(np.int32)
|
|
155
|
+
return np.clip(s, 0, src - 1), np.clip(s + 1, 0, src - 1), w0, w1
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def resize_linear(img: np.ndarray, w: int, h: int, area: bool = False) -> np.ndarray:
|
|
159
|
+
"""A uint8 image resized to (w, h) by OpenCV's fixed-point bilinear, with its SIMD rounding."""
|
|
160
|
+
x0, x1, a0, a1 = _linear_taps(img.shape[1], w, area, clamp=True)
|
|
161
|
+
y0, y1, b0, b1 = _linear_taps(img.shape[0], h, area, clamp=False)
|
|
162
|
+
across = (slice(None),) + (None,) * (img.ndim - 2)
|
|
163
|
+
down = (slice(None),) + (None,) * (img.ndim - 1)
|
|
164
|
+
s = img.astype(np.int32)
|
|
165
|
+
row = (np.take(s, x0, 1) * a0[across] + np.take(s, x1, 1) * a1[across]) >> 4
|
|
166
|
+
out = (((np.take(row, y0, 0) * b0[down]) >> 16) + ((np.take(row, y1, 0) * b1[down]) >> 16) + 2) >> 2
|
|
167
|
+
return out.astype(np.uint8)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _area_taps(src: int, dst: int) -> Tuple[np.ndarray, np.ndarray]:
|
|
171
|
+
"""Along one axis: the source pixels each output pixel averages and their float32 weights, in
|
|
172
|
+
OpenCV's order (padded with zero weights), since float32 sums depend on it."""
|
|
173
|
+
scale = src / dst
|
|
174
|
+
taps = []
|
|
175
|
+
for d in range(dst):
|
|
176
|
+
f1 = d * scale
|
|
177
|
+
f2 = f1 + scale
|
|
178
|
+
s2 = min(math.floor(f2), src - 1)
|
|
179
|
+
s1 = min(math.ceil(f1), s2)
|
|
180
|
+
cell = min(scale, src - f1)
|
|
181
|
+
t = [(s1 - 1, (s1 - f1) / cell)] if s1 - f1 > 1e-3 else []
|
|
182
|
+
t += [(x, 1 / cell) for x in range(s1, s2)]
|
|
183
|
+
t += [(s2, min(min(f2 - s2, 1.0), cell) / cell)] if f2 - s2 > 1e-3 else []
|
|
184
|
+
taps.append(t)
|
|
185
|
+
k = max(map(len, taps))
|
|
186
|
+
idx = np.array([[x for x, _ in t] + [0] * (k - len(t)) for t in taps])
|
|
187
|
+
wt = np.array([[a for _, a in t] + [0.0] * (k - len(t)) for t in taps], dtype=np.float32)
|
|
188
|
+
return idx, wt
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _area_pass(img: np.ndarray, axis: int, dst: int) -> np.ndarray:
|
|
192
|
+
idx, wt = _area_taps(img.shape[axis], dst)
|
|
193
|
+
shape = [1] * img.ndim
|
|
194
|
+
shape[axis] = dst
|
|
195
|
+
out = np.take(img, idx[:, 0], axis) * wt[:, 0].reshape(shape)
|
|
196
|
+
for j in range(1, idx.shape[1]):
|
|
197
|
+
out = out + np.take(img, idx[:, j], axis) * wt[:, j].reshape(shape)
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def resize_area(img: np.ndarray, w: int, h: int) -> np.ndarray:
|
|
202
|
+
"""A uint8 image resized to (w, h) as OpenCV's INTER_AREA does it: a box average shrinking, bilinear growing."""
|
|
203
|
+
H, W = img.shape[:2]
|
|
204
|
+
if w > W or h > H:
|
|
205
|
+
return resize_linear(img, w, h, area=True)
|
|
206
|
+
if W % w == 0 and H % h == 0:
|
|
207
|
+
sx, sy = W // w, H // h
|
|
208
|
+
s = img.astype(np.int64).reshape(h, sy, w, sx, *img.shape[2:]).sum((1, 3))
|
|
209
|
+
if (sx, sy) == (2, 2):
|
|
210
|
+
return ((s + 2) >> 2).astype(np.uint8)
|
|
211
|
+
return np.rint(s.astype(np.float32) * np.float32(1 / (sx * sy))).astype(np.uint8)
|
|
212
|
+
out = _area_pass(_area_pass(img.astype(np.float32), 1, w), 0, h)
|
|
213
|
+
return np.clip(np.rint(out), 0, 255).astype(np.uint8)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def encode_jpeg(frame: np.ndarray) -> bytes:
|
|
217
|
+
"""A BGR frame as JPEG at JPEG_QUALITY with 4:2:0 chroma, the settings the model was trained on."""
|
|
218
|
+
buf = io.BytesIO()
|
|
219
|
+
Image.fromarray(frame[..., ::-1]).save(buf, "JPEG", quality=JPEG_QUALITY, subsampling=2)
|
|
220
|
+
return buf.getvalue()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def data_url(clip: ClipVideo) -> str:
|
|
224
|
+
"""vLLM's `video_url` for this clip: a JPEG sequence, no container, no codec."""
|
|
225
|
+
return "data:video/jpeg;base64," + ",".join(
|
|
226
|
+
base64.b64encode(encode_jpeg(f)).decode("ascii") for f in clip.frames)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def media_io_kwargs(fps: float = FPS) -> dict:
|
|
230
|
+
"""What vLLM must be started with (`--media-io-kwargs`) to read data_url() as sent."""
|
|
231
|
+
return {"video": {"num_frames": -1, "fps": fps}}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def time_to_index(clip: ClipVideo, t: float) -> int:
|
|
235
|
+
"""The SOURCE frame a `"t"` answer names: the first frame of the nearest pair."""
|
|
236
|
+
k = min(range(len(clip.timestamps)), key=lambda i: abs(clip.timestamps[i] - float(t)))
|
|
237
|
+
j = min(TEMPORAL_PATCH * k, len(clip.source_indices) - 1)
|
|
238
|
+
return clip.source_indices[j]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def index_to_time(clip: ClipVideo, source_index: int) -> float:
|
|
242
|
+
"""The `"t"` that names a source frame: the FIRST pair lying wholly at or after it.
|
|
243
|
+
|
|
244
|
+
A label names the first moment the answer is known and clear, so it rounds
|
|
245
|
+
FORWARD by whole pairs, never to the nearest pair. Nearest put the bee's last
|
|
246
|
+
landing (frame 47) on a pair still showing the bee in flight. A frame outside
|
|
247
|
+
the kept loop is folded back into it first; a frame after the last pair takes
|
|
248
|
+
the last pair.
|
|
249
|
+
"""
|
|
250
|
+
s = int(source_index)
|
|
251
|
+
if clip.period:
|
|
252
|
+
s %= clip.period
|
|
253
|
+
idx = clip.source_indices
|
|
254
|
+
for k, ts in enumerate(clip.timestamps):
|
|
255
|
+
pair = idx[TEMPORAL_PATCH * k:TEMPORAL_PATCH * (k + 1)]
|
|
256
|
+
if pair and min(pair) >= s:
|
|
257
|
+
return ts
|
|
258
|
+
return clip.timestamps[-1]
|
|
@@ -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:
|