captchakraken 3.2.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENTS.md +7 -11
  2. package/LICENSE +165 -145
  3. package/NOTICE +4 -4
  4. package/README.md +12 -13
  5. package/bin/captchakraken.js +25 -0
  6. package/dist/cli-invocation.d.ts +6 -3
  7. package/dist/cli-invocation.js +26 -10
  8. package/dist/humanize.d.ts +37 -1
  9. package/dist/humanize.js +143 -9
  10. package/dist/index.d.ts +13 -12
  11. package/dist/index.js +25 -33
  12. package/dist/kinds.d.ts +15 -2
  13. package/dist/kinds.js +12 -4
  14. package/dist/playwright-types.d.ts +3 -0
  15. package/dist/selectors.d.ts +93 -11
  16. package/dist/selectors.js +226 -116
  17. package/dist/solver.d.ts +94 -12
  18. package/dist/solver.js +569 -203
  19. package/dist/types.d.ts +53 -8
  20. package/dist/verdicts.d.ts +3 -0
  21. package/dist/verdicts.js +40 -0
  22. package/package.json +8 -4
  23. package/python/AGENTS.md +9 -13
  24. package/python/LICENSE +165 -145
  25. package/python/NOTICE +4 -4
  26. package/python/README.md +13 -12
  27. package/python/pyproject.toml +27 -13
  28. package/python/src/captchakraken/__init__.py +43 -46
  29. package/python/src/captchakraken/action_types.py +32 -1
  30. package/python/src/captchakraken/captchakraken.config.json +416 -0
  31. package/python/src/captchakraken/cli.py +141 -31
  32. package/python/src/captchakraken/clipvideo.py +258 -0
  33. package/python/src/captchakraken/config.py +72 -7
  34. package/python/src/captchakraken/demo.py +149 -0
  35. package/python/src/captchakraken/humanize.py +141 -10
  36. package/python/src/captchakraken/image_processor.py +3 -7
  37. package/python/src/captchakraken/keyframes.py +96 -14
  38. package/python/src/captchakraken/kinds.py +14 -2
  39. package/python/src/captchakraken/models.json +37 -3
  40. package/python/src/captchakraken/page_solver.py +600 -252
  41. package/python/src/captchakraken/planner.py +311 -49
  42. package/python/src/captchakraken/pointer/__init__.py +20 -0
  43. package/python/src/captchakraken/pointer/detector.py +333 -0
  44. package/python/src/captchakraken/pointer/elements.py +273 -0
  45. package/python/src/captchakraken/pointer/heads.py +163 -0
  46. package/python/src/captchakraken/pointer/layout.py +319 -0
  47. package/python/src/captchakraken/pointer/marks.py +184 -0
  48. package/python/src/captchakraken/pointer/server.py +150 -0
  49. package/python/src/captchakraken/pointer/service.py +553 -0
  50. package/python/src/captchakraken/pointer/vllm_plugin.py +114 -0
  51. package/python/src/captchakraken/prompts.py +111 -34
  52. package/python/src/captchakraken/selectors.py +221 -135
  53. package/python/src/captchakraken/selfhost.py +423 -0
  54. package/python/src/captchakraken/server_manager.py +139 -11
  55. package/python/src/captchakraken/solver.py +169 -88
  56. package/python/src/captchakraken/tool_calls/board_painted.py +11 -6
  57. package/python/src/captchakraken/tool_calls/fill_tracker.py +152 -0
  58. package/python/src/captchakraken/tool_calls/find_checkbox.py +14 -59
  59. package/python/src/captchakraken/tool_calls/find_grid.py +273 -1191
  60. package/python/src/captchakraken/tool_calls/slide_tracker.py +1102 -0
  61. package/python/src/captchakraken/verdicts.py +52 -0
  62. package/dist/slide-geometry.d.ts +0 -6
  63. package/dist/slide-geometry.js +0 -38
  64. package/python/src/captchakraken/tool_calls/track_piece.py +0 -120
