nai-cli 0.1.0__py3-none-any.whl

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 (75) hide show
  1. nai_cli/__init__.py +3 -0
  2. nai_cli/__main__.py +5 -0
  3. nai_cli/api.py +529 -0
  4. nai_cli/auth.py +240 -0
  5. nai_cli/batch.py +126 -0
  6. nai_cli/caches.py +56 -0
  7. nai_cli/charge.py +231 -0
  8. nai_cli/cli.py +110 -0
  9. nai_cli/comfyui.py +194 -0
  10. nai_cli/commands/__init__.py +61 -0
  11. nai_cli/commands/account.py +79 -0
  12. nai_cli/commands/batch.py +142 -0
  13. nai_cli/commands/config.py +57 -0
  14. nai_cli/commands/context.py +201 -0
  15. nai_cli/commands/copies.py +138 -0
  16. nai_cli/commands/cost.py +70 -0
  17. nai_cli/commands/generate.py +257 -0
  18. nai_cli/commands/generation.py +550 -0
  19. nai_cli/commands/grid.py +99 -0
  20. nai_cli/commands/image_tools.py +248 -0
  21. nai_cli/commands/interrogate.py +77 -0
  22. nai_cli/commands/lint.py +24 -0
  23. nai_cli/commands/local.py +62 -0
  24. nai_cli/commands/meta.py +102 -0
  25. nai_cli/commands/models.py +62 -0
  26. nai_cli/commands/output.py +165 -0
  27. nai_cli/commands/redact.py +48 -0
  28. nai_cli/commands/references.py +87 -0
  29. nai_cli/commands/spec.py +245 -0
  30. nai_cli/commands/stats.py +54 -0
  31. nai_cli/commands/strip.py +15 -0
  32. nai_cli/commands/tags.py +32 -0
  33. nai_cli/commands/texts.py +71 -0
  34. nai_cli/commands/vibe.py +151 -0
  35. nai_cli/commands/watermark.py +70 -0
  36. nai_cli/config.py +369 -0
  37. nai_cli/cost.py +114 -0
  38. nai_cli/data/random_prompt.json +2536 -0
  39. nai_cli/decode.py +87 -0
  40. nai_cli/enhance.py +137 -0
  41. nai_cli/errors.py +40 -0
  42. nai_cli/fs.py +209 -0
  43. nai_cli/grid.py +244 -0
  44. nai_cli/images.py +250 -0
  45. nai_cli/import_image.py +235 -0
  46. nai_cli/inpaint.py +476 -0
  47. nai_cli/ledger.py +146 -0
  48. nai_cli/lint.py +302 -0
  49. nai_cli/local_models.py +135 -0
  50. nai_cli/meta.py +606 -0
  51. nai_cli/models.py +308 -0
  52. nai_cli/naming.py +426 -0
  53. nai_cli/parser.py +611 -0
  54. nai_cli/pixel_snap.py +525 -0
  55. nai_cli/presets.py +276 -0
  56. nai_cli/prompt.py +457 -0
  57. nai_cli/random_prompt.py +285 -0
  58. nai_cli/request.py +621 -0
  59. nai_cli/rerun.py +177 -0
  60. nai_cli/resample.py +133 -0
  61. nai_cli/sam.py +63 -0
  62. nai_cli/share.py +392 -0
  63. nai_cli/sheet.py +86 -0
  64. nai_cli/tagger.py +464 -0
  65. nai_cli/tags.py +44 -0
  66. nai_cli/tidy.py +176 -0
  67. nai_cli/tokenizer.py +313 -0
  68. nai_cli/values.py +114 -0
  69. nai_cli/vibe.py +464 -0
  70. nai_cli-0.1.0.dist-info/METADATA +105 -0
  71. nai_cli-0.1.0.dist-info/RECORD +75 -0
  72. nai_cli-0.1.0.dist-info/WHEEL +4 -0
  73. nai_cli-0.1.0.dist-info/entry_points.txt +2 -0
  74. nai_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  75. nai_cli-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +56 -0
