captchakraken 4.1.1 → 5.0.0-beta.41

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.
Files changed (34) hide show
  1. package/README.md +0 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/kinds.d.ts +2 -0
  4. package/dist/kinds.js +2 -0
  5. package/dist/playwright-types.d.ts +2 -0
  6. package/dist/selectors.d.ts +19 -10
  7. package/dist/selectors.js +7 -18
  8. package/dist/solver.d.ts +52 -2
  9. package/dist/solver.js +213 -21
  10. package/package.json +2 -2
  11. package/python/AGENTS.md +5 -4
  12. package/python/README.md +3 -6
  13. package/python/pyproject.toml +6 -9
  14. package/python/src/captchakraken/__init__.py +1 -1
  15. package/python/src/captchakraken/captchakraken.config.json +53 -8
  16. package/python/src/captchakraken/cli.py +2 -47
  17. package/python/src/captchakraken/config.py +0 -4
  18. package/python/src/captchakraken/kinds.py +2 -0
  19. package/python/src/captchakraken/models.json +15 -14
  20. package/python/src/captchakraken/page_solver.py +191 -24
  21. package/python/src/captchakraken/pointer/__init__.py +7 -9
  22. package/python/src/captchakraken/pointer/elements.py +1 -1
  23. package/python/src/captchakraken/pointer/server.py +13 -17
  24. package/python/src/captchakraken/pointer/service.py +35 -324
  25. package/python/src/captchakraken/prompts.py +3 -4
  26. package/python/src/captchakraken/selectors.py +15 -16
  27. package/python/src/captchakraken/selfhost.py +9 -16
  28. package/python/src/captchakraken/server_manager.py +0 -4
  29. package/python/src/captchakraken/solver.py +4 -25
  30. package/python/src/captchakraken/tool_calls/find_checkbox.py +150 -13
  31. package/python/src/captchakraken/tool_calls/find_grid.py +6 -132
  32. package/python/src/captchakraken/tool_calls/slide_tracker.py +10 -1
  33. package/python/src/captchakraken/updater.py +57 -27
  34. package/python/src/captchakraken/pointer/detector.py +0 -333
@@ -1,25 +1,17 @@
1
- """Board in, answer out: the detector, the marks, one vLLM prefill, the decode.
1
+ """Board in, answer out: one vLLM prefill of the bare board, then the decode.
2
2
 
3
- svc = PointerService("/models/pointer-0.8b", detector="/models/detector_r18.pt")
3
+ svc = PointerService("/models/pointer-0.8b")
4
4
  svc.solve(image=PIL.Image) # a still
5
5
  svc.solve(frames=[rgb arrays]) # a video, `clipvideo`-cut
6
6
 
