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,4 +1,4 @@
1
- """Image in, actions out: the element detector plus the model, for one still or one recorded animation."""
1
+ """Image in, actions out: the model, for one still or one recorded animation."""
2
2
 
3
3
  import os
4
4
  import sys
@@ -26,19 +26,12 @@ from .keyframes import KeyframeSet, extract_keyframes, number_for_source_index,
26
26
  from .kinds import ActionKind, PixelAnswerKind, PromptFamily, RetryMode, Vendor
27
27
  from .planner import ActionPlanner
28
28
  from .tool_calls.find_checkbox import find_checkbox
29
- from .tool_calls.find_grid import detect_selected_cells, find_grid, get_numbered_grid_overlay
29
+ from .tool_calls.find_grid import detect_selected_cells, get_numbered_grid_overlay
30
30
 
31
31
  DEBUG = os.getenv("CAPTCHA_DEBUG", "0") == "1"
32
32
  # ~1.2% ≈ ±6px on a 512px challenge.
33
33
  _PIXEL_BOX_HALF = float(os.getenv("CAPTCHA_PIXEL_BOX_HALF", "0.012"))
34
34
 
35
- # The grid expert was trained on reCAPTCHA's 3x3 and 4x4 and hCaptcha's 3x3 and nothing else, so only those
36
- # boards are asked as grids; every other vendor's grid goes to the pixel expert, which was trained on them. A
37
- # caller that names no vendor (the CLI, a script) gets the expert for any 3x3 or 4x4, which is what those boards
38
- # most often are.
39
- GRID_CELL_SHAPES = {9: (3, 3), 16: (4, 4)}
40
- VENDOR_GRID_CELLS: dict[Vendor, frozenset[int]] = {Vendor.HCAPTCHA: frozenset({9}), Vendor.RECAPTCHA: frozenset({9, 16})}
41
-
42
35
 
43
36
  def _debug(message: str) -> None:
44
37
  if DEBUG:
@@ -85,12 +78,6 @@ def _first_frame(path: str) -> Image.Image:
85
78
  raise ValueError(f"Could not read video frame from {path}") from exc
86
79
 
87
80
 
88
- def _grid_dims(n_cells: int, puzzle_source: Vendor = Vendor.UNKNOWN):
89
- vendor = Vendor(puzzle_source)
90
- allowed = frozenset(GRID_CELL_SHAPES) if vendor == Vendor.UNKNOWN else VENDOR_GRID_CELLS.get(vendor, frozenset())
91
- return GRID_CELL_SHAPES[n_cells] if n_cells in allowed else None
92
-
93
-
94
81
  class CaptchaSolver:
95
82
  def __init__(self, model: Optional[str] = None, provider: str = "captchaKrakenApi",
96
83
  api_key: Optional[str] = None, expert: Optional[PromptFamily] = None):
@@ -116,7 +103,6 @@ class CaptchaSolver:
116
103
  img_w, img_h = self._image_size
117
104
 
118
105
  if text_mode:
119
- # A typed captcha's boxed glyphs are exactly the lattice find_grid looks for, so skip it.
120
106
  try:
121
107
  actions = self._solve_pixel(image_path, text_mode=True)
122
108
  except ValueError as exc:
@@ -125,15 +111,8 @@ class CaptchaSolver:
125
111
  return actions
126
112
  raise UnsupportedCaptchaError("Could not read the text captcha")
127
113
 
128
- # Generation 4 never runs find_grid: the pointer server's element detector numbers a grid's cells along with
129
- # everything else on the board, and its answer is points (and element numbers) like any other board's.
130
- grid_boxes = [] if self.planner.prompts.pointer else find_grid(image_path)
131
- dims = _grid_dims(len(grid_boxes), puzzle_source) if grid_boxes else None
132
- if dims:
133
- return self._solve_grid(image_path, grid_boxes, dims[0], dims[1], retry_mode=retry_mode)
134
- if grid_boxes:
135
- _debug(f"find_grid returned {len(grid_boxes)} cells; not solving as a grid")
136
-
114
+ # A board alone carries no grid: its cells are read from the vendor's DOM (`PageSolver`, which asks the grid
115
+ # expert itself), so here a grid is a board like any other and its answer is points.
137
116
  if not self.planner.prompts.pointer:
