captchakraken 5.0.0 → 5.2.0-beta.56

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.
@@ -1,11 +1,15 @@
1
1
  """`captchakraken fetch`: ask which model, GPU and startup mode, then install, download and start it.
2
2
 
3
+ A licensed model (Abyss) downloads from a gated Hub repo as the licence holder's own Hugging Face account,
4
+ so `fetch` checks that account can read it before the 8 GB serving stack installs, and says what to do if not.
5
+
3
6
  Everything lands under the state directory and the choices live in `selfhost.json`, so a solve, the
4
7
  server and `captchakraken start` read one file and nobody exports anything or edits their PATH.
5
8
  The serving stack gets its own environment because the one running this command may be a throwaway:
6
9
  npx and pipx both evict theirs, and a server must not break when they do.
7
10
  """
8
11
 
12
+ import getpass
9
13
  import json
10
14
  import os
11
15
  import secrets
@@ -16,9 +20,12 @@ import sys
16
20
  import venv
17
21
  from dataclasses import dataclass
18
22
  from pathlib import Path
19
- from typing import Callable, List, NamedTuple, Optional, Sequence
23
+ from typing import Callable, List, NamedTuple, Optional, Sequence, Tuple
24
+
25
+ import requests
20
26
 
21
- from . import __version__, config, server_manager
27
+ from . import __version__, config, prompts, server_manager
28
+ from .updater import PLANS_URL
22
29
 
23
30
  ALWAYS_ON = "always"
24
31
  FIRST_SOLVE = "first-solve"
@@ -40,6 +47,20 @@ class Model:
40
47
  min_vram_gb: int
41
48
  # Its share of a small card. Twilight's full-precision weights leave no KV cache at the default (measured, 8 GB).
42
49
  small_card_utilization: float = 0.72
50
+ # Other names `fetch <name>` and `--model` accept, besides the repo and its last part.
51
+ aliases: Tuple[str, ...] = ()
52
+ # False keeps it out of the interactive menu: a single-purpose model is reached by name, never offered to everyone.
53
+ listed: bool = True
54
+ # How an account without access gets it; empty means the Abyss Licence.
55
+ access: str = ""
56
+
57
+ @property
58
+ def licensed(self) -> bool:
59
+ """Read from the registry, the one place that says which weights are gated."""
60
+ return prompts.is_licensed(self.repo)
61
+
62
+ def named(self, wanted: str) -> bool:
63
+ return wanted.lower() in {n.lower() for n in (self.repo, self.repo.split("/")[-1], *self.aliases)}
43
64
 
44
65
 
45
66
  # Sunlight is absent on purpose: its published heads predate this client's layout and refuse to load.
@@ -48,9 +69,20 @@ MODELS = (
48
69
  3.8, 8),
49
70
  Model("CaptchaKraken/TwilightV2-2B", "Twilight V2 2B", "smaller model, full precision", 4.5, 8, 0.80),
50
71
  Model("CaptchaKraken/MidnightV2-4B", "Midnight V2 4B", "the same model at full precision", 9.1, 16),
72
+ Model("CaptchaKraken/AbyssV2-q4", "Abyss V2 Q4", "our most accurate model, needs an Abyss Licence",
73
+ 3.8, 8, aliases=("abyss",)),
74
+ Model("CaptchaKraken/AbyssV2", "Abyss V2", "Abyss at full precision, needs an Abyss Licence", 9.1, 16),
75
+ Model("CaptchaKraken/CaptchaKraken-Custom-Yidun-Commision", "CaptchaKraken Custom Yidun", "Abyss tuned for Yidun icon click-in-order boards",
76
+ 3.8, 8, aliases=("custom-yidun",), listed=False,
77
+ access=" Access to this model is granted by hand once its purchase is confirmed: send the CaptchaKraken team\n"
78
+ " your Hugging Face username. Then run this again."),
51
79
  )
52
80
 
53
81
 
82
+ def listed_models() -> Tuple[Model, ...]:
83
+ return tuple(m for m in MODELS if m.listed)
84
+
85
+
54
86
  class Gpu(NamedTuple):