7
- A still is resized to `layout.board_size`; the detector runs on that, and the
8
- elements it finds are drawn on it (`marks`). A video's frames are detected one
9
- by one, linked across the clip (`elements.track`, so an element keeps one number)
10
- and drawn on every frame. With no detector, or `marked=False`, the board goes
11
- plain. The prompt text is the same for every board (`layout.chat`). The answer is
12
- generation 3's shape, plus the 1-based number of the element under each point
13
- (`elements.ids_for`) when the board was marked, and `checks`: how sure each
14
- decision was, and whether each point's element is the one the model read off
15
- the marks (`cross_check`).
16
-
17
- Needs the `serve` extra (vLLM, torch, torchvision).
7
+ A still is resized to `layout.board_size` and sent as it is: nothing is detected
8
+ or drawn on it. The prompt text is the same for every board (`layout.chat`). The
9
+ answer is generation 3's shape, plus `checks`: how sure each decision was.
10
+
11
+ Needs the `serve` extra (vLLM, torch).
18
12
  """
19
13
  from __future__ import annotations
20
14
 
21
- import collections
22
- import math
23
15
 
24
16
  from pathlib import Path
25
17
  from typing import Dict, List, Optional, Sequence, Union
@@ -30,7 +22,6 @@ from PIL import Image
30
22
  from .. import clipvideo as CV
31
23
  from . import elements as E
32
24
  from . import layout as L
33
- from . import marks as M
34
25
  from . import vllm_plugin
35
26
 
36
27
 
@@ -143,232 +134,8 @@ def same_effect(a: Dict, b: Dict) -> bool:
143
134
  return all(same(x, y) for x, y in zip(pa, pb))
144
135
 
145
136
 
146
- #: Cyrillic capitals the Latin alphabet draws identically. The letter detector reads one
147
- #: box at a time and cannot tell which script a box is in, so readings are compared folded.
148
- HOMOGLYPHS_FROM, HOMOGLYPHS_TO = "АВЕКМНОРСТУХаеорсух", "ABEKMHOPCTYXaeopcyx"
149
- HOMOGLYPHS = str.maketrans(HOMOGLYPHS_FROM, HOMOGLYPHS_TO)
150
- _TO_CYRILLIC = str.maketrans(HOMOGLYPHS_TO, HOMOGLYPHS_FROM)
151
-
152
-
153
- def fold(text: str) -> str:
154
- """`text` as the letter detector can be held to it: lookalike scripts and case merged."""
155
- return (text or "").translate(HOMOGLYPHS).casefold().translate(HOMOGLYPHS)
156
-
157
-
158
- #: Two letter boxes overlapping this much are one letter read twice.
159
- SAME_LETTER_IOU = 0.4
160
-
161
-
162
- def _iou(a: Sequence[float], b: Sequence[float]) -> float:
163
- w = min(a[2], b[2]) - max(a[0], b[0])
164
- h = min(a[3], b[3]) - max(a[1], b[1])
165
- if w <= 0 or h <= 0:
166
- return 0.0
167
- inter = w * h
168
- return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
169
-
170
-
171
- def letter_slots(dets: Sequence[Dict]) -> List[Dict]:
172
- """The letter detector's boxes -> its letters, left to right: {"box", "score", "chars":
173
- {folded character: score}}. The detector suppresses overlaps within a class only, so
174
- one glyph comes back as each lookalike it resembles (A and Cyrillic А, 0 and O): of
175
- boxes overlapping by SAME_LETTER_IOU, the surest stands for the letter and the rest
176
- are its other readings."""
177
- slots: List[Dict] = []
178
- for d in sorted(dets, key=lambda d: -d["score"]):
179
- home = next((s for s in slots if _iou(d["box"], s["box"]) >= SAME_LETTER_IOU), None)
180
- if home is None:
181
- slots.append({"box": d["box"], "score": d["score"], "char": d["class"], "chars": {}, "show": {}})
182
- home = slots[-1]
183
- c = fold(d["class"])
184
- home["chars"][c] = max(home["chars"].get(c, 0.0), d["score"])
185
- home["show"].setdefault(c, d["class"])
186
- return sorted(slots, key=lambda s: s["box"][0] + s["box"][2])
187
-
188
-
189
- def _script(c: str) -> str:
190
- if "\u4e00" <= c <= "\u9fff":
191
- return "han"
192
- if "\u0400" <= c <= "\u04ff":
193
- return "cyrillic"
194
- return "latin" if c.isalpha() else "digit"
195
-
196
-
197
- def in_board_script(slots: Sequence[Dict], like: str) -> List[Dict]:
198
- """`slots` with the readings no letter of the board's script could be: the board is
199
- in the script most of `like` (the model's text) is, and a 王 on a Latin board is the
200
- detector's guess at a stroke, not a letter of the code. Cyrillic boards keep Latin
201
- readings, which `fold` made of their lookalikes. A box left with no reading is still
202
- a box: `fuse` may count it, but the model names it."""
203
- seen = collections.Counter(_script(c) for c in like or "" if _script(c) != "digit")
204
- board = seen.most_common(1)[0][0] if seen else None
205
- if board is None:
206
- return list(slots)
207
- allowed = {board, "digit", *(("latin",) if board == "cyrillic" else ())}
208
- return [{**s, "chars": {c: p for c, p in s["chars"].items() if _script(c) in allowed}} for s in slots]
209
-
210
-
211
- def letter_slots_counted(slots: Sequence[Dict]) -> List[Dict]:
212
- """The letters of `letter_slots` sure enough to count (LETTER_MIN_SCORE)."""
213
- return [s for s in slots if s["score"] >= LETTER_MIN_SCORE]
214
-
215
-
216
- def typed_chars(d: Dict, detokenize, stop_id: int) -> List[Dict]:
217
- """The decision's typed characters as `fuse` takes them: each marker's top choice
218
- and runner-up, {"chars": {folded: p}, "show": {folded: as typed}}."""
219
- out = []
220
- for t, p, a, ap in zip(d["text_ids"], d["text_p"], d["text_alt_ids"], d["text_alt_p"]):
221
- if t == stop_id:
222
- break
223
- chars: Dict[str, float] = {}
224
- show: Dict[str, str] = {}
225
- for i, q in ((t, p), (a, ap)):
226
- if i == stop_id:
227
- continue
228
- c = detokenize([i])
229
- chars[fold(c)] = chars.get(fold(c), 0.0) + q
230
- show.setdefault(fold(c), c)
231
- out.append({"chars": chars, "show": show})
232
- return out
233
-
234
-
235
- def read_letters(dets: Sequence[Dict]) -> str:
236
- """The letter detector's boxes -> the code they spell, left to right.
237
-
238
- The detector suppresses overlaps within a class only, so one glyph comes back as
239
- each lookalike it resembles (A and Cyrillic А, P and Р): of boxes overlapping by
240
- SAME_LETTER_IOU, the surest stands for the letter."""
241
- return "".join(s["char"] for s in letter_slots_counted(letter_slots(dets)))
242
-
243
-
244
- #: A letter box this sure counts as a letter in `read_letters`; fainter ones are left to
245
- #: `fuse`, which keeps one only when the model typed something there too.
246
- LETTER_MIN_SCORE = 0.3
247
- #: The faintest box `fuse` is shown (the detector's own default floor is 0.3).
248
- FAINTEST_LETTER = 0.05
249
- #: `fuse`'s odds. A character neither reader proposed is worth MODEL_FLOOR / CNN_FLOOR of
250
- #: a proposal. A model character with no box under it is a letter the detector missed
251
- #: (CNN_MISSED) or a marker that landed on a letter already read (MODEL_EXTRA, DOUBLED
252
- #: when it repeats its neighbour: R99VK for R9VK, the model's usual slip); a box the
253
- #: model typed nothing for is a letter the model skipped (MODEL_MISSED) or noise.
254
- MODEL_FLOOR, CNN_FLOOR = 0.2, 0.2
255
- CNN_MISSED, MODEL_EXTRA, DOUBLED = 0.05, 0.1, 0.3
256
- MODEL_MISSED = 0.03
257
- #: Joint readings tried before the model's own answers.
258
- FUSED_TRIES = 2
259
-
260
-
261
- def fuse(model: Sequence[Dict], slots: Sequence[Dict]) -> List[Dict]:
262
- """The code both readers support. `model`: the typed characters in order, each
263
- {"chars": {folded character: p}, "show": {folded: as typed}} (the head's top choice
264
- and runner-up); `slots`: `letter_slots`. The two are aligned in reading order, and
265
- every position picks the character with the most evidence from both, so the model
266
- fixes a box the detector misread and the boxes fix a doubled or wrong model letter.
267
-
268
- -> the chosen characters, each {"char", "margin"}: margin is the log odds of the
269
- choice over the runner-up character at that place (inf when there was none), the
270
- place a retry should change first."""
271
- lg = math.log
272
- n, m = len(model), len(slots)
273
- NEG = -1e18
274
- best = [[NEG] * (m + 1) for _ in range(n + 1)]
275
- back: List[List[Optional[tuple]]] = [[None] * (m + 1) for _ in range(n + 1)]
276
- best[0][0] = 0.0
277
-
278
- def pick(mc: Dict, cc: Dict):
279
- cands = sorted(((lg(mc.get(c, 0.0) + MODEL_FLOOR) + lg(cc.get(c, 0.0) + CNN_FLOOR), c)
280
- for c in {*mc, *cc}), reverse=True)
281
- if len(cands) == 1:
282
- return cands[0][0], cands[0][1], None, math.inf
283
- return cands[0][0], cands[0][1], cands[1][1], cands[0][0] - cands[1][0]
284
-
285
- def top(chars: Dict):
286
- if not chars:
287
- return None, 0.0
288
- c = max(chars, key=chars.get)
289
- return c, chars[c]
290
- for i in range(n + 1):
291
- for j in range(m + 1):
292
- here = best[i][j]
293
- if here == NEG:
294
- continue
295
- if i < n and j < m:
296
- sc, c, alt, margin = pick(model[i]["chars"], slots[j]["chars"])
297
- step = (i, j, c, alt, margin)
298
- if here + sc > best[i + 1][j + 1]:
299
- best[i + 1][j + 1], back[i + 1][j + 1] = here + sc, step
300
- if i < n:
301
- c, p = top(model[i]["chars"])
302
- doubled = any(top(model[k]["chars"])[0] == c for k in (i - 1, i + 1) if 0 <= k < n)
303
- keep, drop = lg(CNN_MISSED) + lg(p), lg(DOUBLED if doubled else MODEL_EXTRA)
304
- sc = max(keep, drop)
305
- if here + sc > best[i + 1][j]:
306
- best[i + 1][j] = here + sc
307
- back[i + 1][j] = (i, j, *((c, None) if keep >= drop else (None, c)), abs(keep - drop))
308
- if j < m:
309
- c, p = top(slots[j]["chars"])
310
- keep = lg(MODEL_MISSED) + lg(p) if c is not None else -math.inf
311
- drop = lg(1.0 - p + 1e-6)
312
- sc = max(keep, drop)
313
- if here + sc > best[i][j + 1]:
314
- best[i][j + 1] = here + sc
315
- back[i][j + 1] = (i, j, *((c, None) if keep >= drop else (None, c)), abs(keep - drop))
316
- out: List[Dict] = []
317
- i, j = n, m
318
- while (i, j) != (0, 0):
319
- pi, pj, c, alt, margin = back[i][j]
320
-
321
- def show(c):
322
- if c is None:
323
- return ""
324
- return (model[pi]["show"].get(c) if pi < i else None) or (slots[pj]["show"].get(c) if pj < j else None) or c
325
- out.append({"char": show(c), "alt": show(alt), "margin": margin})
326
- i, j = pi, pj
327
- return out[::-1]
328
-
329
-
330
- def fused_texts(model: Sequence[Dict], slots: Sequence[Dict], tries: int = 2) -> List[str]:
331
- """`fuse`'s code, then the code with its least sure choice made the other way (the
332
- runner-up character, or a letter kept or dropped), and so on: `tries` distinct codes,
333
- written in the board's script (`_in_board_script`; a board whose script no letter
334
- tells is tried in Latin, then Cyrillic, before any letter changes). With no box
335
- found, the model's own text alone."""
336
- if not model:
337
- return []
338
- if not slots:
339
- return _in_board_script("".join(m["show"][max(m["chars"], key=m["chars"].get)] for m in model), slots)[:tries]
340
- steps = fuse(model, slots)
341
- out = _in_board_script("".join(s["char"] for s in steps), slots)
342
- for k in sorted(range(len(steps)), key=lambda k: steps[k]["margin"]):
343
- if len(out) >= tries or steps[k]["margin"] == math.inf:
344
- break
345
- text = _in_board_script("".join(s["alt"] if q == k else s["char"] for q, s in enumerate(steps)), slots)[0]
346
- if text and text not in out:
347
- out.append(text)
348
- return [t for t in out if t][:tries]
349
-
350
-
351
- def _in_board_script(text: str, slots: Sequence[Dict]) -> List[str]:
352
- """`text` with each lookalike letter written in the board's script, a typed Cyrillic
353
- Р is not the P a Latin board asks for: the script its letters that have no lookalike
354
- are in, in `text` and in the detector's reading. With none to tell (ЕСКХ), or as
355
- many each way, Latin, the script nearly every live board is in, then Cyrillic: the
356
- detector's classes for a lookalike are no guide on real boards (it reads Х in a
357
- Latin 6X6XXT), and the model types Latin for both."""
358
- look = set(HOMOGLYPHS_FROM + HOMOGLYPHS_TO)
359
- seen = collections.Counter(_script(c) for c in text + "".join(s["char"] for s in slots)
360
- if c not in look and _script(c) in ("latin", "cyrillic"))
361
- latin, cyrillic = text.translate(HOMOGLYPHS), text.translate(_TO_CYRILLIC)
362
- if seen["cyrillic"] > seen["latin"]:
363
- return [cyrillic]
364
- if seen["latin"] > seen["cyrillic"] or latin == cyrillic:
365
- return [latin]
366
- return [latin, cyrillic]
367
-
368
-
369
137
  def read_answers(d: Dict, size, els, detokenize, stop_id: Optional[int],
370
- timestamps=None, avoid: Sequence[Dict] = (), letters: Optional[Sequence[Dict]] = None,
371
- top: int = 3) -> List[Dict]:
138
+ timestamps=None, avoid: Sequence[Dict] = (), top: int = 3) -> List[Dict]:
372
139
  """Unpacked decisions -> the likeliest distinct answers, best first.
373
140
 
374
141
  `avoid`: answers already performed on this board and refused. `top` answers are
@@ -377,45 +144,22 @@ def read_answers(d: Dict, size, els, detokenize, stop_id: Optional[int],
377
144
  goes back onto one already tried. With every variant refused, the heads' own
378
145
  answer is the one that comes back.
379
146
 
380
- `letters`: the letter detector's letters on a typed board (`letter_slots`). The
381
- code typed is the one the model and the detector read together (`fused_texts`):
382
- first their joint reading, then it with its least sure choice made the other way,
383
- then the model's own `variants`, then the detector's reading. `checks` carries the
384
- detector's reading and whether it spells what the model read on its own (`fold`ed):
385
- two readers that agree are almost always right (all 25 such real boards), and the
386
- fusion matters where they do not."""
147
+ `els`: numbered elements on the board, when the caller marked it (the client
148
+ sends every board bare and passes none)."""
387
149
  if top < 1:
388
150
  raise ValueError("top must be at least 1")
389
151
  grid = L.token_grid(size)
390
152
  if timestamps is not None and els:
391
153
  els = E.on_frame(els, E.moment_frame(d["moment"], len(els[0]["frames"])))
392
154
  order = L.variants(d, stop_id)
393
- reading = model = slots = None
394
- if letters is not None and stop_id is not None and L._chosen(order[0])[0] == "type":
395
- chars = typed_chars(d, detokenize, stop_id)
396
- model = "".join(c["show"][max(c["chars"], key=c["chars"].get)] for c in chars)
397
- slots = in_board_script(letters, model)
398
- reading = "".join(s["char"] for s in letter_slots_counted(letters))
399
- joint = [{**order[0], "typed": t, **({"retry": "joint reading"} if k else {})}
400
- for k, t in enumerate(fused_texts(chars, slots, FUSED_TRIES))]
401
- order = [*joint, *order, {**order[0], "typed": _in_board_script(reading, slots)[0],
402
- "retry": "letter detector's reading"}]
403
155
  first = None
404
156
  answers: List[Dict] = []
405
157
  for v in order:
406
158
  ids = v["text_ids"]
407
159
  if stop_id is not None and stop_id in ids:
408
160
  ids = ids[:ids.index(stop_id)]
409
- text = v.get("typed")
410
- if text is None:
411
- text = detokenize(ids)
412
- if slots is not None and L._chosen(v)[0] == "type":
413
- text = _in_board_script(text, slots)[0]
414
- ans = L.answer(v, grid, text=text, timestamps=timestamps)
161
+ ans = L.answer(v, grid, text=detokenize(ids), timestamps=timestamps)
415
162
  ans = cross_check(_distinct_drags(_distinct_clicks(E.ids_for(ans, size, els), els)), size, els)
416
- if reading is not None and ans["action"] == "type":
417
- ans["checks"]["letters"] = reading
418
- ans["checks"]["letters_agree"] = fold(model) == fold(reading)
419
163
  first = first or ans
420
164
  if any(same_effect(ans, r) for r in avoid):
421
165
  continue
@@ -428,15 +172,14 @@ def read_answers(d: Dict, size, els, detokenize, stop_id: Optional[int],
428
172
 
429
173
 
430
174
  def read_answer(d: Dict, size, els, detokenize, stop_id: Optional[int],
431
- timestamps=None, avoid: Sequence[Dict] = (), letters: Optional[Sequence[Dict]] = None) -> Dict:
175
+ timestamps=None, avoid: Sequence[Dict] = ()) -> Dict:
432
176
  """The single likeliest answer; `read_answers` with `top=1`."""
433
- return read_answers(d, size, els, detokenize, stop_id, timestamps, avoid, letters, top=1)[0]
177
+ return read_answers(d, size, els, detokenize, stop_id, timestamps, avoid, top=1)[0]
434
178
 
435
179
 
436
180
  class PointerService:
437
- def __init__(self, checkpoint: Union[str, Path], detector: Union[str, Path, None] = None,
438
- gpu_memory_utilization: float = 0.45, max_model_len: int = 8192,
439
- letters: Union[str, Path, None] = None, **llm_kwargs):
181
+ def __init__(self, checkpoint: Union[str, Path], gpu_memory_utilization: float = 0.45,
182
+ max_model_len: int = 8192, **llm_kwargs):
440
183
  vllm_plugin.register()
441
184
  from transformers import AutoProcessor
442
185
  from vllm import LLM
@@ -453,30 +196,17 @@ class PointerService:
453
196
  limit_mm_per_prompt={"image": 1 + L.MAX_HISTORY, "video": 1},
454
197
  mm_processor_kwargs={"min_pixels": 64 * 64, "max_pixels": L.MAX_PIXELS},
455
198
  enable_prefix_caching=False, **llm_kwargs)
456
- self.detector = None
457
- if detector is not None:
458
- from .detector import Detector
459
- self.detector = Detector(detector)
460
- #: The letter detector (`scripts/build_glyph_dataset.py` in the Finetune repo): on a board the
461
- #: model types into, the characters it finds, left to right (`read_answer`'s `letters`).
462
- self.letters = None
463
- if letters is not None:
464
- from .detector import Detector
465
- self.letters = Detector(letters)
466
199
 
467
200
  # ── one board ────────────────────────────────────────────────────────────
468
- def _shown(self, image: Image.Image, marked: bool):
469
- """(the board at the size the model sees, its numbered elements, the
470
- picture sent): the same for a screen sent now or again as history."""
471
- board = image.convert("RGB").resize(L.board_size(*image.size), Image.LANCZOS)
472
- els = E.number(self.detector.detect(board)) if (marked and self.detector is not None) else []
473
- return board, els, (M.draw(board, els) if els else board)
201
+ def _shown(self, image: Image.Image) -> Image.Image:
202
+ """The board at the size the model sees: the same for a screen sent now or again as history."""
203
+ return image.convert("RGB").resize(L.board_size(*image.size), Image.LANCZOS)
474
204
 
475
205
  def prepare(self, image: Optional[Image.Image] = None, frames: Optional[Sequence[np.ndarray]] = None,
476
- marked: bool = True, history: Sequence[Image.Image] = ()) -> Dict:
206
+ history: Sequence[Image.Image] = ()) -> Dict:
477
207
  """The request vLLM gets, and what decoding its answer needs. `history`:
