captchakraken 4.0.0 → 4.1.1

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.
@@ -17,6 +17,9 @@ STATE_DIR = config.state_dir()
17
17
  LOCK_FILE = STATE_DIR / "vllm.lock"
18
18
  PID_FILE = STATE_DIR / "vllm.pid"
19
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"
20
23
 
21
24
  STARTUP_TIMEOUT_S = int(os.getenv("CAPTCHA_KRAKEN_STARTUP_TIMEOUT", "600"))
22
25
 
@@ -38,7 +41,9 @@ def is_local(base_url: str) -> bool:
38
41
 
39
42
  def is_healthy(base_url: str, timeout: float = 2.0) -> bool:
40
43
  try:
41
- 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)
42
47
  return r.ok
43
48
  except requests.RequestException:
44
49
  return False
@@ -53,7 +58,12 @@ def _vllm_bin() -> "str | None":
53
58
 
54
59
 
55
60
  def _vllm_available() -> bool:
56
- 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
57
67
 
58
68
 
59
69
  def _read_pid() -> "int | None":
@@ -61,6 +71,12 @@ def _read_pid() -> "int | None":
61
71
  pid = int(PID_FILE.read_text().strip())
62
72
  except (OSError, ValueError):
63
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
64
80
  try:
65
81
  os.kill(pid, 0)
66
82
  return pid
@@ -72,14 +88,18 @@ def build_serve_command() -> "list[str]":
72
88
  from . import prompts
73
89
 
74
90
  if prompts.resolve(config.lora_adapter()).pointer:
75
- detector = os.environ["CAPTCHA_POINTER_DETECTOR"]
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()
76
95
  return [
77
- sys.executable, "-m", "captchakraken.pointer.server",
78
- "--model", config.base_model(),
96
+ _serve_python(), "-m", "captchakraken.pointer.server",
97
+ "--model", config.serve_model(),
79
98
  "--detector", detector,
80
99
  "--host", os.getenv("CAPTCHA_POINTER_HOST", "127.0.0.1"),
81
100
  "--port", str(config.port()),
82
101
  "--gpu-memory-utilization", str(config.gpu_memory_utilization()),
102
+ *(["--max-cudagraph-capture-size", str(capture)] if capture else []),
83
103
  ]
84
104
  return [
85
105
  _vllm_bin() or "vllm", "serve", config.base_model(),
@@ -106,6 +126,13 @@ def _serve_env() -> dict:
106
126
  # Only forward a real key; api_key() falls back to "EMPTY", which would lock vLLM to a placeholder.
107
127
  if key and key != "EMPTY":
108
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))
109
136
  return env
110
137
 
111
138
 
@@ -113,9 +140,8 @@ def _spawn() -> subprocess.Popen:
113
140
  STATE_DIR.mkdir(parents=True, exist_ok=True)
114
141
  if not _vllm_available():
115
142
  raise RuntimeError(
116
- "vLLM is not installed, so a local server can't be started. Run the "
117
- "setup script (./setup.sh) or `pip install \"captchakraken[serve]\"`, "
118
- "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."
119
145
  )
120
146
  cmd = build_serve_command()
121
147
  _log("starting: " + " ".join(cmd))
@@ -134,18 +160,88 @@ def _spawn() -> subprocess.Popen:
134
160
  return proc
135
161
 
136
162
 
137
- def _wait_healthy(base_url: str, timeout: float) -> bool:
163
+ def _wait_healthy(base_url: str, timeout: float, alive=None) -> bool:
138
164
  deadline = time.time() + timeout
165
+ alive = alive or (lambda: _read_pid() is not None)
139
166
  while time.time() < deadline:
140
167
  if is_healthy(base_url, timeout=2.0):
141
168
  return True
142
- pid = _read_pid()
143
- if pid is None:
169
+ if not alive():
144
170
  return False
145
171
  time.sleep(2.0)
146
172
  return False
147
173
 
148
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
+
149
245
  def ensure_server(base_url: "str | None" = None) -> None:
150
246
  base_url = base_url or config.base_url()
151
247
 
@@ -156,6 +252,8 @@ def ensure_server(base_url: "str | None" = None) -> None:
156
252
  return
157
253
  if not config.autostart_enabled():
158
254
  return
255
+ if config.selfhost_active() and STOPPED_FILE.exists():
256
+ raise RuntimeError("The CaptchaKraken server is stopped. Start it with: captchakraken start")
159
257
 
160
258
  STATE_DIR.mkdir(parents=True, exist_ok=True)
161
259
  # Two solves racing on first use must not both spawn a server; re-check under the lock.
@@ -174,10 +272,13 @@ def ensure_server(base_url: "str | None" = None) -> None:
174
272
 
175
273
  def start(background: bool = True) -> dict:
176
274
  base_url = config.base_url()
275
+ STOPPED_FILE.unlink(missing_ok=True)
177
276
  if is_healthy(base_url):