55
87
  index: int
56
88
  name: str
@@ -170,12 +202,13 @@ def choose(title: str, options: Sequence[Option], default: int = 0) -> int:
170
202
  def ask(gpus: Sequence[Gpu], saved: dict) -> Choice:
171
203
  """Model, then GPU, then startup. A previous choice is where the cursor starts."""
172
204
  biggest = max(gpus, key=lambda g: g.total_mib)
173
- default_model = next((i for i, m in enumerate(MODELS) if m.repo == saved.get("model")), 0)
174
- picked = MODELS[choose("Which model do you want to run?", [
205
+ menu = listed_models()
206
+ default_model = next((i for i, m in enumerate(menu) if m.repo == saved.get("model")), 0)
207
+ picked = menu[choose("Which model do you want to run?", [
175
208
  Option(m.title, f"{m.blurb}, {m.download_gb:.1f} GB download, needs {m.min_vram_gb} GB of VRAM",
176
209
  "" if _fits(m, biggest) else f"needs {m.min_vram_gb} GB of VRAM, your largest has "
177
210
  f"{biggest.total_mib / 1024:.0f} GB")
178
- for m in MODELS], default_model)]
211
+ for m in menu], default_model)]
179
212
 
180
213
  fitting = [g for g in gpus if _fits(picked, g)]
181
214
  default_gpu = next((i for i, g in enumerate(gpus) if g.index == saved.get("gpu")), None)
@@ -193,6 +226,95 @@ def ask(gpus: Sequence[Gpu], saved: dict) -> Choice:
193
226
  return Choice(picked, gpu, startup)
194
227
 
195
228
 
229
+ # ── a licensed model's Hugging Face access ───────────────────────────────────
230
+
231
+ HUB = "https://huggingface.co"
232
+ HOSTED_API = "https://api.captchakraken.com"
233
+ # Replaced in tests; the signature is requests.request's.
234
+ _HUB_REQUEST: Callable = requests.request
235
+
236
+
237
+ def _hub_token_path() -> Path:
238
+ """Where huggingface_hub keeps the login `hf auth login` writes, so the download finds what was saved here."""
239
+ if os.getenv("HF_TOKEN_PATH"):
240
+ return Path(os.environ["HF_TOKEN_PATH"])
241
+ home = os.getenv("HF_HOME") or os.path.join(os.getenv("XDG_CACHE_HOME") or Path.home() / ".cache", "huggingface")
242
+ return Path(home) / "token"
243
+
244
+
245
+ def hub_token() -> Optional[str]:
246
+ token = os.getenv("HF_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN")
247
+ if token:
248
+ return token.strip()
249
+ try:
250
+ return _hub_token_path().read_text().strip() or None
251
+ except OSError:
252
+ return None
253
+
254
+
255
+ def _save_hub_token(token: str) -> None:
256
+ path = _hub_token_path()
257
+ try:
258
+ path.parent.mkdir(parents=True, exist_ok=True)
259
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
260
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
261
+ f.write(token)
262
+ os.chmod(path, 0o600)
263
+ except OSError as e:
264
+ raise RuntimeError(f"Could not save the Hugging Face token to {path}: {e}") from e
265
+
266
+
267
+ def _hub(http: Callable, method: str, url: str, token: str):
268
+ try:
269
+ return http(method, url, headers={"Authorization": f"Bearer {token}"}, timeout=20, allow_redirects=False)
270
+ except requests.RequestException as e:
271
+ raise RuntimeError(f"Could not reach Hugging Face to check the licence: {e}") from e
272
+
273
+
274
+ def _licence_steps() -> str:
275
+ return (f" An Abyss Licence comes with access: buy one at {PLANS_URL} and add your Hugging Face username there.\n"
276
+ f" Or use the hosted API ({HOSTED_API}), which serves Abyss to every account and needs no weights.")
277
+
278
+
279
+ def ensure_access(repo: str, *, interactive: bool, http: Optional[Callable] = None,
280
+ read_secret: Callable[[str], str] = getpass.getpass, access: str = "") -> str:
281
+ """The Hugging Face account that will download `repo`, once it is known to be allowed to. A token typed here is saved where huggingface_hub looks, so the download and later updates use it."""
282
+ http = http or _HUB_REQUEST
283
+ token, typed = hub_token(), False
284
+ if not token:
285
+ if not interactive:
286
+ raise RuntimeError(f"{repo} downloads as your Hugging Face account, and none is signed in here.\n"
287
+ " Set HF_TOKEN, or run `hf auth login`, then run this again.\n" + (access or _licence_steps()))
288
+ print(f"{repo} downloads as your Hugging Face account. Paste a token from "
289
+ f"{HUB}/settings/tokens (read access is enough).")
290
+ token, typed = read_secret("Hugging Face token: ").strip(), True
291
+ if not token:
292
+ raise Cancelled()
293
+
294
+ who = _hub(http, "GET", f"{HUB}/api/whoami-v2", token)
295
+ if who.status_code == 401:
296
+ raise RuntimeError("Hugging Face did not accept that token. Make a new one at "
297
+ f"{HUB}/settings/tokens and run this again.")
298
+ if who.status_code != 200:
299
+ raise RuntimeError(f"Hugging Face answered {who.status_code} when asked who the token belongs to. Try again shortly.")
300
+ user = who.json().get("name") or "this account"
301
+
302
+ probe = _hub(http, "HEAD", f"{HUB}/{repo}/resolve/main/config.json", token)
303
+ if probe.status_code in (401, 403, 404):
304
+ if access:
305
+ raise RuntimeError(f"Hugging Face account {user} cannot download {repo} yet.\n" + access)
306
+ raise RuntimeError(f"Hugging Face account {user} cannot download {repo} yet.\n"
307
+ f" If you have an Abyss Licence, set your Hugging Face username to {user} at {PLANS_URL};\n"
308
+ " access follows within a couple of minutes. Then run this again.\n" + _licence_steps())
309
+ if not 200 <= probe.status_code < 400:
310
+ raise RuntimeError(f"Hugging Face answered {probe.status_code} for {repo}. Try again shortly.")
311
+
312
+ if typed:
313
+ _save_hub_token(token)
314
+ _ok(f"Hugging Face account {user} has access to {repo}")
315
+ return user
316
+
317
+
196
318
  # ── installing ───────────────────────────────────────────────────────────────