478
- the puzzle's earlier screens, oldest first, as they were sent (marked the
479
- same way), so the prompt up to them is the one already cached."""
208
+ the puzzle's earlier screens, oldest first, as they were sent, so the
209
+ prompt up to them is the one already cached."""
480
210
  if (image is None) == (frames is None):
481
211
  raise ValueError("give exactly one of image or frames")
482
212
  if frames is not None and history:
@@ -488,24 +218,16 @@ class PointerService:
488
218
  raise ValueError(f"frames are {w}x{h}; cut them with clipvideo.clip_video first")
489
219
  meta = {"fps": CV.FPS, "frames_indices": list(range(n)), "total_num_frames": n,
490
220
  "duration": n / CV.FPS, "video_backend": "opencv", "do_sample_frames": False}
491
- tracks = []
492
- if marked and self.detector is not None:
493
- ims = [Image.fromarray(f) for f in fr]
494
- tracks = E.track([E.number(self.detector.detect(im)) for im in ims])
495
- if tracks:
496
- fr = np.stack([np.asarray(M.draw(im, E.on_frame(tracks, k)))
497
- for k, im in enumerate(ims)])
498
221
  prompt = L.chat(self.processor, True).replace(L.VIDEO_PAD, L.VLLM_VIDEO)
499
222
  return {"request": {"prompt": prompt,
500
223
  "multi_modal_data": {"video": (fr, meta)},
501
224
  "mm_processor_kwargs": {"do_sample_frames": False}},
502
- "size": (w, h), "elements": tracks, "shown": None,
503
- "timestamps": CV.pair_timestamps(n)}
504
- board, els, shown = self._shown(image, marked)
505
- earlier = [self._shown(h, marked)[2] for h in history]
225
+ "size": (w, h), "shown": None, "timestamps": CV.pair_timestamps(n)}
226
+ board = self._shown(image)
227
+ earlier = [self._shown(h) for h in history]
506
228
  return {"request": {"prompt": L.chat(self.processor, False, history=len(earlier)),
507
- "multi_modal_data": {"image": [*earlier, shown] if earlier else shown}},
508
- "size": board.size, "elements": els, "shown": shown, "timestamps": None, "board": board}
229
+ "multi_modal_data": {"image": [*earlier, board] if earlier else board}},
230
+ "size": board.size, "shown": board, "timestamps": None}
509
231
 