nai_cli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """nai-cli: NovelAI image generation from the command line."""
2
+
3
+ __version__ = "0.1.0"
nai_cli/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """python -m nai_cli runs the command line."""
2
+
3
+ from nai_cli.cli import main
4
+
5
+ raise SystemExit(main())
nai_cli/api.py ADDED
@@ -0,0 +1,529 @@
1
+ """NovelAI's HTTP API: the requests, their retries, and the replies read back as images and accounts."""
2
+
3
+ import base64
4
+ import io
5
+ import re
6
+ import struct
7
+ import time
8
+ import zipfile
9
+ import zlib
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass
12
+ from typing import Any, TypeVar
13
+ from urllib.parse import SplitResult, quote, urlsplit, urlunsplit
14
+
15
+ import httpx
16
+
17
+ from nai_cli import __version__, decode, errors, values
18
+
19
+ API = "https://api.novelai.net"
20
+ # Generation, tools, login and account endpoints of the official service all live on this host
21
+ IMAGE = "https://image.novelai.net"
22
+ WEB = "https://novelai.net"
23
+ RETRY_429 = [5, 10, 20, 40, 60]
24
+ RETRY_5XX = [5]
25
+ TIMEOUT = httpx.Timeout(connect=30, read=180, write=60, pool=30)
26
+ # Token counts fall back to estimates, so an unreachable host should not hold up lint for long
27
+ TOKENIZER_TIMEOUT = httpx.Timeout(connect=10, read=30, write=10, pool=10)
28
+ # The larger tokenizer file is under 4 MB
29
+ _MAX_TOKENIZER = 32 * 1024 * 1024
30
+ # Server messages are cut to this length after credentials are hidden
31
+ _MAX_MESSAGE = 500
32
+ # Characters encodeURIComponent leaves as they are
33
+ _URI_SAFE = "-_.!~*'()"
34
+ # The connection was never made, so nothing reached NovelAI and even a paid request can be sent again
35
+ _NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
36
+ _BEARER = re.compile(r"Bearer\s+\S+")
37
+ # A 4096x4096 RGBA PNG stored without compression is 64 MiB
38
+ _MAX_ENTRY = 128 * 1024 * 1024
39
+ # More than any reply holds: eight images, or the three of background removal
40
+ _MAX_ENTRIES = 32
41
+ _MAX_REPLY = 4 * _MAX_ENTRY
42
+ # What a truncated or foreign archive raises while reading
43
+ _BAD_ARCHIVE = (
44
+ zipfile.BadZipFile,
45
+ zlib.error,
46
+ EOFError,
47
+ KeyError,
48
+ ValueError,
49
+ NotImplementedError,
50
+ RuntimeError,
51
+ OSError,
52
+ struct.error,
53
+ )
54
+ # Account types the official client counts as subscribed whatever the expiry: B2B, service, support, admin
55
+ _STAFF_ACCOUNTS = {1, 2, 3, 4}
56
+ # What a JSON reply of the wrong shape raises while reading
57
+ _BAD_REPLY = (ValueError, TypeError, KeyError, AttributeError)
58
+ T = TypeVar("T")
59
+
60
+
61
+ def fetch_tokenizer(name: str, version: int) -> bytes:
62
+ """The tokenizer file the official client loads for counting; free and needs no token. ValueError for one
63
+ larger than any tokenizer, httpx.HTTPError when it cannot be fetched."""
64
+ url = f"{WEB}/tokenizer/compressed/{name}?v={version}&static=true"
65
+ data = _download(url, _MAX_TOKENIZER, TOKENIZER_TIMEOUT, follow_redirects=False)
66
+ if len(data) > _MAX_TOKENIZER:
67
+ raise ValueError(f"{url} sends more than {_MAX_TOKENIZER} bytes")
68
+ return data
69
+
70
+
71
+ def fetch_file(url: str, size: int) -> bytes:
72
+ """A public file of a known size, such as a local model; anything of another size is refused."""
73
+ try:
74
+ data = _download(url, size, TIMEOUT, follow_redirects=True)
75
+ except httpx.HTTPError as e:
76
+ raise errors.NaiError(errors.NETWORK, f"cannot download {url}: {e}") from e
77
+ if len(data) != size:
78
+ raise errors.NaiError(errors.NETWORK, f"{url} sent {len(data)} bytes where {size} were expected")
79
+ return data
80
+
81
+
82
+ def _download(url: str, limit: int, timeout: httpx.Timeout, follow_redirects: bool) -> bytes:
83
+ """At most limit + 1 bytes, so a reply too large is known without holding it all."""
84
+ with httpx.stream(
85
+ "GET", url, headers={"User-Agent": f"nai-cli/{__version__}"}, timeout=timeout, follow_redirects=follow_redirects
86
+ ) as response:
87
+ response.raise_for_status()
88
+ data = bytearray()
89
+ for chunk in response.iter_bytes():
90
+ data += chunk
91
+ if len(data) > limit:
92
+ break
93
+ return bytes(data)
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Endpoint:
98
+ """Where requests go: the official hosts, or a NovelAI-compatible relay that may serve both from one URL."""
99
+
100
+ api_base: str = API
101
+ image_base: str = IMAGE
102
+
103
+ @property
104
+ def official(self) -> bool:
105
+ return self == OFFICIAL
106
+
107
+ def image(self, path: str) -> str:
108
+ return self.image_base + path
109
+
110
+ def user(self, path: str) -> str:
111
+ # The official service answers user endpoints on the image host; relays keep their own layout
112
+ return self.image(path) if self.official else self.api_base + path
113
+
114
+
115
+ OFFICIAL = Endpoint()
116
+
117
+
118
+ def endpoint(api_url: str, image_url: str = "") -> Endpoint:
119
+ """A relay's addresses as typed: https:// is assumed, and http:// for this machine; image_url defaults to
120
+ api_url."""
121
+ main = _base_url(api_url)
122
+ return Endpoint(main, _base_url(image_url) if image_url.strip() else main)
123
+
124
+
125
+ def _base_url(value: str) -> str:
126
+ parts = _address(value)
127
+ return urlunsplit((parts.scheme, parts.netloc, parts.path.rstrip("/"), "", ""))
128
+
129
+
130
+ def _address(value: str) -> SplitResult:
131
+ """https:// is assumed, and http:// for this machine. ValueError for anything but an http or https address
132
+ of a host without credentials in it."""
133
+ text = value.strip()
134
+ if "://" not in text:
135
+ host = text.split("/", 1)[0].lower()
136
+ local = host.split(":", 1)[0] in ("localhost", "127.0.0.1") or host.startswith("[::1]")
137
+ text = ("http://" if local else "https://") + text
138
+ try:
139
+ parts = urlsplit(text)
140
+ hostname = parts.hostname
141
+ except ValueError:
142
+ hostname = None
143
+ # The address is not repeated, since a key or password put in it by mistake would be printed
144
+ if hostname is None or parts.scheme not in ("http", "https"):
145
+ raise ValueError("the address is not an http or https address")
146
+ if parts.query or parts.fragment or parts.username or parts.password:
147
+ raise ValueError("the address takes no query, fragment, user or password; the token goes in token")
148
+ return parts
149
+
150
+
151
+ def login(endpoint: Endpoint, access_key: str, transport: httpx.BaseTransport | None = None) -> str:
152
+ """Exchange an access key for a token, as the official login does; the token lasts 30 days."""
153
+ with httpx.Client(headers={"User-Agent": f"nai-cli/{__version__}"}, timeout=TIMEOUT, transport=transport) as http:
154
+ try:
155
+ response = http.post(endpoint.user("/user/login"), json={"key": access_key})
156
+ except httpx.TransportError as e:
157
+ raise errors.NaiError(errors.NETWORK, f"cannot reach NovelAI: {scrub(str(e), (access_key,))}") from e
158
+ if response.status_code in (401, 403):
159
+ raise errors.NaiError(errors.AUTH, "NovelAI refused the email or password", status=response.status_code)
160
+ if response.status_code >= 400:
161
+ raise _status_error(response, (access_key,))
162
+ return _parsed(response, "login reply", lambda data: _text_field(data, "accessToken"), (access_key,))
163
+
164
+
165
+ def _text_field(data: dict[str, Any], key: str) -> str:
166
+ value = data[key]
167
+ if not isinstance(value, str) or not value:
168
+ raise ValueError(f"{key} is not a text but {type(value).__name__}")
169
+ return value
170
+
171
+
172
+ @dataclass
173
+ class Account:
174
+ tier: int
175
+ active: bool
176
+ anlas_fixed: int
177
+ anlas_purchased: int
178
+ quota_percent: float | None
179
+ quota_negative: bool
180
+ quota_next_percent_seconds: float | None
181
+ # A relay without the subscription endpoint: prices are standard and the spend cannot be measured
182
+ measured: bool = True
183
+
184
+ @property
185
+ def anlas(self) -> int:
186
+ return self.anlas_fixed + self.anlas_purchased
187
+
188
+ @property
189
+ def opus(self) -> bool:
190
+ return self.tier >= 3 and self.active
191
+
192
+ def to_json(self) -> dict[str, Any]:
193
+ if not self.measured:
194
+ return {"measured": False}
195
+ return {
196
+ "tier": {0: "Paper", 1: "Tablet", 2: "Scroll", 3: "Opus"}.get(self.tier, str(self.tier)),
197
+ "active": self.active,
198
+ "anlas": self.anlas,
199
+ "anlas_fixed": self.anlas_fixed,
200
+ "anlas_purchased": self.anlas_purchased,
201
+ "quota_percent": self.quota_percent,
202
+ "quota_exhausted": self.quota_negative,
203
+ "quota_next_percent_seconds": self.quota_next_percent_seconds,
204
+ }
205
+
206
+
207
+ def _multipart(image: bytes, request: dict[str, Any], mask: bytes | None = None) -> dict[str, tuple[str, bytes, str]]:
208
+ """The image, then the mask, then the request, whose fields name the parts; a mask equal to the image is sent
209
+ once, as the official client sends it."""
210
+ parts = {"image": ("blob", image, "image/png")}
211
+ if mask is not None and mask != image:
212
+ parts["mask"] = ("blob", mask, "image/png")
213
+ parts["request"] = ("blob", values.to_json(values.as_js(request)).encode(), "application/json")
214
+ return parts
215
+
216
+
217
+ class DamagedImages(errors.NaiError):
218
+ """Some images of a paid reply do not decode. The error carries every image in order, None where damaged,
219
+ so the others can still be saved under their own numbers."""
220
+
221
+ def __init__(self, message: str, images: list[bytes | None]) -> None:
222
+ super().__init__(errors.API, message, maybe_processed=True)
223
+ self.images = images
224
+
225
+
226
+ def unzip_images(data: bytes) -> list[bytes | None]:
227
+ """Each image in a reply, None for an entry that cannot be read, so one damaged entry spares the rest."""
228
+ if data[:2] != b"PK":
229
+ return [data] if data[:8] == b"\x89PNG\r\n\x1a\n" else []
230
+ with zipfile.ZipFile(io.BytesIO(data)) as z:
231
+ names = sorted(n for n in z.namelist() if n.lower().endswith((".png", ".jpg", ".webp")))
232
+ out: list[bytes | None] = []
233
+ room = _MAX_REPLY
234
+ for name in names[:_MAX_ENTRIES]:
235
+ entry = _entry(z, name, min(_MAX_ENTRY, room))
236
+ room -= len(entry) if entry is not None else 0
237
+ out.append(entry)
238
+ return out
239
+
240
+
241
+ def _entry(z: zipfile.ZipFile, name: str, limit: int) -> bytes | None:
242
+ # An entry past the limit is not read, so a small reply cannot fill the memory
243
+ try:
244
+ with z.open(name) as f:
245
+ data = f.read(limit + 1)
246
+ except _BAD_ARCHIVE:
247
+ return None
248
+ return data if len(data) <= limit else None
249
+
250
+
251
+ def _parsed(response: httpx.Response, what: str, read: Callable[[Any], T], secrets: tuple[str, ...]) -> T:
252
+ try:
253
+ return read(values.parse_json(response.content))
254
+ except _BAD_REPLY as e:
255
+ # The error may quote the reply, which a relay may have filled with what was sent
256
+ reason = _short(scrub(f"{type(e).__name__}: {e}", secrets))
257
+ raise errors.NaiError(errors.API, f"unexpected {what} from NovelAI: {reason}") from e
258
+
259
+
260
+ def _number(value: Any, name: str) -> float:
261
+ if not values.is_number(value):
262
+ raise ValueError(f"{name} is {value!r}")
263
+ return value
264
+
265
+
266
+ def _optional_number(value: Any, name: str) -> float | None:
267
+ return None if value is None else _number(value, name)
268
+
269
+
270
+ def _account(data: dict[str, Any]) -> Account:
271
+ # As in the official client: two counts or a single number, and anything else is an error rather than 0
272
+ steps = data["trainingStepsLeft"]
273
+ if isinstance(steps, dict):
274
+ fixed = _number(steps["fixedTrainingStepsLeft"], "fixedTrainingStepsLeft")
275
+ purchased = _number(steps["purchasedTrainingSteps"], "purchasedTrainingSteps")
276
+ else:
277
+ fixed, purchased = _number(steps, "trainingStepsLeft"), 0
278
+ tier = int(_number(data["tier"], "tier"))
279
+ expires = _optional_number(data.get("expiresAt"), "expiresAt")
280
+ # Decided as the official client does; the reply's own active flag only drives its billing pages
281
+ active = _optional_number(data.get("accountType"), "accountType") in _STAFF_ACCOUNTS or (
282
+ expires is not None and expires > time.time() and tier > 0
283
+ )
284
+ usage = data.get("usage") or {}
285
+ return Account(
286
+ tier=tier,
287
+ active=active,
288
+ anlas_fixed=int(fixed),
289
+ anlas_purchased=int(purchased),
290
+ quota_percent=_optional_number(usage.get("percent"), "usage.percent"),
291
+ quota_negative=bool(usage.get("isNegative", False)),
292
+ quota_next_percent_seconds=_optional_number(usage.get("timeUntilNextPercent"), "usage.timeUntilNextPercent"),
293
+ )
294
+
295
+
296
+ UNMEASURED = Account(0, False, 0, 0, None, False, None, measured=False)
297
+
298
+
299
+ def _tags(data: Any) -> list[dict[str, Any]]:
300
+ # Japanese lookups return a bare list with jp_tag, en_tag and power
301
+ if isinstance(data, list):
302
+ return [{"tag": t["en_tag"], "jp": t["jp_tag"], "count": t["power"]} for t in data]
303
+ return [{"tag": t["tag"], "count": t["count"]} for t in data.get("tags", [])]
304
+
305
+
306
+ def _decodes(data: bytes | None) -> bool:
307
+ if data is None:
308
+ return False
309
+ try:
310
+ decode.verify(data)
311
+ except decode.BAD_IMAGE:
312
+ return False
313
+ return True
314
+
315
+
316
+ def _error_message(response: httpx.Response, secrets: tuple[str, ...]) -> str:
317
+ """What the server says went wrong, short, with the credentials sent hidden in case a relay repeats them."""
318
+ try:
319
+ payload = values.parse_json(response.content)
320
+ except ValueError:
321
+ text = response.text or response.reason_phrase
322
+ else:
323
+ found = payload.get("message") or payload.get("error") if isinstance(payload, dict) else None
324
+ text = str(found or payload)
325
+ # Hidden before cutting, so a credential cut in half cannot show its first part
326
+ return _short(scrub(text, secrets))
327
+
328
+
329
+ def _short(text: str) -> str:
330
+ return text if len(text) <= _MAX_MESSAGE else text[:_MAX_MESSAGE] + "…"
331
+
332
+
333
+ def _status_error(response: httpx.Response, secrets: tuple[str, ...]) -> errors.NaiError:
334
+ """The error of a request NovelAI refused or failed, by its status."""
335
+ status = response.status_code
336
+ code = {
337
+ 401: errors.AUTH,
338
+ 402: errors.INSUFFICIENT_ANLAS,
339
+ 429: errors.RATE_LIMITED,
340
+ }.get(status, errors.SERVER if status >= 500 else errors.API)
341
+ return errors.NaiError(code, f"NovelAI returned {status}: {_error_message(response, secrets)}", status=status)
342
+
343
+
344
+ def scrub(text: str, secrets: tuple[str, ...]) -> str:
345
+ for secret in secrets:
346
+ if secret:
347
+ text = text.replace(secret, "<hidden>")
348
+ return _BEARER.sub("Bearer <hidden>", text)
349
+
350
+
351
+ class Client:
352
+ def __init__(
353
+ self,
354
+ token: str,
355
+ endpoint: Endpoint = OFFICIAL,
356
+ sleep: Callable[[float], None] = time.sleep,
357
+ transport: httpx.BaseTransport | None = None,
358
+ before_send: Callable[[], None] | None = None,
359
+ ):
360
+ self.endpoint = endpoint
361
+ # Called as each request goes on the wire, which paces a batch
362
+ self._before_send = before_send or (lambda: None)
363
+ self._secrets = (token,)
364
+ self._sleep = sleep
365
+ self._http = httpx.Client(
366
+ headers={"Authorization": f"Bearer {token}", "User-Agent": f"nai-cli/{__version__}"},
367
+ timeout=TIMEOUT,
368
+ transport=transport,
369
+ )
370
+ self.retries: list[dict[str, Any]] = []
371
+
372
+ def close(self) -> None:
373
+ self._http.close()
374
+
375
+ def __enter__(self) -> "Client":
376
+ return self
377
+
378
+ def __exit__(self, *exc: object) -> None:
379
+ self.close()
380
+
381
+ def _wait(self, seconds: float) -> None:
382
+ # Nothing is in flight between attempts, and a paid request is only retried when it cannot have run
383
+ try:
384
+ self._sleep(seconds)
385
+ except KeyboardInterrupt:
386
+ raise errors.NaiError(errors.INTERRUPTED, "interrupted") from None
387
+
388
+ def _send(self, method: str, url: str, paid: bool = False, **kwargs: Any) -> httpx.Response:
389
+ """Paid requests are sent again only when they cannot have run, as the official client never resends them;
390
+ 429 means the request was refused."""
391
+ attempt_429 = attempt_5xx = attempt_net = 0
392
+ while True:
393
+ self._before_send()
394
+ try:
395
+ response = self._http.request(method, url, **kwargs)
396
+ except httpx.TransportError as e:
397
+ unsent = isinstance(e, _NOT_SENT)
398
+ if attempt_net < 1 and (unsent or not paid):
399
+ attempt_net += 1
400
+ self.retries.append({"reason": "network", "error": scrub(str(e), self._secrets)})
401
+ self._wait(5)
402
+ continue
403
+ if paid and not unsent:
404
+ raise errors.NaiError(
405
+ errors.NETWORK,
406
+ "lost the connection to NovelAI after sending the request, which may have run: "
407
+ + scrub(str(e), self._secrets),
408
+ maybe_processed=True,
409
+ ) from e
410
+ raise errors.NaiError(errors.NETWORK, f"cannot reach NovelAI: {scrub(str(e), self._secrets)}") from e
411
+ status = response.status_code
412
+ if status < 400:
413
+ return response
414
+ message = _error_message(response, self._secrets)
415
+ if status == 429 and attempt_429 < len(RETRY_429):
416
+ wait = RETRY_429[attempt_429]
417
+ attempt_429 += 1
418
+ self.retries.append({"reason": "429", "wait": wait, "message": message})
419
+ self._wait(wait)
420
+ continue
421
+ if status >= 500 and paid:
422
+ raise errors.NaiError(
423
+ errors.SERVER,
424
+ f"NovelAI returned {status}, and the request may have run: {message}",
425
+ status=status,
426
+ maybe_processed=True,
427
+ )
428
+ if status >= 500 and attempt_5xx < len(RETRY_5XX):
429
+ wait = RETRY_5XX[attempt_5xx]
430
+ attempt_5xx += 1
431
+ self.retries.append({"reason": str(status), "wait": wait, "message": message})
432
+ self._wait(wait)
433
+ continue
434
+ raise _status_error(response, self._secrets)
435
+
436
+ @staticmethod
437
+ def _images(response: httpx.Response, what: str, expected: int = 1) -> list[bytes]:
438
+ """A paid request answered with 200 has run, so an unusable reply may still have been charged. Images
439
+ missing from the reply count as damaged, after the ones that came."""
440
+ try:
441
+ entries = unzip_images(response.content)
442
+ except _BAD_ARCHIVE as e:
443
+ raise errors.NaiError(
444
+ errors.API, f"NovelAI sent a damaged {what}: {type(e).__name__}: {e}", maybe_processed=True
445
+ ) from e
446
+ if not entries:
447
+ raise errors.NaiError(errors.API, f"no image in the {what}", maybe_processed=True)
448
+ decoded: list[bytes | None] = [p if _decodes(p) else None for p in entries]
449
+ decoded += [None] * (expected - len(decoded))
450
+ damaged = decoded.count(None)
451
+ if damaged:
452
+ raise DamagedImages(f"{damaged} of {len(decoded)} images in the {what} are damaged or missing", decoded)
453
+ return [p for p in decoded if p is not None]
454
+
455
+ def generate(self, body: dict[str, Any]) -> list[bytes]:
456
+ response = self._send(
457
+ "POST",
458
+ self.endpoint.image("/ai/generate-image"),
459
+ paid=True,
460
+ content=values.to_json(values.as_js(body)).encode(),
461
+ headers={"Content-Type": "application/json"},
462
+ )
463
+ return self._images(response, "response", body.get("parameters", {}).get("n_samples", 1))
464
+
465
+ def upscale(self, image: bytes) -> list[bytes]:
466
+ request = {"image": "image", "model": "nai-diffusion-5-curated", "declared_blur_sigma": 0}
467
+ response = self._send("POST", self.endpoint.image("/ai/upscale"), paid=True, files=_multipart(image, request))
468
+ return self._images(response, "upscale response")
469
+
470
+ def augment(
471
+ self,
472
+ image: bytes,
473
+ req_type: str,
474
+ width: int,
475
+ height: int,
476
+ prompt: str = "",
477
+ defry: int = 0,
478
+ expected: int = 1,
479
+ ) -> list[bytes]:
480
+ """Every image of the reply: background removal returns three, as presets.TOOL_OUTPUTS names them."""
481
+ request: dict[str, Any] = {"req_type": req_type, "use_new_shared_trial": True}
482
+ if req_type in ("colorize", "emotion"):
483
+ request["prompt"] = prompt
484
+ request["defry"] = defry
485
+ request.update({"width": width, "height": height, "image": "image"})
486
+ response = self._send(
487
+ "POST", self.endpoint.image("/ai/augment-image"), paid=True, files=_multipart(image, request)
488
+ )
489
+ return self._images(response, "Director tool response", expected)
490
+
491
+ def encode_vibe(self, image: bytes, model: str, information_extracted: float = 1.0, mask: str | None = None) -> str:
492
+ """mask is the base64 PNG a Vibe file keeps."""
493
+ request: dict[str, Any] = {"image": "image", "information_extracted": information_extracted}
494
+ # An empty mask stays in the request but sends no part, as the official client only uploads a non-empty one
495
+ mask_png = base64.b64decode(mask) if mask else None
496
+ if mask is not None:
497
+ request["mask"] = mask if mask_png is None else "image" if mask_png == image else "mask"
498
+ request["model"] = model
499
+ response = self._send(
500
+ "POST", self.endpoint.image("/ai/encode-vibe"), paid=True, files=_multipart(image, request, mask_png)
501
+ )
502
+ if not response.content:
503
+ raise errors.NaiError(errors.API, "NovelAI sent back an empty Vibe encoding", maybe_processed=True)
504
+ return base64.b64encode(response.content).decode()
505
+
506
+ def suggest_tags(self, prompt: str, model: str, lexicon: str | None, lang: str | None) -> list[dict[str, Any]]:
507
+ query = f"model={quote(model, safe=_URI_SAFE)}&prompt={quote(prompt, safe=_URI_SAFE)}"
508
+ if lexicon:
509
+ query += f"&type={lexicon}"
510
+ if lang:
511
+ query += f"&lang={lang}"
512
+ response = self._send(
513
+ "GET",
514
+ self.endpoint.image(f"/ai/generate-image/suggest-tags?{query}"),
515
+ headers={"Content-Type": "application/json"},
516
+ )
517
+ return _parsed(response, "tag suggestions", _tags, self._secrets)
518
+
519
+ def account(self) -> Account:
520
+ try:
521
+ response = self._send("GET", self.endpoint.user("/user/subscription"))
522
+ except errors.NaiError as e:
523
+ if self.endpoint.official or e.detail.get("status") != 404:
524
+ raise
525
+ return UNMEASURED
526
+ # A relay may answer unknown paths with a web page
527
+ if not self.endpoint.official and "json" not in response.headers.get("content-type", ""):
528
+ return UNMEASURED
529
+ return _parsed(response, "account details", _account, self._secrets)