178
277
  return {"status": "already-running", "base_url": base_url, "pid": _read_pid()}
179
278
  if not background:
180
279
  run_foreground()
280
+ if _always_on():
281
+ return _start_unit(base_url)
181
282
  _spawn()
182
283
  ok = _wait_healthy(base_url, STARTUP_TIMEOUT_S)
183
284
  return {
@@ -191,17 +292,23 @@ def start(background: bool = True) -> dict:
191
292
  def run_foreground() -> None:
192
293
  if not _vllm_available():
193
294
  raise RuntimeError(
194
- "vLLM is not installed. Run ./setup.sh or "
195
- "`pip install \"captchakraken[serve]\"`."
295
+ "vLLM is not installed. Run `captchakraken fetch`."
196
296
  )
197
297
  cmd = build_serve_command()
198
298
  os.execvpe(cmd[0], cmd, _serve_env())
199
299
 
200
300
 
201
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)
202
309
  pid = _read_pid()
203
310
  if pid is None:
204
- return {"status": "not-running"}
311
+ return {"status": "stopped" if was_on else "not-running"}
205
312
  try:
206
313
  os.killpg(os.getpgid(pid), signal.SIGTERM)
207
314
  except OSError:
@@ -228,6 +335,9 @@ def status(base_url: "str | None" = None) -> dict:
228
335
  "local": is_local(base_url),
229
336
  "pid": _read_pid(),
230
337
  "autostart": config.autostart_enabled(),
338
+ "gpu": config.selfhost_active().get("gpu"),
339
+ "startup": config.selfhost_active().get("startup"),
340
+ "stopped": STOPPED_FILE.exists(),
231
341
  "base_model": config.base_model(),
232
342
  "lora_adapter": config.lora_adapter(),
233
343
  "lora_name": config.lora_name(),
@@ -65,6 +65,38 @@ def _jsonp_result(body: str) -> Optional[Verdict]:
65
65
  return {"success": Verdict.ACCEPTED, "fail": Verdict.REJECTED}.get(result) if isinstance(result, str) else None
66
66
 
67
67
 
68
+ def _tencent_ticket(body: str) -> Optional[Verdict]:
69
+ """`{"errorCode": "0", "ticket": ...}` when taken; `{"errorCode": "50", "ticket": ""}` when a wrong slide is refused.
70
+ Any other code (rate limits, expired sessions) has not been recorded, so the DOM judges it."""
71
+ data = _json(body)
72
+ if not isinstance(data, dict):
73
+ return None
74
+ code = str(data.get("errorCode"))
75
+ if code == "0" and data.get("ticket"):
76
+ return Verdict.ACCEPTED
77
+ return Verdict.REJECTED if code == "50" and not data.get("ticket") else None
78
+
79
+
80
+ def _yidun_check(body: str) -> Optional[Verdict]:
81
+ """`callback({"data": {"result": true, ...}, "error": 0})` when taken, `"result": false` with `"error": 0` when refused."""
82
+ start, end = body.find("("), body.rfind(")")
83
+ data = _json(body[start + 1:end]) if 0 <= start < end else None
84
+ if not isinstance(data, dict) or data.get("error") != 0:
85
+ return None
86
+ result = (data.get("data") or {}).get("result")
87
+ return {True: Verdict.ACCEPTED, False: Verdict.REJECTED}.get(result) if isinstance(result, bool) else None
88
+
89
+
90
+ def _arkose_answer(body: str) -> Optional[Verdict]:
91
+ """`solved: true` when taken; `solved: false` with `time_end` set when the session ended refused."""
92
+ data = _json(body)
93
+ if not isinstance(data, dict):
94
+ return None
95
+ if data.get("solved") is True:
96
+ return Verdict.ACCEPTED
97
+ return Verdict.REJECTED if data.get("solved") is False and data.get("time_end") is not None else None
98
+
99
+
68
100
  def _url_only(_body: str) -> Optional[Verdict]:
69
101
  return Verdict.NEW_CHALLENGE
70
102
 
@@ -85,6 +117,10 @@ VERDICT_ENDPOINTS: Mapping[Vendor, Sequence[VerdictEndpoint]] = {
85
117
  VerdictEndpoint("/recaptcha/api2/reload", _new_board)),
86
118
  Vendor.GEETEST: (VerdictEndpoint("geetest.com/verify", _jsonp_result),
87
119
  VerdictEndpoint("geetest.com/load", _url_only)),
120
+ Vendor.TENCENT: (VerdictEndpoint("/cap_union_new_verify", _tencent_ticket),),
121
+ Vendor.YIDUN: (VerdictEndpoint("dun.163.com/api/v3/check", _yidun_check),),
122
+ # Sites serve this from their own hostnames, so the path is what identifies it.
123
+ Vendor.FUNCAPTCHA: (VerdictEndpoint("/fc/ca/", _arkose_answer),),
88
124
  }
89
125
 
90
126