510
232
  def decode_answers(self, prep: Dict, vector: Sequence[float], avoid: Sequence[Dict] = (),
511
233
  top: int = 3) -> List[Dict]:
@@ -516,38 +238,27 @@ class PointerService:
516
238
  raise ValueError(f"vLLM saw {int(per_moment)} tokens per moment, the board has {grid}: "
517
239
  "the processor resized it, so points would be misplaced")
518
240
  d = L.unpack(v[:L.PACKED])
519
- return read_answers(d, prep["size"], prep["elements"], self.processor.tokenizer.decode, self.stop_id,
520
- prep["timestamps"], avoid, self.count_letters(prep, d), top)
241
+ return read_answers(d, prep["size"], [], self.processor.tokenizer.decode, self.stop_id,
242
+ prep["timestamps"], avoid, top)
521
243
 
522
244
  def decode(self, prep: Dict, vector: Sequence[float], avoid: Sequence[Dict] = ()) -> Dict:
523
245
  """The single likeliest answer; `decode_answers` with `top=1`."""
524
246
  return self.decode_answers(prep, vector, avoid, 1)[0]
525
247
 
526
- def count_letters(self, prep: Dict, d: Dict) -> Optional[List[Dict]]:
527
- """The letter detector's `letter_slots` on a still the heads would type into; else None."""
528
- if self.letters is None or prep.get("board") is None:
529
- return None
530
- if L.ACTIONS[max(range(len(L.ACTIONS)), key=lambda k: d["action_p"][k])] != "type":
531
- return None
532
- return letter_slots(self.letters.detect(prep["board"], min_score=FAINTEST_LETTER))
533
-
534
248
  def solve(self, image: Optional[Image.Image] = None, frames: Optional[Sequence[np.ndarray]] = None,
535
- marked: bool = True, history: Sequence[Image.Image] = (), avoid: Sequence[Dict] = (),
536
- top: int = 3) -> Dict:
249
+ history: Sequence[Image.Image] = (), avoid: Sequence[Dict] = (), top: int = 3) -> Dict:
537
250
  """-> {"answer": the likeliest generation-3 dict, "answers": the `top` likeliest
538
- distinct ones, "elements": numbered elements (board px; a video's are
539
- `elements.track` tracks), "shown": the image the model saw (None for a video),
540
- "size": board (W, H)}. `avoid`: see `read_answers`."""
541
- return self.solve_many([{"image": image, "frames": frames, "marked": marked, "history": history,
542
- "avoid": avoid}], top=top)[0]
251
+ distinct ones, "shown": the image the model saw (None for a video), "size":
252
+ board (W, H)}. `avoid`: see `read_answers`."""
253
+ return self.solve_many([{"image": image, "frames": frames, "history": history, "avoid": avoid}],
254
+ top=top)[0]
543
255
 
544
256
  def solve_many(self, boards: List[Dict], top: int = 3) -> List[Dict]:
545
- preps = [self.prepare(b.get("image"), b.get("frames"), b.get("marked", True), b.get("history", ()))
257
+ preps = [self.prepare(b.get("image"), b.get("frames"), b.get("history", ()))
546
258
  for b in boards]
547
259
  outs = self.llm.embed([p["request"] for p in preps], use_tqdm=False)
548
260
  results = []
549
261
  for b, p, o in zip(boards, preps, outs):
550
262
  answers = self.decode_answers(p, o.outputs.embedding, b.get("avoid", ()), top)
551
- results.append({"answer": answers[0], "answers": answers, "elements": p["elements"],
552
- "shown": p["shown"], "size": p["size"]})
263
+ results.append({"answer": answers[0], "answers": answers, "shown": p["shown"], "size": p["size"]})
553
264
  return results
@@ -191,7 +191,7 @@ BUILTIN_PROMPTS = {
191
191
  ),
192
192
  },
193
193
  # Generation 4 is the pointer (`captchakraken.pointer`): the board goes to the server's /pointer endpoint,
194
- # which numbers its elements with the element detector, builds the prompt itself and reads the answer from one
194
+ # which builds the prompt itself and reads the answer from one
195
195
  # prefill. The client sends no prompt text, so there is none to drift.
196
196
  "4": {
197
197
  "pointer": True,
@@ -263,13 +263,12 @@ def availability(model: Optional[str]) -> Availability:
263
263
 
264
264
 
265
265
  def is_licensed(model: Optional[str]) -> bool:
266
- # PRIVATE is not a softer LICENSED: refusing a licensed model early replaces a RepositoryNotFoundError that
267
- # reads as "not logged in" with the truth, but refusing a private one would stop our own token pulling weights.
266
+ # A licensed model's Hub refusal means "buy a licence", not "log in": fetch words it differently from a private one.
268
267
  return availability(model) == Availability.LICENSED
269
268
 
270
269
 
271
270
  def requires_auth(model: Optional[str]) -> bool:
272
- return availability(model) == Availability.PRIVATE
271
+ return availability(model) in (Availability.PRIVATE, Availability.LICENSED)
273
272
 
274
273
 
275
274
  @dataclass
@@ -43,6 +43,9 @@ class VendorSelectors:
43
43
  fresh: Optional[str] = None
44
44
  # Inside the challenge frame: the pictures a board is made of; the driver waits for each to have painted.
45
45
  images: Sequence[str] = ()
46
+ # Inside the challenge frame: the tiles of the board's grid, in reading order. Where each one is placed is read
47
+ # from the DOM, to click it and to watch it reload.
48
+ tiles: Sequence[str] = ()
46
49
  # Inside the widget: the vendor's own submit control, tried after the generic text probes.
47
50
  submit: Sequence[str] = ()
48
51
  # Inside the challenge frame: verdict banners and what each means.
@@ -55,6 +58,12 @@ class VendorSelectors:
55
58
  text_input: Sequence[str] = ()
56
59
  # Inside the widget: the knob a slide must start on; a drag from the piece moves nothing.
57
60
  slider_handle: Sequence[str] = ()
61
+ # Beside the widget (a sibling of it, or of its parent): a strip the vendor draws outside the widget element that
62
+ # every board carries, such as Yidun's prompt and slider bar. The shot takes it in.
63
+ bar: Sequence[str] = ()
64
+ # Inside the widget's frame or a frame nested in it: the board itself, when the widget frame pads it (Proton's
65
+ # 682x600 frame around its 370x534 `.protonCaptchaContainer`). The shot is this element.
66
+ board: Sequence[str] = ()
58
67
  # Inside the widget: the piece, measured to steer the slide and dragged directly when there is no track.
59
68
  piece: Sequence[str] = ()
60
69
  # Inside the widget: the control that deals a new puzzle, pressed when the model answers `refresh`.
@@ -140,28 +149,18 @@ def _entry(where: str, raw: Any, hosts_required: bool = True) -> VendorSelectors
140
149
  return VendorSelectors(**kw)
141
150
 
142
151
 
143
- #: The element detector a config may choose (see `pointer.detector`).
144
- DETECTOR_CHOICES = ("auto", "standard", "lite")
145
-
146
-
147
152
  class SelectorConfig(NamedTuple):
148
- """A loaded config: the caller's own entry, every vendor's in detection order, the generic fallbacks, and which
149
- element detector runs."""
153
+ """A loaded config: the caller's own entry, every vendor's in detection order, and the generic fallbacks."""
150
154
  custom: Optional[VendorSelectors]
151
155
  vendors: Mapping[Vendor, VendorSelectors]
152
156
  generic: Mapping[str, Tuple[str, ...]]
153
- detector: str = "auto"
154
157
 
155
158
 
156
159
  def _parse(name: str, doc: Mapping[str, Any], base: Optional[SelectorConfig]) -> SelectorConfig:
157
160
  for key in doc:
161
+ # `detector` chose an element detector the client no longer has; a config written for one still loads.
158
162
  if not key.startswith("_") and key not in ("detector", "custom", "vendors", "generic"):
159
- raise SelectorConfigError(f"{name}: {key}: not a config key (detector, custom, vendors, generic)")
160
- detector = base.detector if base else "auto"
161
- if "detector" in doc:
162
- if not isinstance(doc["detector"], str) or doc["detector"].strip().lower() not in DETECTOR_CHOICES:
163
- raise SelectorConfigError(f"{name}: detector: {doc['detector']!r} is not one of {', '.join(DETECTOR_CHOICES)}")
164
- detector = doc["detector"].strip().lower()
163
+ raise SelectorConfigError(f"{name}: {key}: not a config key (custom, vendors, generic)")
165
164
  custom = base.custom if base else None
166
165
  if "custom" in doc:
167
166
  custom = None if doc["custom"] is None else _entry(f"{name}: custom", doc["custom"], hosts_required=False)
@@ -193,7 +192,7 @@ def _parse(name: str, doc: Mapping[str, Any], base: Optional[SelectorConfig]) ->
193
192
  generic[key] = _strings(f"{name}: generic.{key}", value)
194
193
  if base is None and set(generic) != set(_GENERIC):
195
194
  raise SelectorConfigError(f"{name}: generic: missing {sorted(set(_GENERIC) - set(generic))}")
196
- return SelectorConfig(custom, vendors, generic, detector)
195
+ return SelectorConfig(custom, vendors, generic)
197
196
 
198
197
 
199
198
  def load_config(source: Optional[ConfigSource] = None) -> SelectorConfig:
@@ -257,8 +256,8 @@ class SelectorTable:
257
256
  self.response: Sequence[str] = tuple(s.response for _, s in self.vendors if s.response)
258
257
  self.accepted: Sequence[str] = tuple(s.accepted for _, s in self.vendors if s.accepted)
259
258
  # A real Verify/Next/Submit/Skip/Confirm first; the vendor-named controls are fallbacks.
260
- self.submit: Sequence[str] = (*map(submit_by_text, loaded.generic["submit_text"]),
261
- *self._of_every_vendor("submit"))
259
+ self.submit_vendor: Sequence[str] = self._of_every_vendor("submit")
260
+ self.submit: Sequence[str] = (*map(submit_by_text, loaded.generic["submit_text"]), *self.submit_vendor)
262
261
  # Vendor-named first, generic last: the driver takes the first visible match, and a generic selector
263
262
  # reached before the vendor's own is how a captcha's answer ends up in a login form's username box.
264
263
  self.text_input_vendor: Sequence[str] = self._of_every_vendor("text_input")
@@ -20,9 +20,6 @@ from typing import Callable, List, NamedTuple, Optional, Sequence
20
20
 
21
21
  from . import __version__, config, server_manager
22
22
 
23
- DETECTOR_REPO = "CaptchaKraken/CaptchaKrakenV2-CNN-large"
24
- DETECTOR_FILE = "detector_r18.pt"
25
-
26
23
  ALWAYS_ON = "always"
27
24
  FIRST_SOLVE = "first-solve"
28
25
 
@@ -241,18 +238,15 @@ def install_client(python: Path, extra: str = "") -> None:
241
238
 
242
239
  _DOWNLOAD = """