197
319
 
198
320
  def _step(message: str) -> None:
@@ -363,10 +485,10 @@ def _summary(values: dict) -> None:
363
485
  def _from_flags(gpus: Sequence[Gpu], saved: dict, model: Optional[str], gpu: Optional[int],
364
486
  startup: Optional[str]) -> Choice:
365
487
  wanted = model or saved.get("model") or MODELS[0].repo
366
- found = next((m for m in MODELS if wanted in (m.repo, m.repo.split("/")[-1])), None)
488
+ found = next((m for m in MODELS if m.named(wanted)), None)
367
489
  if found is None:
368
- raise RuntimeError(f"Unknown model {wanted!r}. Choose from: "
369
- + ", ".join(m.repo.split("/")[-1] for m in MODELS))
490
+ raise RuntimeError(f"Unknown model {wanted!r}. Choose from: abyss, "
491
+ + ", ".join(m.repo.split("/")[-1] for m in listed_models()))
370
492
  index = gpu if gpu is not None else saved.get("gpu")
371
493
  if index is None:
372
494
  fitting = [g for g in gpus if _fits(found, g)]
@@ -405,6 +527,9 @@ def fetch(*, yes: bool = False, model: Optional[str] = None, gpu: Optional[int]
405
527
  else:
406
528
  print("\n\033[1mCaptchaKraken self-hosted setup\033[0m\n")
407
529
  choice = ask(gpus, saved)
530
+ if choice.model.licensed:
531
+ # A sign-in, not a choice: asked for whenever there is a terminal, --yes or not.
532
+ ensure_access(choice.model.repo, interactive=interactive, access=choice.model.access)
408
533
  values = install(choice, saved)
409
534
  except Cancelled:
410
535
  print("Cancelled. Nothing was changed.")