@@ -0,0 +1,423 @@
1
+ """`captchakraken fetch`: ask which model, GPU and startup mode, then install, download and start it.
2
+
3
+ Everything lands under the state directory and the choices live in `selfhost.json`, so a solve, the
4
+ server and `captchakraken start` read one file and nobody exports anything or edits their PATH.
5
+ The serving stack gets its own environment because the one running this command may be a throwaway:
6
+ npx and pipx both evict theirs, and a server must not break when they do.
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import secrets
12
+ import shutil
13
+ import socket
14
+ import subprocess
15
+ import sys
16
+ import venv
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Callable, List, NamedTuple, Optional, Sequence
20
+
21
+ from . import __version__, config, server_manager
22
+
23
+ DETECTOR_REPO = "CaptchaKraken/CaptchaKrakenV2-CNN-large"
24
+ DETECTOR_FILE = "detector_r18.pt"
25
+
26
+ ALWAYS_ON = "always"
27
+ FIRST_SOLVE = "first-solve"
28
+
29
+ # The serving stack on disk, measured: torch and vLLM with their CUDA libraries.
30
+ RUNTIME_GB = 8.0
31
+ # vLLM's default reservation and graph set run an 8 GB card out of memory while it starts.
32
+ SMALL_CARD_MIB = 12_000
33
+ SMALL_CARD_CAPTURE_SIZE = 16
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Model:
38
+ repo: str
39
+ title: str
40
+ blurb: str
41
+ download_gb: float
42
+ # The smallest card it was seen to load on, as a card's advertised size.
43
+ min_vram_gb: int
44
+ # Its share of a small card. Twilight's full-precision weights leave no KV cache at the default (measured, 8 GB).
45
+ small_card_utilization: float = 0.72
46
+
47
+
48
+ # Sunlight is absent on purpose: its published heads predate this client's layout and refuse to load.
49
+ MODELS = (
50
+ Model("CaptchaKraken/MidnightV2-4B-q4", "Midnight V2 4B Q4", "the default: best balance of speed and accuracy",
51
+ 3.8, 8),
52
+ Model("CaptchaKraken/TwilightV2-2B", "Twilight V2 2B", "smaller model, full precision", 4.5, 8, 0.80),
53
+ Model("CaptchaKraken/MidnightV2-4B", "Midnight V2 4B", "the same model at full precision", 9.1, 16),
54
+ )
55
+
56
+
57
+ class Gpu(NamedTuple):
58
+ index: int
59
+ name: str
60
+ total_mib: int
61
+ free_mib: int
62
+
63
+ @property
64
+ def label(self) -> str:
65
+ return f"{self.name} ({self.total_mib / 1024:.0f} GB, {self.free_mib / 1024:.1f} GB free)"
66
+
67
+
68
+ class Choice(NamedTuple):
69
+ model: Model
70
+ gpu: Gpu
71
+ startup: str
72
+
73
+
74
+ class Cancelled(Exception):
75
+ pass
76
+
77
+
78
+ def _fits(model: Model, gpu: Gpu) -> bool:
79
+ # Cards are sold in GB and report a little under it: an "8 GB" 5060 reports 8151 MiB, a 7.96.
80
+ return gpu.total_mib >= model.min_vram_gb * 1024 * 0.95
81
+
82
+
83
+ def _busy_note(model: Model, gpu: Gpu) -> str:
84
+ # The server holds about 70% of a card sold at the model's minimum.
85
+ return "" if gpu.free_mib >= model.min_vram_gb * 1024 * 0.7 else "too full right now unless you free it up"
86
+
87
+
88
+ def detect_gpus(run: Callable = subprocess.run) -> List[Gpu]:
89
+ """Numbered as nvidia-smi numbers them, which is PCI order, so the server is pinned with that same order."""
90
+ try:
91
+ out = run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free", "--format=csv,noheader,nounits"],
92
+ capture_output=True, text=True, timeout=30)
93
+ except (OSError, subprocess.SubprocessError):
94
+ return []
95
+ if out.returncode != 0:
96
+ return []
97
+ gpus = []
98
+ for line in out.stdout.splitlines():
99
+ fields = [f.strip() for f in line.split(",")]
100
+ if len(fields) == 4 and fields[0].isdigit() and fields[2].isdigit() and fields[3].isdigit():
101
+ gpus.append(Gpu(int(fields[0]), fields[1], int(fields[2]), int(fields[3])))
102
+ return gpus
103
+
104
+
105
+ # ── the terminal menu ────────────────────────────────────────────────────────
106
+
107
+ class Option(NamedTuple):
108
+ label: str
109
+ detail: str = ""
110
+ disabled: str = ""
111
+
112
+
113
+ def _read_key() -> str:
114
+ ch = os.read(sys.stdin.fileno(), 1).decode(errors="ignore")
115
+ if ch != "\x1b":
116
+ return ch
117
+ import select
118
+ if not select.select([sys.stdin], [], [], 0.05)[0]:
119
+ return "esc"
120
+ tail = os.read(sys.stdin.fileno(), 2).decode(errors="ignore")
121
+ return {"[A": "up", "[B": "down"}.get(tail, "")
122
+
123
+
124
+ def _render(title: str, options: Sequence[Option], at: int) -> List[str]:
125
+ lines = [f"\033[1m{title}\033[0m"]
126
+ for i, o in enumerate(options):
127
+ if o.disabled:
128
+ lines.append(f" \033[2m{i + 1}. {o.label} ({o.disabled})\033[0m")
129
+ continue
130
+ here = i == at
131
+ mark = "\033[1;36m❯\033[0m" if here else " "
132
+ name = f"\033[1;36m{o.label}\033[0m" if here else o.label
133
+ lines.append(f" {mark} {i + 1}. {name}" + (f" \033[2m{o.detail}\033[0m" if o.detail else ""))
134
+ lines.append(" \033[2m↑/↓ or a number, Enter to choose, q to quit\033[0m")
135
+ return lines
136
+
137
+
138
+ def choose(title: str, options: Sequence[Option], default: int = 0) -> int:
139
+ """The index picked with the arrow keys. A disabled option can be seen and not landed on."""
140
+ import termios
141
+ import tty
142
+
143
+ usable = [i for i, o in enumerate(options) if not o.disabled]
144
+ at = default if default in usable else usable[0]
145
+ fd = sys.stdin.fileno()
146
+ saved = termios.tcgetattr(fd)
147
+ drawn = 0
148
+ try:
149
+ tty.setcbreak(fd)
150
+ sys.stdout.write("\033[?25l")
151
+ while True:
152
+ lines = _render(title, options, at)
153
+ sys.stdout.write((f"\033[{drawn}F" if drawn else "") + "".join(f"\033[2K{li}\n" for li in lines))
154
+ sys.stdout.flush()
155
+ drawn = len(lines)
156
+ key = _read_key()
157
+ if key in ("q", "esc", "\x03"):
158
+ raise Cancelled()
159
+ if key in ("\n", "\r"):
160
+ return at
161
+ if key in ("up", "k"):
162
+ at = usable[(usable.index(at) - 1) % len(usable)]
163
+ elif key in ("down", "j"):
164
+ at = usable[(usable.index(at) + 1) % len(usable)]
165
+ elif key.isdigit() and int(key) - 1 in usable:
166
+ at = int(key) - 1
167
+ finally:
168
+ termios.tcsetattr(fd, termios.TCSADRAIN, saved)
169
+ sys.stdout.write("\033[?25h\n")
170
+ sys.stdout.flush()
171
+
172
+
173
+ def ask(gpus: Sequence[Gpu], saved: dict) -> Choice:
174
+ """Model, then GPU, then startup. A previous choice is where the cursor starts."""
175
+ biggest = max(gpus, key=lambda g: g.total_mib)
176
+ default_model = next((i for i, m in enumerate(MODELS) if m.repo == saved.get("model")), 0)
177
+ picked = MODELS[choose("Which model do you want to run?", [
178
+ Option(m.title, f"{m.blurb}, {m.download_gb:.1f} GB download, needs {m.min_vram_gb} GB of VRAM",
179
+ "" if _fits(m, biggest) else f"needs {m.min_vram_gb} GB of VRAM, your largest has "
180
+ f"{biggest.total_mib / 1024:.0f} GB")
181
+ for m in MODELS], default_model)]
182
+
183
+ fitting = [g for g in gpus if _fits(picked, g)]
184
+ default_gpu = next((i for i, g in enumerate(gpus) if g.index == saved.get("gpu")), None)
185
+ if default_gpu is None or gpus[default_gpu] not in fitting:
186
+ default_gpu = gpus.index(max(fitting, key=lambda g: g.free_mib))
187
+ gpu = gpus[choose("Which GPU should the server run on?", [
188
+ Option(f"GPU {g.index}: {g.label}", _busy_note(picked, g), "" if g in fitting else f"too small for {picked.title}")
189
+ for g in gpus], default_gpu)]
190
+
191
+ modes = [ALWAYS_ON, FIRST_SOLVE]
192
+ startup = modes[choose("When should the server run?", [
193
+ Option("Always on", "starts with this machine and restarts if it crashes"),
194
+ Option("Warm start", "starts now and after a reboot on the first solve, then stays loaded"),
195
+ ], modes.index(saved["startup"]) if saved.get("startup") in modes else 0)]
196
+ return Choice(picked, gpu, startup)
197
+
198
+
199
+ # ── installing ───────────────────────────────────────────────────────────────
200
+
201
+ def _step(message: str) -> None:
202
+ print(f"\033[1;36m➜\033[0m {message}", flush=True)
203
+
204
+
205
+ def _ok(message: str) -> None:
206
+ print(f"\033[1;32m✓\033[0m {message}", flush=True)
207
+
208
+
209
+ def _source_tree() -> Optional[Path]:
210
+ """The installable source beside this package, which npm ships and a checkout has."""
211
+ # A checkout runs from src/, and npm keeps its environment at python/.venv beside the source it ships.
212
+ for root in (Path(__file__).resolve().parents[2], Path(sys.prefix).resolve().parent):
213
+ if (root / "pyproject.toml").is_file():
214
+ return root
215
+ return None
216
+
217
+
218
+ def make_venv(where: Path) -> Path:
219
+ python = where / "bin" / "python"
220
+ if not python.exists():
221
+ try:
222
+ venv.create(where, with_pip=True)
223
+ except (OSError, subprocess.CalledProcessError) as e:
224
+ shutil.rmtree(where, ignore_errors=True)
225
+ raise RuntimeError(f"Could not create a Python environment at {where}: {e}. "
226
+ "On Debian or Ubuntu, install it with: sudo apt install python3-venv") from e
227
+ return python
228
+
229
+
230
+ def install_client(python: Path, extra: str = "") -> None:
231
+ """This same version from PyPI, or from the source beside this file when that version is not on PyPI."""
232
+ subprocess.run([str(python), "-m", "pip", "install", "--quiet", "--upgrade", "pip"], check=True)
233
+ wanted = f"captchakraken{extra}=={__version__}"
234
+ if subprocess.run([str(python), "-m", "pip", "install", "--quiet", wanted]).returncode == 0:
235
+ return
236
+ source = _source_tree()
237
+ if source is None:
238
+ raise RuntimeError(f"Could not install {wanted}. The pip output above says why.")
239
+ subprocess.run([str(python), "-m", "pip", "install", "--quiet", f"{source}{extra}"], check=True)
240
+
241
+
242
+ _DOWNLOAD = """
243
+ import sys
244
+ from huggingface_hub import hf_hub_download, snapshot_download
245
+ print(snapshot_download(sys.argv[1]))
246
+ print(hf_hub_download(sys.argv[2], sys.argv[3]))
247
+ """
248
+
249
+
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
256
+
257
+
258
+ def free_port(start: int = 8000) -> int:
259
+ for port in range(start, start + 100):
260
+ with socket.socket() as s:
261
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
262
+ try:
263
+ s.bind(("127.0.0.1", port))
264
+ return port
265
+ except OSError:
266
+ continue
267
+ raise RuntimeError(f"No free port between {start} and {start + 99}.")
268
+
269
+
270
+ def settings(choice: Choice, model_path: str, detector: str, saved: dict) -> dict:
271
+ small = choice.gpu.total_mib < SMALL_CARD_MIB
272
+ return {
273
+ "model": choice.model.repo,
274
+ "title": choice.model.title,
275
+ "model_path": model_path,
276
+ "detector": detector,
277
+ "gpu": choice.gpu.index,
278
+ "gpu_name": choice.gpu.name,
279
+ "startup": choice.startup,
280
+ "port": saved.get("port") or free_port(),
281
+ # The client and the server both read it from this file, which only its owner can open.
282
+ "key": saved.get("key") or secrets.token_hex(32),
283
+ "gpu_memory_utilization": choice.model.small_card_utilization if small else 0.80,
284
+ "max_cudagraph_capture_size": SMALL_CARD_CAPTURE_SIZE if small else None,
285
+ }
286
+
287
+
288
+ def write_settings(values: dict) -> None:
289
+ path = config.selfhost_path()
290
+ path.parent.mkdir(parents=True, exist_ok=True)
291
+ temporary = path.with_suffix(".tmp")
292
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
293
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
294
+ json.dump(values, f, indent=2)
295
+ os.replace(temporary, path)
296
+
297
+
298
+ def link_command() -> Optional[Path]:
299
+ """`captchakraken` on the PATH where the system already looks, so no shell file gets edited."""
300
+ bin_dir = Path.home() / ".local" / "bin"
301
+ link = bin_dir / "captchakraken"
302
+ target = config.runtime_dir() / "bin" / "captchakraken"
303
+ try:
304
+ bin_dir.mkdir(parents=True, exist_ok=True)
305
+ if link.is_symlink() or not link.exists():
306
+ link.unlink(missing_ok=True)
307
+ link.symlink_to(target)
308
+ except OSError:
309
+ return None
310
+ return link if link.resolve() == target.resolve() else None
311
+
312
+
313
+ def _on_path(command: Path) -> bool:
314
+ found = shutil.which(command.name)
315
+ return bool(found) and Path(found).resolve() == command.resolve()
316
+
317
+
318
+ def _disk_check(model: Model) -> None:
319
+ where = config.state_dir()
320
+ where.mkdir(parents=True, exist_ok=True)
321
+ free_gb = shutil.disk_usage(where).free / 1e9
322
+ needed = model.download_gb + RUNTIME_GB
323
+ if free_gb < needed:
324
+ raise RuntimeError(f"This needs about {needed:.0f} GB of disk and {where} has {free_gb:.0f} GB free.")
325
+
326
+
327
+ def install(choice: Choice, saved: dict) -> dict:
328
+ _disk_check(choice.model)
329
+ server_manager.stop()
330
+
331
+ _step("Installing the serving stack (torch and vLLM)")
332
+ python = make_venv(config.runtime_dir())
333
+ install_client(python, "[serve]")
334
+
335
+ _step(f"Downloading {choice.model.title} and the element detector")
336
+ model_path, detector = download(python, choice.model.repo)
337
+
338
+ values = settings(choice, model_path, detector, saved)
339
+ write_settings(values)
340
+ config.selfhost.cache_clear()
341
+
342
+ _step("Preparing the browser for the demo")
343
+ try:
344
+ from . import demo
345
+ demo.prepare()
346
+ except (RuntimeError, subprocess.SubprocessError, OSError) as e:
347
+ print(f" The demo browser did not install ({e}); `captchakraken demo` will try again.", flush=True)
348
+
349
+ _step(f"Starting the server on GPU {choice.gpu.index} ({choice.gpu.name})")
350
+ started = server_manager.start(background=True)
351
+ if started["status"] not in ("running", "already-running"):
352
+ raise RuntimeError(f"The server did not come up. Last lines of {server_manager.LOG_FILE}:\n"
353
+ + server_manager.log_tail())
354
+ return values
355
+
356
+
357
+ def _summary(values: dict) -> None:
358
+ command = link_command()
359
+ bare = bool(command) and _on_path(command)
360
+ name = "captchakraken" if bare else str(command or config.runtime_dir() / "bin" / "captchakraken")
361
+ _ok(f"{values['title']} is running on GPU {values['gpu']} at http://127.0.0.1:{values['port']}")
362
+ print(f"\nTry it:\n {name} demo\n")
363
+ print(f"Start and stop the server:\n {name} start\n {name} stop\n")
364
+ if command and not bare:
365
+ print(f"Open a new terminal for the short name `captchakraken`, once {command.parent} is on your PATH.\n")
366
+ if os.getenv("VLLM_BASE_URL"):
367
+ print(f"VLLM_BASE_URL is set in this shell, and it wins over this install: {os.environ['VLLM_BASE_URL']}\n")
368
+
369
+
370
+ def _from_flags(gpus: Sequence[Gpu], saved: dict, model: Optional[str], gpu: Optional[int],
371
+ startup: Optional[str]) -> Choice:
372
+ wanted = model or saved.get("model") or MODELS[0].repo
373
+ found = next((m for m in MODELS if wanted in (m.repo, m.repo.split("/")[-1])), None)
374
+ if found is None:
375
+ raise RuntimeError(f"Unknown model {wanted!r}. Choose from: "
376
+ + ", ".join(m.repo.split("/")[-1] for m in MODELS))
377
+ index = gpu if gpu is not None else saved.get("gpu")
378
+ if index is None:
379
+ fitting = [g for g in gpus if _fits(found, g)]
380
+ if not fitting:
381
+ raise RuntimeError(f"{found.title} needs {found.min_vram_gb} GB of VRAM.")
382
+ chosen = max(fitting, key=lambda g: g.free_mib)
383
+ else:
384
+ chosen = next((g for g in gpus if g.index == index), None)
385
+ if chosen is None:
386
+ raise RuntimeError(f"There is no GPU {index}. Found: {[g.index for g in gpus]}")
387
+ return Choice(found, chosen, startup or saved.get("startup") or ALWAYS_ON)
388
+
389
+
390
+ NO_GPU = ("No NVIDIA GPU was found, and self-hosting needs one on Linux.\n"
391
+ "The hosted API needs no GPU: https://github.com/CaptchaKraken/CaptchaKraken/blob/main/docs/hosted-api.md")
392
+
393
+
394
+ def fetch(*, yes: bool = False, model: Optional[str] = None, gpu: Optional[int] = None,
395
+ startup: Optional[str] = None) -> int:
396
+ if sys.platform != "linux":
397
+ print(NO_GPU, file=sys.stderr)
398
+ return 1
399
+ gpus = detect_gpus()
400
+ if not gpus:
401
+ print(NO_GPU, file=sys.stderr)
402
+ return 1
403
+ saved = config.selfhost()
404
+ interactive = sys.stdin.isatty() and sys.stdout.isatty()
405
+ if not yes and not interactive:
406
+ print("`captchakraken fetch` asks its questions in a terminal. Without one, pass --yes, "
407
+ "plus --model, --gpu and --startup to choose other than the defaults.", file=sys.stderr)
408
+ return 2
409
+ try:
410
+ if yes:
411
+ choice = _from_flags(gpus, saved, model, gpu, startup)
412
+ else:
413
+ print("\n\033[1mCaptchaKraken self-hosted setup\033[0m\n")
414
+ choice = ask(gpus, saved)
415
+ values = install(choice, saved)
416
+ except Cancelled:
417
+ print("Cancelled. Nothing was changed.")
418
+ return 130
419
+ except (RuntimeError, subprocess.CalledProcessError) as e:
420
+ print(f"\033[1;31m✗\033[0m {e}", file=sys.stderr)
421
+ return 1
422
+ _summary(values)
423
+ return 0
@@ -1,3 +1,4 @@
1
+ import json
1
2
  import os
2
3
  import shutil
3
4
  import signal
@@ -10,11 +11,15 @@ from urllib.parse import urlparse
10
11
  import requests
11
12
 
12
13
  from . import config
14
+ from .clipvideo import media_io_kwargs
13
15
 
14
16
  STATE_DIR = config.state_dir()
15
17
  LOCK_FILE = STATE_DIR / "vllm.lock"
16
18
  PID_FILE = STATE_DIR / "vllm.pid"
17
19
  LOG_FILE = STATE_DIR / "vllm.log"
20
+ # `captchakraken stop` means off: a solve must not quietly start the server again.
21
+ STOPPED_FILE = STATE_DIR / "server.stopped"
22
+ UNIT = "captchakraken-local.service"
18
23
 
19
24
  STARTUP_TIMEOUT_S = int(os.getenv("CAPTCHA_KRAKEN_STARTUP_TIMEOUT", "600"))
20
25
 
@@ -36,7 +41,9 @@ def is_local(base_url: str) -> bool:
36
41
 
37
42
  def is_healthy(base_url: str, timeout: float = 2.0) -> bool:
38
43
  try:
39
- r = requests.get(_server_root(base_url) + "/health", timeout=timeout)
44
+ # Empty, not absent: a machine's HTTP_PROXY must not carry a call to this machine's own server.
45
+ direct = {"http": "", "https": ""} if is_local(base_url) else None
46
+ r = requests.get(_server_root(base_url) + "/health", timeout=timeout, proxies=direct)
40
47
  return r.ok
41
48
  except requests.RequestException:
42
49
  return False
@@ -51,7 +58,12 @@ def _vllm_bin() -> "str | None":
51
58
 
52
59
 
53
60
  def _vllm_available() -> bool:
54
- return _vllm_bin() is not None
61
+ return Path(_serve_python()).exists() if config.selfhost_active() else _vllm_bin() is not None
62
+
63
+
64
+ def _serve_python() -> str:
65
+ """The stack `fetch` installed, whichever environment this command itself is running from."""
66
+ return str(config.runtime_dir() / "bin" / "python") if config.selfhost_active() else sys.executable
55
67
 
56
68
 
57
69
  def _read_pid() -> "int | None":
@@ -59,6 +71,12 @@ def _read_pid() -> "int | None":
59
71
  pid = int(PID_FILE.read_text().strip())
60
72
  except (OSError, ValueError):
61
73
  return None
74
+ try:
75
+ # A server we spawned that crashed stays a zombie until we reap it, and kill(0) calls a zombie alive.
76
+ if os.waitpid(pid, os.WNOHANG)[0] == pid:
77
+ return None
78
+ except OSError:
79
+ pass # not our child: someone else's start, or a pid from an earlier run
62
80
  try:
63
81
  os.kill(pid, 0)
64
82
  return pid
@@ -67,6 +85,22 @@ def _read_pid() -> "int | None":
67
85
 
68
86
 
69
87
  def build_serve_command() -> "list[str]":
88
+ from . import prompts
89
+
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
+ capture = config.max_cudagraph_capture_size()
95
+ return [
96
+ _serve_python(), "-m", "captchakraken.pointer.server",
97
+ "--model", config.serve_model(),
98
+ "--detector", detector,
99
+ "--host", os.getenv("CAPTCHA_POINTER_HOST", "127.0.0.1"),
100
+ "--port", str(config.port()),
101
+ "--gpu-memory-utilization", str(config.gpu_memory_utilization()),
102
+ *(["--max-cudagraph-capture-size", str(capture)] if capture else []),
103
+ ]
70
104
  return [
71
105
  _vllm_bin() or "vllm", "serve", config.base_model(),
72
106
  "--reasoning-parser", "qwen3",
@@ -78,6 +112,10 @@ def build_serve_command() -> "list[str]":
78
112
  "--trust-remote-code",
79
113
  "--port", str(config.port()),
80
114
  "--lora-modules", f"{config.lora_name()}={config.lora_adapter()}",
115
+ # A video-generation model watches an animation as one JPEG frame sequence; without these vLLM refuses the
116
+ # video or resamples it to its own frame count, and the time the model answers with names the wrong moment.
117
+ "--limit-mm-per-prompt", json.dumps({"image": 8, "video": 1}),
118
+ "--media-io-kwargs", json.dumps(media_io_kwargs()),
81
119
  *config.extra_serve_args(),
82
120
  ]
83
121
 
@@ -88,6 +126,13 @@ def _serve_env() -> dict:
88
126
  # Only forward a real key; api_key() falls back to "EMPTY", which would lock vLLM to a placeholder.
89
127
  if key and key != "EMPTY":
90
128
  env["VLLM_API_KEY"] = key
129
+ active = config.selfhost_active()
130
+ if active:
131
+ env["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
132
+ # nvidia-smi numbers GPUs in PCI order and CUDA does not unless told to.
133
+ if "CUDA_VISIBLE_DEVICES" not in os.environ:
134
+ env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
135
+ env["CUDA_VISIBLE_DEVICES"] = str(active.get("gpu", 0))
91
136
  return env
92
137
 
93
138
 
@@ -95,9 +140,8 @@ def _spawn() -> subprocess.Popen:
95
140
  STATE_DIR.mkdir(parents=True, exist_ok=True)
96
141
  if not _vllm_available():
97
142
  raise RuntimeError(
98
- "vLLM is not installed, so a local server can't be started. Run the "
99
- "setup script (./setup.sh) or `pip install \"captchakraken[serve]\"`, "
100
- "or point VLLM_BASE_URL at a server you already run."
143
+ "vLLM is not installed, so a local server can't be started. Run "
144
+ "`captchakraken fetch`, or point VLLM_BASE_URL at a server you already run."
101
145
  )
102
146
  cmd = build_serve_command()
103
147
  _log("starting: " + " ".join(cmd))
@@ -116,18 +160,88 @@ def _spawn() -> subprocess.Popen:
116
160
  return proc
117
161
 
118
162
 
119
- def _wait_healthy(base_url: str, timeout: float) -> bool:
163
+ def _wait_healthy(base_url: str, timeout: float, alive=None) -> bool:
120
164
  deadline = time.time() + timeout
165
+ alive = alive or (lambda: _read_pid() is not None)
121
166
  while time.time() < deadline:
122
167
  if is_healthy(base_url, timeout=2.0):
123
168
  return True
124
- pid = _read_pid()
125
- if pid is None:
169
+ if not alive():
126
170
  return False
127
171
  time.sleep(2.0)
128
172
  return False
129
173
 
130
174
 
175
+ def log_tail(lines: int = 15) -> str:
176
+ try:
177
+ return "\n".join(LOG_FILE.read_text(errors="replace").splitlines()[-lines:])
178
+ except OSError:
179
+ return "(no log)"
180
+
181
+
182
+ def _always_on() -> bool:
183
+ return config.selfhost_active().get("startup") == "always" and _systemd_available()
184
+
185
+
186
+ def _systemd_available() -> bool:
187
+ return shutil.which("systemctl") is not None and subprocess.run(
188
+ ["systemctl", "--user", "show-environment"], capture_output=True).returncode == 0
189
+
190
+
191
+ def _unit_path() -> Path:
192
+ return Path.home() / ".config" / "systemd" / "user" / UNIT
193
+
194
+
195
+ def _unit_text() -> str:
196
+ return (
197
+ "[Unit]\nDescription=CaptchaKraken pointer server\nAfter=network.target\n\n"
198
+ "[Service]\n"
199
+ f"Environment=CAPTCHA_KRAKEN_STATE_DIR={config.state_dir()}\n"
200
+ f"ExecStart={_serve_python()} -m captchakraken.cli server run\n"
201
+ f"StandardOutput=append:{LOG_FILE}\nStandardError=append:{LOG_FILE}\n"
202
+ "Restart=on-failure\nRestartSec=10\n\n"
203
+ "[Install]\nWantedBy=default.target\n"
204
+ )
205
+
206
+
207
+ def _unit_running() -> bool:
208
+ return subprocess.run(["systemctl", "--user", "is-active", "--quiet", UNIT]).returncode == 0
209
+
210
+
211
+ def _unit_alive() -> bool:
212
+ # Between a crash and its restart the unit reads "activating", which is still worth waiting on.
213
+ state = subprocess.run(["systemctl", "--user", "is-failed", UNIT], capture_output=True, text=True).stdout.strip()
214
+ return state != "failed" and state != "inactive"
215
+
216
+
217
+ def _start_unit(base_url: str) -> dict:
218
+ path = _unit_path()
219
+ path.parent.mkdir(parents=True, exist_ok=True)
220
+ path.write_text(_unit_text(), encoding="utf-8")
221
+ subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
222
+ subprocess.run(["systemctl", "--user", "enable", "--now", UNIT], check=True, capture_output=True)
223
+ # Without linger a user's services wait for them to log in. Refused on some systems; it still runs from login.
224
+ subprocess.run(["loginctl", "enable-linger"], capture_output=True)
225
+ restarts = _unit_restarts()
226
+ # A server that dies while loading is restarted by systemd for ever; one restart is the answer.
227
+ ok = _wait_healthy(base_url, STARTUP_TIMEOUT_S, alive=lambda: _unit_alive() and _unit_restarts() == restarts)
228
+ crashed = not ok and _unit_restarts() != restarts
229
+ if crashed:
230
+ subprocess.run(["systemctl", "--user", "disable", "--now", UNIT], capture_output=True)
231
+ return {"status": "running" if ok else "crashed" if crashed else "timeout", "base_url": base_url, "unit": UNIT,
232
+ "log": str(LOG_FILE)}
233
+
234
+
235
+ def _unit_restarts() -> int:
236
+ out = subprocess.run(["systemctl", "--user", "show", "-p", "NRestarts", "--value", UNIT],
237
+ capture_output=True, text=True).stdout.strip()
238
+ return int(out) if out.isdigit() else 0
239
+
240
+
241
+ def _unit_installed() -> bool:
242
+ return _unit_path().exists() and shutil.which("systemctl") is not None
243
+
244
+
131
245
  def ensure_server(base_url: "str | None" = None) -> None:
132
246
  base_url = base_url or config.base_url()
133
247
 
@@ -138,6 +252,8 @@ def ensure_server(base_url: "str | None" = None) -> None:
138
252
  return
139
253
  if not config.autostart_enabled():
140
254
  return
255
+ if config.selfhost_active() and STOPPED_FILE.exists():
256
+ raise RuntimeError("The CaptchaKraken server is stopped. Start it with: captchakraken start")
141
257
 
142
258
  STATE_DIR.mkdir(parents=True, exist_ok=True)
143
259
  # Two solves racing on first use must not both spawn a server; re-check under the lock.
@@ -156,10 +272,13 @@ def ensure_server(base_url: "str | None" = None) -> None:
156
272
 
157
273
  def start(background: bool = True) -> dict:
158
274
  base_url = config.base_url()
275
+ STOPPED_FILE.unlink(missing_ok=True)
159
276
  if is_healthy(base_url):
160
277
  return {"status": "already-running", "base_url": base_url, "pid": _read_pid()}
161
278
  if not background:
162
279
  run_foreground()
280
+ if _always_on():
281
+ return _start_unit(base_url)
163
282
  _spawn()
164
283
  ok = _wait_healthy(base_url, STARTUP_TIMEOUT_S)
165
284
  return {
@@ -173,17 +292,23 @@ def start(background: bool = True) -> dict:
173
292
  def run_foreground() -> None:
174
293
  if not _vllm_available():
175
294
  raise RuntimeError(
176
- "vLLM is not installed. Run ./setup.sh or "
177
- "`pip install \"captchakraken[serve]\"`."
295
+ "vLLM is not installed. Run `captchakraken fetch`."
178
296
  )
179
297
  cmd = build_serve_command()
180
298
  os.execvpe(cmd[0], cmd, _serve_env())
181
299
 
182
300
 
183
301
  def stop() -> dict:
302
+ was_on = False
303
+ if config.selfhost():
304
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
305
+ STOPPED_FILE.touch()
306
+ if _unit_installed():
307
+ was_on = _unit_running()
308
+ subprocess.run(["systemctl", "--user", "disable", "--now", UNIT], capture_output=True)
184
309
  pid = _read_pid()
185
310
  if pid is None:
186
- return {"status": "not-running"}
311
+ return {"status": "stopped" if was_on else "not-running"}
187
312
  try:
188
313
  os.killpg(os.getpgid(pid), signal.SIGTERM)
189
314
  except OSError:
@@ -210,6 +335,9 @@ def status(base_url: "str | None" = None) -> dict:
210
335
  "local": is_local(base_url),
211
336
  "pid": _read_pid(),
212
337
  "autostart": config.autostart_enabled(),
338
+ "gpu": config.selfhost_active().get("gpu"),
339
+ "startup": config.selfhost_active().get("startup"),
340
+ "stopped": STOPPED_FILE.exists(),
213
341
  "base_model": config.base_model(),
214
342
  "lora_adapter": config.lora_adapter(),
215
343
  "lora_name": config.lora_name(),