243
240
  import sys
244
- from huggingface_hub import hf_hub_download, snapshot_download
241
+ from huggingface_hub import snapshot_download
245
242
  print(snapshot_download(sys.argv[1]))
246
- print(hf_hub_download(sys.argv[2], sys.argv[3]))
247
243
  """
248
244
 
249
245
 
250
- def download(python: Path, repo: str) -> "tuple[str, str]":
251
- """(model directory, detector file). Stored as paths so a server never asks the Hub again."""
252
- out = subprocess.run([str(python), "-c", _DOWNLOAD, repo, DETECTOR_REPO, DETECTOR_FILE],
253
- stdout=subprocess.PIPE, text=True, check=True)
254
- model_path, detector = out.stdout.strip().splitlines()[-2:]
255
- return model_path, detector
246
+ def download(python: Path, repo: str) -> str:
247
+ """The model directory. Stored as a path so a server never asks the Hub again."""
248
+ out = subprocess.run([str(python), "-c", _DOWNLOAD, repo], stdout=subprocess.PIPE, text=True, check=True)
249
+ return out.stdout.strip().splitlines()[-1]
256
250
 
257
251
 
258
252
  def free_port(start: int = 8000) -> int:
@@ -267,13 +261,12 @@ def free_port(start: int = 8000) -> int:
267
261
  raise RuntimeError(f"No free port between {start} and {start + 99}.")
268
262
 
269
263
 
270
- def settings(choice: Choice, model_path: str, detector: str, saved: dict) -> dict:
264
+ def settings(choice: Choice, model_path: str, saved: dict) -> dict:
271
265
  small = choice.gpu.total_mib < SMALL_CARD_MIB
272
266
  return {
273
267
  "model": choice.model.repo,
274
268
  "title": choice.model.title,
275
269
  "model_path": model_path,
276
- "detector": detector,
277
270
  "gpu": choice.gpu.index,
278
271
  "gpu_name": choice.gpu.name,
279
272
  "startup": choice.startup,
@@ -332,10 +325,10 @@ def install(choice: Choice, saved: dict) -> dict:
332
325
  python = make_venv(config.runtime_dir())
333
326
  install_client(python, "[serve]")
334
327
 
335
- _step(f"Downloading {choice.model.title} and the element detector")
336
- model_path, detector = download(python, choice.model.repo)
328
+ _step(f"Downloading {choice.model.title}")
329
+ model_path = download(python, choice.model.repo)
337
330
 
338
- values = settings(choice, model_path, detector, saved)
331
+ values = settings(choice, model_path, saved)
339
332
  write_settings(values)
340
333
  config.selfhost.cache_clear()
341
334
 
@@ -88,14 +88,10 @@ def build_serve_command() -> "list[str]":
88
88
  from . import prompts
89
89
 
90
90
  if prompts.resolve(config.lora_adapter()).pointer:
91
- detector = config.pointer_detector()
92
- if not detector:
93
- raise RuntimeError("No detector is set up for the pointer server. Run: captchakraken fetch")
94
91
  capture = config.max_cudagraph_capture_size()
95
92
  return [
96
93
  _serve_python(), "-m", "captchakraken.pointer.server",
97
94
  "--model", config.serve_model(),
98
- "--detector", detector,
99
95
  "--host", os.getenv("CAPTCHA_POINTER_HOST", "127.0.0.1"),
100
96
  "--port", str(config.port()),
101
97
  "--gpu-memory-utilization", str(config.gpu_memory_utilization()),