138
117
  checkbox = find_checkbox(image_path)
139
118
  if checkbox:
@@ -1,21 +1,158 @@
1
1
  """Where the driver clicks first, before any model runs: the tick box of a vendor's
2
- checkbox widget, as the element detector's `checkbox` class finds it. Neither a
3
- false positive nor a false negative raises."""
2
+ checkbox widget, found in a screenshot of the widget with plain pixel arithmetic.
3
+
4
+ An unticked tick box is a square of one flat colour (white, near-black or the
5
+ widget's own background) closed in by an outline. So: mark every pixel whose
6
+ neighbours are the same shade, split those into connected regions, and keep a
7
+ region that fills a square, does not touch the screenshot's edge, and is big
8
+ next to the widget. A ticked box has a check mark inside, so it is not flat; a
9
+ spinner or a passed badge is round, so it does not fill its square; a letter
10
+ like ロ is a square too, but a small one. The largest square left is the box.
11
+
12
+ Neither a false positive nor a false negative raises. Measured on the widgets in
13
+ `tests/fixtures/checkbox/` (reCAPTCHA, hCaptcha, Turnstile and CaptchaFox, light
14
+ and dark, 1x to 2x, in a language none of the thresholds were tuned against).
15
+ """
4
16
 
5
17
  from typing import Optional, Tuple
6
18
 
7
- #: Measured on widgets in a language the detector never trained on: every one of
8
- #: 96 tick boxes scored >= 0.997, a ticked or passed widget 0, and the highest
9
- #: `checkbox` score on 600 real puzzle boards was 0.145. 0.6 sits far from both.
10
- MIN_SCORE = 0.6
19
+ import numpy as np
20
+ from PIL import Image
21
+ from scipy import ndimage
11
22
 
23
+ #: A pixel is flat when its grey level differs from its neighbours (two apart, on
24
+ #: each axis) by less than this. Outlines and antialiased glyph edges are well above it.
25
+ FLAT_GRADIENT = 24.0
26
+ #: The flat region must cover this share of its bounding square: a round spinner
27
+ #: or badge covers pi/4 of it.
28
+ MIN_FILL = 0.88
29
+ #: A box whose flat inside bleeds out through one low-contrast edge (hCaptcha's dark
30
+ #: theme: the bottom outline is nearly the panel's shade, so a ragged tail hangs off
31
+ #: the square and fill drops to 0.87) still has a solid core: most rows run nearly
32
+ #: edge to edge and almost every column is mostly filled. A disc does neither (about
33
+ #: 0.31 of its rows and 0.60 of its columns), nor does a spinner arc or a badge (0).
34
+ MIN_FILL_SOLID_CORE = 0.80
35
+ SOLID_ROW_FILL, MIN_SOLID_ROWS = 0.95, 0.65
36
+ SOLID_COL_FILL, MIN_SOLID_COLS = 0.80, 0.90
37
+ #: A tick box is painted one colour: its inside spans at most this many grey levels
38
+ #: (5th to 95th percentile). A smooth patch of photo (sky, asphalt, a pail's side)
39
+ #: is flat by the gradient test yet spans tens of levels; every tick box measured
40
+ #: spans 0.
41
+ MAX_SPREAD = 8.0
42
+ #: The box sits at the widget's leading edge (left, or right in a right-to-left
43
+ #: locale), inset from it by this many box-widths. A flat square further in, or one
44
+ #: flush against the edge, is part of a puzzle: a grid tile, a slider handle.
45
+ LEADING_INSET = (0.3, 1.2)
46
+ #: Around the box is the widget's own flat panel: on at least MIN_PANEL_SIDES sides,
47
+ #: PANEL_SHARE of a band just outside the outline sits within MAX_SPREAD grey levels
48
+ #: of the band's median. A share, not a range: a label or a test key's warning may
49
+ #: crowd a side (live 2026-11-13, German and Russian widgets). Every tick box
50
+ #: measured has a second side at least 0.87 flat; a drag card on a puzzle's tray
51
+ #: reaches 0.81, a cartoon-grid tile 0.60.
52
+ PANEL_BAND = (0.25, 0.30)
53
+ MIN_PANEL_SIDES = 2
54
+ PANEL_SHARE = 0.85
55
+ #: A tick box is painted a neutral shade (white, near-black, grey): the median of
56
+ #: max(R,G,B) - min(R,G,B) inside it is 0 on every widget measured. A puzzle's
57
+ #: flat coloured tile (a road piece, a red cube face) is well above this.
58
+ MAX_CHROMA = 24
59
+ #: An unticked box is empty: whatever its flat inside encloses (a check mark, a
60
+ #: drag card's drawing, a dot on a counting card) may cover at most this share of it.
61
+ MAX_ENCLOSED = 0.01
62
+ #: Width over height, both ways.
63
+ MAX_ASPECT = 1.25
64
+ #: The box's inside, as a share of the widget's height. Every tick box measured is
65
+ #: at least 0.16 of it; a letter of the widget's text is at most 0.06.
66
+ MIN_SIDE_OF_HEIGHT = 0.10
67
+ #: A flat region larger than this share of the height is a panel, not a box.
68
+ MAX_SIDE_OF_HEIGHT = 0.60
69
+ #: Nor more than this share of the width: the widest measured is hCaptcha's compact
70
+ #: card at 0.19, and a tile of a 4x4 puzzle grid is a quarter of its board.
71
+ MAX_SIDE_OF_WIDTH = 0.23
72
+ #: Smaller than this many pixels is a glyph or a speck, whatever the widget's size.
73
+ MIN_SIDE_PX = 12
74
+
75
+
76
+ def _flat(grey: np.ndarray) -> np.ndarray:
77
+ gx = np.zeros_like(grey)
78
+ gy = np.zeros_like(grey)
79
+ gx[:, 1:-1] = grey[:, 2:] - grey[:, :-2]
80
+ gy[1:-1] = grey[2:] - grey[:-2]
81
+ return np.hypot(gx, gy) < FLAT_GRADIENT
82
+
83
+
84
+ def _fills_its_square(mask: np.ndarray) -> bool:
85
+ fill = mask.mean()
86
+ if fill >= MIN_FILL:
87
+ return True
88
+ return (fill >= MIN_FILL_SOLID_CORE
89
+ and (mask.mean(axis=1) >= SOLID_ROW_FILL).mean() >= MIN_SOLID_ROWS
90
+ and (mask.mean(axis=0) >= SOLID_COL_FILL).mean() >= MIN_SOLID_COLS)
12
91
 
13
- def find_checkbox(image_path: str) -> Optional[Tuple[int, int, int, int]]:
14
- """(x, y, w, h) of the most confident tick box in pixels, or None."""
15
- from ..pointer.detector import detect_file
16
92
 
17
- boxes = [d for d in detect_file(image_path) if d["class"] == "checkbox" and d["score"] >= MIN_SCORE]
18
- if not boxes:
93
+ def _at_leading_edge(x0: int, x1: int, side: float, w_img: int) -> bool:
94
+ lo, hi = LEADING_INSET
95
+ return any(lo * side <= inset <= hi * side for inset in (x0, w_img - x1))
96
+
97
+
98
+ def _sits_on_a_panel(grey: np.ndarray, x0: int, y0: int, x1: int, y1: int, side: float) -> bool:
99
+ o = max(2, int(round(PANEL_BAND[0] * side)))
100
+ k = max(3, int(round(PANEL_BAND[1] * side)))
101
+ X0, Y0, X1, Y1 = max(0, x0 - o), max(0, y0 - o), x1 + o, y1 + o
102
+ flat_sides = 0
103
+ for band in (grey[max(0, Y0 - k):Y0, X0:X1], grey[Y1:Y1 + k, X0:X1],
104
+ grey[Y0:Y1, max(0, X0 - k):X0], grey[Y0:Y1, X1:X1 + k]):
105
+ if band.size and np.mean(np.abs(band - np.median(band)) <= MAX_SPREAD) >= PANEL_SHARE:
106
+ flat_sides += 1
107
+ return flat_sides >= MIN_PANEL_SIDES
108
+
109
+
110
+ def find_checkbox(image_path: str) -> Optional[Tuple[int, int, int, int]]:
111
+ """(x, y, w, h) of the tick box in pixels, or None."""
112
+ try:
113
+ with Image.open(image_path) as im:
114
+ rgb = np.asarray(im.convert("RGB"), np.int16)
115
+ grey = np.asarray(Image.fromarray(rgb.astype(np.uint8)).convert("L"), np.float32)
116
+ except Exception:
117
+ return None
118
+ h_img, w_img = grey.shape
119
+ if h_img < 3 or w_img < 3:
120
+ return None
121
+ labels, _ = ndimage.label(_flat(grey))
122
+ best = None
123
+ for i, sl in enumerate(ndimage.find_objects(labels), 1):
124
+ if sl is None:
125
+ continue
126
+ y0, y1, x0, x1 = sl[0].start, sl[0].stop, sl[1].start, sl[1].stop
127
+ if y0 == 0 or x0 == 0 or y1 == h_img or x1 == w_img:
128
+ continue
129
+ w, h = x1 - x0, y1 - y0
130
+ side = (w + h) / 2
131
+ if min(w, h) < MIN_SIDE_PX or not 1 / MAX_ASPECT <= w / h <= MAX_ASPECT:
132
+ continue
133
+ if not MIN_SIDE_OF_HEIGHT * h_img <= side <= MAX_SIDE_OF_HEIGHT * h_img:
134
+ continue
135
+ if side > MAX_SIDE_OF_WIDTH * w_img:
136
+ continue
137
+ inside = labels[sl] == i
138
+ if not _fills_its_square(inside):
139
+ continue
140
+ if ndimage.binary_fill_holes(inside).sum() - inside.sum() > MAX_ENCLOSED * inside.size:
141
+ continue
142
+ shade = grey[sl][inside]
143
+ if np.percentile(shade, 95) - np.percentile(shade, 5) > MAX_SPREAD:
144
+ continue
145
+ paint = rgb[sl][inside]
146
+ if np.median(paint.max(axis=1) - paint.min(axis=1)) > MAX_CHROMA:
147
+ continue
148
+ if not _at_leading_edge(x0, x1, side, w_img) or not _sits_on_a_panel(grey, x0, y0, x1, y1, side):
149
+ continue
150
+ if best is None or side > best[0]:
151
+ best = (side, x0, y0, w, h)
152
+ if best is None:
19
153
  return None
20
- x0, y0, x1, y1 = max(boxes, key=lambda d: d["score"])["box"]
21
- return int(round(x0)), int(round(y0)), int(round(x1 - x0)), int(round(y1 - y0))
154
+ # The flat inside stops a pixel or two short of the outline; grow it back to the box.
155
+ side, x0, y0, w, h = best
156
+ pad = int(round(0.06 * side)) + 1
157
+ x0, y0 = max(0, x0 - pad), max(0, y0 - pad)
158
+ return x0, y0, min(w_img - x0, w + 2 * pad), min(h_img - y0, h + 2 * pad)
@@ -1,19 +1,15 @@
1
- """A board's grid of tiles, and the state of each tile.
1
+ """The state of each tile of a board's grid, read from pixels.
2
2
 
3
- `find_grid` asks the element detector (`pointer.detector`) for the board's grid
4
- and the cells inside it, and returns the cells in reading order when they make
5
- a whole lattice. The detector was trained on every vendor's boards, grids and
6
- not-grids alike, so a board of cards, a sprite sheet or a keyframe of moving
7
- tiles is simply not a `grid` to it.
8
-
9
- The rest reads pixels inside cells the grid has already given: a vendor's
10
- "selected" mark, a tile still loading, an empty slot, a tile fading in.
3
+ The grid itself comes from the vendor's DOM (`PageSolver._dom_grid`): where the
4
+ challenge frame placed each tile. Given those cells, this reads the pixels inside
5
+ them: a vendor's "selected" mark, a tile still loading, an empty slot, a tile
6
+ fading in.
11
7
  """
12
8
 
13
9
  from __future__ import annotations
14
10
 
15
11
  import tempfile
16
- from typing import List, Optional, Sequence, Tuple
12
+ from typing import List, Optional, Tuple
17
13
 
18
14
  import numpy as np
19
15
  from PIL import Image
@@ -24,128 +20,6 @@ from ..overlay import add_overlays_to_image
24
20
 
25
21
  Box = Tuple[int, int, int, int]
26
22
 
27
- #: Below these the detector is guessing: measured on real captures, every true
28
- #: grid and its cells score above them and no not-grid board's grid does.
29
- GRID_MIN_SCORE = 0.5
30
- CELL_MIN_SCORE = 0.5
31
- #: A row starts where a cell's top sits more than this share of a cell below the row's.
32
- ROW_BREAK = 0.5
33
- #: A tile is a cell whatever else it looks like: a flat-coloured tile (a blank one
34
- #: mid-fade, a plain colour) reads as a jigsaw piece (`draggable`) or an `item`.
35
- #: Inside the grid, one the size of the cells (within this share) that no cell box
36
- #: already covers fills its slot.
37
- TILE_CLASSES = ("draggable", "item")
38
- TILE_SIZE_TOL = 0.25
39
- #: A lattice the detector saw most of: when its cells do not form whole rows (a
40
- #: gutter it missed merges two tiles, a faint one splits none), a grid box whose
41
- #: slots are this share filled, every row and column with at least one, is the
42
- #: lattice. Two real reCAPTCHA 4x4 photo boards came back with 14 and 17 cells.
43
- LATTICE_MIN_FILLED = 0.75
44
-
45
-
46
- def _iou(a: Sequence[float], b: Sequence[float]) -> float:
47
- ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
48
- iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
49
- inter = ix * iy
50
- union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
51
- return inter / union if union > 0 else 0.0
52
-
53
-
54
- def _with_tiles(cells: List[List[float]], tiles: List[List[float]]) -> List[List[float]]:
55
- """`cells` plus every tile the size of a cell that no cell (or tile already taken) overlaps."""
56
- if not cells:
57
- return cells
58
- w = float(np.median([c[2] - c[0] for c in cells]))
59
- h = float(np.median([c[3] - c[1] for c in cells]))
60
- out = list(cells)
61
- for t in tiles:
62
- if abs((t[2] - t[0]) - w) <= TILE_SIZE_TOL * w and abs((t[3] - t[1]) - h) <= TILE_SIZE_TOL * h \
63
- and all(_iou(t, c) < 0.3 for c in out):
64
- out.append(t)
65
- return out
66
-
67
-
68
- def _cells_in(grid: Sequence[float], cells: List[List[float]]) -> List[List[float]]:
69
- x0, y0, x1, y1 = grid
70
- return [c for c in cells if x0 <= (c[0] + c[2]) / 2 <= x1 and y0 <= (c[1] + c[3]) / 2 <= y1]
71
-
72
-
73
- def _rows(cells: List[List[float]]) -> List[List[List[float]]]:
74
- """Cells grouped into rows, top to bottom, each row left to right."""
75
- h = float(np.median([c[3] - c[1] for c in cells]))
76
- rows: List[List[List[float]]] = []
77
- for c in sorted(cells, key=lambda c: c[1]):
78
- if rows and c[1] - rows[-1][0][1] <= ROW_BREAK * h:
79
- rows[-1].append(c)
80
- else:
81
- rows.append([c])
82
- return [sorted(r, key=lambda c: c[0]) for r in rows]
83
-
84
-
85
- def _lattice(grid: Sequence[float], cells: List[List[float]]) -> Optional[List[List[float]]]:
86
- """The rows x columns lattice `cells` mostly fill inside `grid`, each slot at its
87
- column's and row's median edges; None when they do not fill one."""
88
- w = float(np.median([c[2] - c[0] for c in cells]))
89
- h = float(np.median([c[3] - c[1] for c in cells]))
90
- gx0, gy0, gx1, gy1 = grid
91
- centres = [((c[0] + c[2]) / 2, (c[1] + c[3]) / 2) for c in cells]
92
-
93
- def pitch(axis: int, size: float, other: float) -> Optional[float]:
94
- """Median step to the next cell along `axis`, so gutters of any width count."""
95
- steps = [min((q[axis] - p[axis] for q in centres
96
- if q[axis] - p[axis] > 0.5 * size and abs(q[1 - axis] - p[1 - axis]) < 0.5 * other),
97
- default=None) for p in centres]
98
- steps = [d for d in steps if d is not None]
99
- return float(np.median(steps)) if steps else None
100
- px, py = pitch(0, w, h), pitch(1, h, w)
101
- if px is None or py is None:
102
- return None
103
- cols, rows = int(round((gx1 - gx0 - w) / px)) + 1, int(round((gy1 - gy0 - h) / py)) + 1
104
- if cols < 2 or rows < 2:
105
- return None
106
- # Slot k along an axis is centred at the grid edge + half a cell + k pitches.
107
- sx, sy = gx0 + ((gx1 - gx0) - (cols - 1) * px - w) / 2, gy0 + ((gy1 - gy0) - (rows - 1) * py - h) / 2
108
- slot = {}
109
- for c in cells:
110
- cw, ch = c[2] - c[0], c[3] - c[1]
111
- if abs(cw - w) > TILE_SIZE_TOL * w or abs(ch - h) > TILE_SIZE_TOL * h:
112
- continue # two tiles read as one, or a piece of one
113
- k = (int(round(((c[1] + c[3]) / 2 - sy - h / 2) / py)), int(round(((c[0] + c[2]) / 2 - sx - w / 2) / px)))
114
- if not (0 <= k[0] < rows and 0 <= k[1] < cols):
115
- continue
116
- slot.setdefault(k, c)
117
- if len(slot) < LATTICE_MIN_FILLED * rows * cols \
118
- or {r for r, _ in slot} != set(range(rows)) or {c for _, c in slot} != set(range(cols)):
119
- return None
120
- xs = [(float(np.median([c[0] for (_, j), c in slot.items() if j == col])),
121
- float(np.median([c[2] for (_, j), c in slot.items() if j == col]))) for col in range(cols)]
122
- ys = [(float(np.median([c[1] for (i, _), c in slot.items() if i == row])),
123
- float(np.median([c[3] for (i, _), c in slot.items() if i == row]))) for row in range(rows)]
124
- return [[xs[j][0], ys[i][0], xs[j][1], ys[i][1]] for i in range(rows) for j in range(cols)]
125
-
126
-
127
- def find_grid(image_path: str) -> Optional[List[Box]]:
128
- """The cells of the board's grid in reading order, as (x0, y0, x1, y1) pixels;
129
- None when the board has no grid, or its cells do not form whole rows of one length."""
130
- from ..pointer.detector import detect_file
131
-
132
- dets = detect_file(image_path)
133
- grids = [d for d in dets if d["class"] == "grid" and d["score"] >= GRID_MIN_SCORE]
134
- if not grids:
135
- return None
136
- grid = max(grids, key=lambda d: d["score"])["box"]
137
- cells = _cells_in(grid, [d["box"] for d in dets if d["class"] == "cell" and d["score"] >= CELL_MIN_SCORE])
138
- cells = _with_tiles(cells, _cells_in(grid, [d["box"] for d in dets
139
- if d["class"] in TILE_CLASSES and d["score"] >= CELL_MIN_SCORE]))
140
- if len(cells) < 4:
141
- return None
142
- rows = _rows(cells)
143
- if len(rows) < 2 or len({len(r) for r in rows}) != 1 or len(rows[0]) < 2:
144
- lattice = _lattice(grid, cells)
145
- return None if lattice is None else [tuple(int(round(v)) for v in c) for c in lattice]
146
- return [tuple(int(round(v)) for v in c) for r in rows for c in r]
147
-
148
-
149
23
  # ── colour ──────────────────────────────────────────────────────────────
150
24
 
151
25
  def _read_rgb(image_path: str) -> Optional[np.ndarray]:
@@ -1091,7 +1091,16 @@ def slide_step(first: Image, probe: Image, current: Image, *, probe_s: Offset, s
1091
1091
  if _same(current, probe):
1092
1092
  params, corr = measure(first, probe, seg, guess=seg.probe, reach_px=2.0, reach_deg=1.0)
1093
1093
  else:
1094
- params, corr = measure(first, current, seg, guess=predict(samples, seg, cur))
1094
+ guess = predict(samples, seg, cur)
1095
+ try:
1096
+ params, corr = measure(first, current, seg, guess=guess)
1097
+ except TrackingError:
1098
+ # A part that trails its handle reads a short gain off the probe: Yidun's lags by half the travel up to
1099
+ # ~11px, so an 8px probe moved it 4 and the plan sent the handle twice as far as it needed. The part then
1100
+ # lands far outside the reach around the guess. On a rail the whole track is cheap to search.
1101
+ if _rail(seg) is None:
1102
+ raise
1103
+ params, corr = measure(first, current, seg, guess=guess, reach_px=float(a.shape[1]))
1095
1104
  samples.append(Sample(cur, params))
1096
1105
  pos = transform_point(params, seg.centroid, point)
1097
1106
  dist = math.hypot(goal[0] - pos[0], goal[1] - pos[1])
@@ -35,29 +35,52 @@ def _pip_upgrade_cmd() -> "list[str]":
35
35
  return [sys.executable, "-m", "pip", "install", "--upgrade", *ENGINE_PACKAGES]
36
36
 
37
37
 
38
+ PLANS_URL = "https://captchakraken.com/plans"
39
+
40
+
38
41
  class LicensedModelError(RuntimeError):
39
42
  pass
40
43
 
41
44
 
42
- def _refuse_licensed(repo_id: str) -> None:
43
- """A licensed model has no Hub repo; the Hub's RepositoryNotFoundError reads as "you are not logged in".
45
+ def _licence_message(repo_id: str) -> str:
46
+ return (
47
+ f"{repo_id} needs an Abyss Licence: its weights are in a gated Hugging Face repo, "
48
+ "and the Hub refused this download.\n"
49
+ f" Buy a licence at {PLANS_URL}, add your Hugging Face username on that page,\n"
50
+ " then sign in as that account (`hf auth login`, or HF_TOKEN) and run fetch again.\n"
51
+ " Or use the hosted API (https://api.captchakraken.com), which needs no weights at all."
52
+ )
44
53
 
45
- A `private` model is deliberately NOT refused: its 401 is the true answer, and pre-empting it would stop
46
- the holder of an authorised token from fetching weights they are entitled to.
47
- """
48
- from . import prompts
49
54
 
50
- if not prompts.is_licensed(repo_id):
51
- return
52
- raise LicensedModelError(
53
- f"{repo_id} is a LICENSED model: its weights are not published and "
54
- "there is nothing at that Hub id to download.\n"
55
- " Reach it through the hosted API (https://api.captchakraken.com), "
56
- "which needs no weights at all,\n"
57
- " or ask us about a self-hosting licence: https://captchakraken.com/contact\n"
58
- " To fetch a downloadable model instead, unset CAPTCHA_LORA_ADAPTER "
59
- "or point it at a published one."
60
- )
55
+ def _hub_refused(error: "BaseException | None") -> bool:
56
+ """snapshot_download wraps some refusals (a 403 on the repo lookup) in LocalEntryNotFoundError, so walk the causes."""
57
+ from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
58
+
59
+ while error is not None:
60
+ # GatedRepoError is a RepositoryNotFoundError, which is also how the Hub answers a token it will not show the repo to.
61
+ if isinstance(error, RepositoryNotFoundError):
62
+ return True
63
+ if isinstance(error, HfHubHTTPError) and error.response is not None \
64
+ and error.response.status_code in (401, 403):
65
+ return True
66
+ error = error.__cause__
67
+ return False
68
+
69
+
70
+ def _download_licensed(repo_id: str) -> None:
71
+ """In-process, not through `hf download`, so a refusal arrives as an exception that names the licence."""
72
+ try:
73
+ from huggingface_hub import snapshot_download
74
+ except ImportError as e:
75
+ raise RuntimeError(f'Fetching {repo_id} needs huggingface_hub: pip install "captchakraken[serve]"') from e
76
+
77
+ _log(f"$ snapshot_download({repo_id!r})")
78
+ try:
79
+ snapshot_download(repo_id)
80
+ except Exception as e:
81
+ if _hub_refused(e):
82
+ raise LicensedModelError(_licence_message(repo_id)) from e
83
+ raise
61
84
 
62
85
 
63
86
  def _needs_auth(*repo_ids: "str | None") -> "list[str]":
@@ -67,6 +90,13 @@ def _needs_auth(*repo_ids: "str | None") -> "list[str]":
67
90
  return [r for r in repo_ids if r and prompts.requires_auth(r)]
68
91
 
69
92
 
93
+ def _hub_id(model: str) -> str:
94
+ """A served name such as `abyss` is not a Hub id; download the repo it names."""
95
+ from . import prompts
96
+
97
+ return prompts.canonical_model_id(model) or model
98
+
99
+
70
100
  def plan(
71
101
  *,
72
102
  weights: bool = True,
@@ -75,14 +105,10 @@ def plan(
75
105
  base: "str | None" = None,
76
106
  lora: "str | None" = None,
77
107
  ) -> dict:
78
- base_model = base or config.base_model()
79
- lora_adapter = lora or config.lora_adapter()
108
+ base_model = _hub_id(base or config.base_model())
109
+ lora_adapter = _hub_id(lora or config.lora_adapter())
80
110
  base_url = config.base_url()
81
111
 
82
- if weights:
83
- _refuse_licensed(lora_adapter)
84
- _refuse_licensed(base_model)
85
-
86
112
  repos = [lora_adapter, base_model] if weights else []
87
113
  return {
88
114
  "weights": weights,
@@ -127,12 +153,16 @@ def fetch(
127
153
  return {**p, "dry_run": True}
128
154
 
129
155
  if weights:
156
+ from . import prompts
157
+
130
158
  _log(f"Pulling latest weights from {p['hf_org']} (+ base) …")
131
159
  for repo in p["needs_auth"]:
132
- _log(f"{repo} is a PRIVATE repo — this needs a HuggingFace token "
133
- "authorised on it (`hf auth login`, or HF_TOKEN).")
134
- for cmd in p["downloads"]:
135
- _run(cmd)
160
+ _log(f"{repo} needs a Hugging Face token authorised on it (`hf auth login`, or HF_TOKEN).")
161
+ for repo, cmd in zip((p["lora_adapter"], p["base_model"]), p["downloads"]):
162
+ if prompts.is_licensed(repo):
163
+ _download_licensed(repo)
164
+ else:
165
+ _run(cmd)
136
166
 
137
167
  if engine:
138
168
  _log("Upgrading the vLLM serving stack …")