captchakraken 4.2.0 → 5.0.0-beta.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +0 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/kinds.d.ts +1 -0
  4. package/dist/kinds.js +1 -0
  5. package/dist/playwright-types.d.ts +4 -0
  6. package/dist/puppeteer-adapter.d.ts +2 -0
  7. package/dist/puppeteer-adapter.js +34 -2
  8. package/dist/selectors.d.ts +22 -11
  9. package/dist/selectors.js +9 -19
  10. package/dist/solver.d.ts +49 -4
  11. package/dist/solver.js +177 -47
  12. package/package.json +2 -2
  13. package/python/AGENTS.md +5 -4
  14. package/python/README.md +3 -6
  15. package/python/pyproject.toml +6 -9
  16. package/python/src/captchakraken/__init__.py +1 -1
  17. package/python/src/captchakraken/captchakraken.config.json +43 -9
  18. package/python/src/captchakraken/cli.py +2 -47
  19. package/python/src/captchakraken/config.py +0 -4
  20. package/python/src/captchakraken/kinds.py +1 -0
  21. package/python/src/captchakraken/models.json +15 -14
  22. package/python/src/captchakraken/page_solver.py +168 -49
  23. package/python/src/captchakraken/pointer/__init__.py +7 -9
  24. package/python/src/captchakraken/pointer/elements.py +1 -1
  25. package/python/src/captchakraken/pointer/server.py +13 -17
  26. package/python/src/captchakraken/pointer/service.py +35 -324
  27. package/python/src/captchakraken/prompts.py +3 -4
  28. package/python/src/captchakraken/selectors.py +19 -17
  29. package/python/src/captchakraken/selfhost.py +9 -16
  30. package/python/src/captchakraken/server_manager.py +0 -4
  31. package/python/src/captchakraken/solver.py +4 -25
  32. package/python/src/captchakraken/tool_calls/find_checkbox.py +150 -13
  33. package/python/src/captchakraken/tool_calls/find_grid.py +6 -132
  34. package/python/src/captchakraken/updater.py +57 -27
  35. package/python/src/captchakraken/pointer/detector.py +0 -333
@@ -1,20 +1,20 @@
1
1
  """The /pointer HTTP endpoint: one board per request, generation 3's answer back.
2
2
 
3
- python -m captchakraken.pointer.server --model /models/pointer-0.8b \\
4
- --detector /models/detector_r18.pt --port 8001
3
+ python -m captchakraken.pointer.server --model /models/pointer-0.8b --port 8001
5
4
 
6
5
  POST /v1/pointer
7
6
  {"image": "<base64 PNG/JPEG>"} a still, as captured
8
7
  {"frames": ["<base64 JPEG>", ...], "fps": 5.0} a video, `clipvideo`-cut
9
- {"marked": false} optional: skip the detector
10
8
  {"avoid": [answer, ...]} optional: answers already refused on this
11
9
  board; the likeliest other ones come back
12
10
  -> {"actions": [{...}, {...}, {...}], the three likeliest distinct answers, best first
13
11
  "answer": {...}, the first action, kept for older callers
14
- "elements": [{"id", "class", "box", "score"}], "size": [W, H]}
12
+ "elements": [], "size": [W, H]}
15
13
 
16
- `elements` are in the pixels of the board as the model saw it (`size`), numbered
17
- as the answer's ids are. The client sends no prompt: the server owns it.
14
+ `size` is the board in pixels as the model saw it. `elements` is always empty and
15
+ `marked` in a request is ignored: both are left from the element detector, which
16
+ the client no longer has, so older callers keep working. The client sends no
17
+ prompt: the server owns it.
18
18
  """
19
19
  from __future__ import annotations
20
20
 
@@ -45,7 +45,6 @@ def parse(body: Dict) -> Dict:
45
45
  """A request body -> PointerService.solve's arguments. Raises ValueError on a bad one."""
46
46
  if ("image" in body) == ("frames" in body):
47
47
  raise ValueError("send exactly one of image or frames")
48
- marked = bool(body.get("marked", True))
49
48
  avoid = body.get("avoid") or []
50
49
  if not isinstance(avoid, list) or not all(isinstance(a, dict) for a in avoid):
51
50
  raise ValueError("avoid is a list of earlier answers")
@@ -55,7 +54,7 @@ def parse(body: Dict) -> Dict:
55
54
  if "image" in body:
56
55
  if len(history) > L.MAX_HISTORY:
57
56
  raise ValueError(f"{len(history)} earlier screens; at most {L.MAX_HISTORY}")
58
- return {"image": _image(body["image"]), "marked": marked, "avoid": avoid,
57
+ return {"image": _image(body["image"]), "avoid": avoid,
59
58
  "history": [_image(h) for h in history]}
60
59
  if history:
61
60
  raise ValueError("a video board carries no earlier screens")
@@ -65,14 +64,12 @@ def parse(body: Dict) -> Dict:
65
64
  frames = [np.asarray(Image.open(io.BytesIO(base64.b64decode(f))).convert("RGB")) for f in body["frames"]]
66
65
  if len(frames) < 2:
67
66
  raise ValueError("a video needs at least two frames")
68
- return {"frames": frames, "marked": False, "avoid": avoid}
67
+ return {"frames": frames, "avoid": avoid}
69
68
 
70
69
 
71
70
  def reply(result: Dict) -> Dict:
72
71
  return {"actions": result.get("answers") or [result["answer"]],
73
- "answer": result["answer"], "size": list(result["size"]),
74
- "elements": [{"id": n, "class": e["class"], "box": [round(v, 1) for v in e["box"]],
75
- "score": e["score"]} for n, e in enumerate(result["elements"], 1)]}
72
+ "answer": result["answer"], "size": list(result["size"]), "elements": []}
76
73
 
77
74
 
78
75
  def make_handler(service):
@@ -129,9 +126,9 @@ def make_handler(service):
129
126
  def main():
130
127
  ap = argparse.ArgumentParser()
131
128
  ap.add_argument("--model", required=True, help="an exported pointer checkpoint")
132
- ap.add_argument("--detector", default=None, help="the element detector; without it every board goes plain")
133
- ap.add_argument("--letters", default=None,
134
- help="the letter detector: a typed code is the one it and the model read together")
129
+ # Left from the element and letter detectors; a unit file that still passes them starts the same server.
130
+ ap.add_argument("--detector", default=None, help=argparse.SUPPRESS)
131
+ ap.add_argument("--letters", default=None, help=argparse.SUPPRESS)
135
132
  ap.add_argument("--host", default="127.0.0.1")
136
133
  ap.add_argument("--port", type=int, default=8001)
137
134
  ap.add_argument("--gpu-memory-utilization", type=float, default=0.45)
@@ -140,8 +137,7 @@ def main():
140
137
  a = ap.parse_args()
141
138
  from .service import PointerService
142
139
  capture = a.max_cudagraph_capture_size
143
- svc = PointerService(a.model, detector=a.detector, letters=a.letters,
144
- gpu_memory_utilization=a.gpu_memory_utilization,
140
+ svc = PointerService(a.model, gpu_memory_utilization=a.gpu_memory_utilization,
145
141
  **({"compilation_config": {"max_cudagraph_capture_size": capture}} if capture else {}))
146
142
  ThreadingHTTPServer((a.host, a.port), make_handler(svc)).serve_forever()
147
143
 
@@ -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