captchakraken 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -2
- package/README.md +3 -3
- package/bin/captchakraken.js +25 -0
- package/dist/solver.d.ts +2 -0
- package/dist/solver.js +7 -0
- package/dist/verdicts.js +34 -0
- package/package.json +5 -1
- package/python/AGENTS.md +2 -2
- package/python/README.md +3 -3
- package/python/pyproject.toml +1 -1
- package/python/src/captchakraken/__init__.py +1 -1
- package/python/src/captchakraken/cli.py +75 -1
- package/python/src/captchakraken/config.py +72 -7
- package/python/src/captchakraken/demo.py +149 -0
- package/python/src/captchakraken/models.json +9 -0
- package/python/src/captchakraken/page_solver.py +5 -1
- package/python/src/captchakraken/planner.py +13 -2
- package/python/src/captchakraken/pointer/server.py +5 -1
- package/python/src/captchakraken/pointer/vllm_plugin.py +9 -4
- package/python/src/captchakraken/selfhost.py +423 -0
- package/python/src/captchakraken/server_manager.py +124 -14
- package/python/src/captchakraken/verdicts.py +36 -0
|
@@ -14,7 +14,7 @@ from PIL import Image
|
|
|
14
14
|
from . import clipvideo, config, errors, prompts
|
|
15
15
|
from .clipvideo import ClipVideo
|
|
16
16
|
from .kinds import ActionKind, PixelAnswerKind, PromptFamily, RetryMode
|
|
17
|
-
from .server_manager import ensure_server
|
|
17
|
+
from .server_manager import ensure_server, is_local
|
|
18
18
|
|
|
19
19
|
DEBUG = os.getenv("CAPTCHA_DEBUG", "0") == "1"
|
|
20
20
|
|
|
@@ -245,6 +245,8 @@ def _same_drags(a: List[Dict[str, Any]], b: List[Dict[str, Any]]) -> bool:
|
|
|
245
245
|
|
|
246
246
|
class ActionPlanner:
|
|
247
247
|
|
|
248
|
+
_server_ensured = False
|
|
249
|
+
|
|
248
250
|
def __init__(
|
|
249
251
|
self,
|
|
250
252
|
model: Optional[str] = None,
|
|
@@ -286,8 +288,8 @@ class ActionPlanner:
|
|
|
286
288
|
self.experts = prompts.experts(_prompt_key)
|
|
287
289
|
if self.expert:
|
|
288
290
|
prompts.route(_prompt_key, None, pin=self.expert)
|
|
289
|
-
self._server_ensured = False
|
|
290
291
|
self._http = requests.Session()
|
|
292
|
+
self._http.trust_env = not is_local(self.base_url) # a machine's HTTP_PROXY must not carry a local call
|
|
291
293
|
self.outcome_supported = True
|
|
292
294
|
|
|
293
295
|
def _model_for(self, family: Optional[PromptFamily]) -> str:
|
|
@@ -545,6 +547,15 @@ class ActionPlanner:
|
|
|
545
547
|
"Content-Type": "application/json",
|
|
546
548
|
**routing_headers(hosted=config.is_hosted_endpoint(self.base_url)),
|
|
547
549
|
}
|
|
550
|
+
if not self._server_ensured:
|
|
551
|
+
try:
|
|
552
|
+
ensure_server(self.base_url)
|
|
553
|
+
except Exception as e:
|
|
554
|
+
# On an install `fetch` manages, the reason beats the "connection refused" the request would earn.
|
|
555
|
+
if config.selfhost_active():
|
|
556
|
+
raise
|
|
557
|
+
self._log(f"ensure_server: {e}")
|
|
558
|
+
self._server_ensured = True
|
|
548
559
|
url = f"{self.base_url}{self._POINTER_PATH}"
|
|
549
560
|
self._log(f"POST {url} model={self.model} media={sorted(k for k in body if k not in ('model', 'avoid'))}")
|
|
550
561
|
if self.avoid_refused and self.pointer_answers:
|
|
@@ -135,10 +135,14 @@ def main():
|
|
|
135
135
|
ap.add_argument("--host", default="127.0.0.1")
|
|
136
136
|
ap.add_argument("--port", type=int, default=8001)
|
|
137
137
|
ap.add_argument("--gpu-memory-utilization", type=float, default=0.45)
|
|
138
|
+
ap.add_argument("--max-cudagraph-capture-size", type=int, default=None,
|
|
139
|
+
help="largest batch vLLM compiles a graph for; each one holds GPU memory (small cards need this)")
|
|
138
140
|
a = ap.parse_args()
|
|
139
141
|
from .service import PointerService
|
|
142
|
+
capture = a.max_cudagraph_capture_size
|
|
140
143
|
svc = PointerService(a.model, detector=a.detector, letters=a.letters,
|
|
141
|
-
gpu_memory_utilization=a.gpu_memory_utilization
|
|
144
|
+
gpu_memory_utilization=a.gpu_memory_utilization,
|
|
145
|
+
**({"compilation_config": {"max_cudagraph_capture_size": capture}} if capture else {}))
|
|
142
146
|
ThreadingHTTPServer((a.host, a.port), make_handler(svc)).serve_forever()
|
|
143
147
|
|
|
144
148
|
|
|
@@ -25,6 +25,13 @@ def register() -> None:
|
|
|
25
25
|
ModelRegistry.register_model(ARCHITECTURE, "captchakraken.pointer.vllm_plugin:PointerQwen3_5")
|
|
26
26
|
|
|
27
27
|
|
|
28
|
+
def is_startup_run(ids, markers: int) -> bool:
|
|
29
|
+
"""vLLM's own start-up batches carry no prompt: its memory profile sends all-zero tokens, and
|
|
30
|
+
0.29's kernel warmup sends `range(2)`. Neither is long enough, or real enough, to hold the question
|
|
31
|
+
markers. A real prompt that lost its markers is long, so it still fails in `Positions`."""
|
|
32
|
+
return not bool(ids.any()) or ids.numel() < markers
|
|
33
|
+
|
|
34
|
+
|
|
28
35
|
def _model_class():
|
|
29
36
|
import torch
|
|
30
37
|
from vllm.model_executor.layers.pooler.abstract import Pooler
|
|
@@ -59,10 +66,8 @@ def _model_class():
|
|
|
59
66
|
if h is None: # a prefill chunk; the request is not finished yet
|
|
60
67
|
out.append(None)
|
|
61
68
|
continue
|
|
62
|
-
if
|
|
63
|
-
# vLLM
|
|
64
|
-
# sizes memory from this output, so it gets one of the real size.
|
|
65
|
-
# A real prompt without its markers still fails in Positions.
|
|
69
|
+
if is_startup_run(ids, len(L.QUESTIONS)):
|
|
70
|
+
# vLLM sizes memory from this output, so it gets one of the real size.
|
|
66
71
|
out.append(torch.zeros(L.PACKED + TRAILER, device=h.device))
|
|
67
72
|
continue
|
|
68
73
|
if h.shape[0] != ids.shape[0]:
|
|
@@ -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
|