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/vibe.py ADDED
@@ -0,0 +1,464 @@
1
+ """Read and write .naiv4vibe files; user files are never modified."""
2
+
3
+ import base64
4
+ import binascii
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import math
9
+ import re
10
+ import time
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from PIL import Image
16
+
17
+ from nai_cli import decode, errors, images, models, resample, values
18
+ from nai_cli.meta import model_of, png_text_entries, read_raw
19
+ from nai_cli.request import check_range
20
+
21
+ IDENTIFIER = "novelai-vibe-transfer"
22
+ BUNDLE_IDENTIFIER = "novelai-vibe-transfer-bundle"
23
+ VERSION = 1
24
+ MODEL_KEYS = {
25
+ "nai-diffusion-4-5-full": "v4-5full",
26
+ "nai-diffusion-4-5-curated": "v4-5curated",
27
+ "nai-diffusion-4-full": "v4full",
28
+ "nai-diffusion-4-curated-preview": "v4curated",
29
+ }
30
+ DEFAULT_STRENGTH = 0.6
31
+ # Default information extracted: 0.7 for V4.5 Full, 1 otherwise
32
+ _DEFAULT_INFORMATION_EXTRACTED = {"nai-diffusion-4-5-full": 0.7}
33
+ _FILE_SUFFIXES = (".naiv4vibe", ".naiv4vibebundle", ".json")
34
+ # The official client exports Vibes into PNG images under this text chunk, as base64 JSON
35
+ _PNG_KEYWORD = "naidata"
36
+ _ID = re.compile(r"[0-9a-f]{64}")
37
+ _THUMBNAIL = re.compile(r"data:image/[^;]+;base64,")
38
+ # The official client stores a JPEG of this longest side at quality 0.8 with each image Vibe
39
+ _THUMBNAIL_SIDE = 256
40
+ _THUMBNAIL_QUALITY = 80
41
+ # The fields the official export writes, in its order; it drops any others
42
+ _ENTRY_FIELDS = (
43
+ "identifier",
44
+ "version",
45
+ "type",
46
+ "image",
47
+ "id",
48
+ "encodings",
49
+ "name",
50
+ "thumbnail",
51
+ "createdAt",
52
+ "importInfo",
53
+ )
54
+ _PARAMS_FIELDS = ("mask", "information_extracted")
55
+
56
+
57
+ def default_information_extracted(model: str) -> float:
58
+ return _DEFAULT_INFORMATION_EXTRACTED.get(model, 1.0)
59
+
60
+
61
+ @dataclass
62
+ class VibeSource:
63
+ name: str
64
+ image_b64: str | None
65
+ encodings: dict[str, dict[str, dict[str, Any]]]
66
+ strength: float
67
+ information_extracted: float
68
+ # Only carried over from imported files; the official client has no way to draw one
69
+ mask: Any = None
70
+ # As read from a file, so an export keeps its id, name and thumbnail
71
+ entry: dict[str, Any] | None = None
72
+
73
+
74
+ def params_key(information_extracted: float, mask: Any = None) -> str:
75
+ # Parameters sorted by name, unset ones dropped, as the official client hashes them
76
+ params = {"information_extracted": information_extracted, "mask": mask}
77
+ canonical = ",".join(f"{k}:{_js_text(v)}" for k, v in sorted(params.items()) if v is not None)
78
+ return hashlib.sha256(canonical.encode()).hexdigest()
79
+
80
+
81
+ def load(path: Path, strength: float | None, information_extracted: float | None, model: str) -> list[VibeSource]:
82
+ """Load a .naiv4vibe or .naiv4vibebundle, an image carrying one, or a plain image to encode later.
83
+ Unset values come from the file, then the defaults; a bundle applies them to every Vibe."""
84
+ if path.suffix.lower() in _FILE_SUFFIXES:
85
+ try:
86
+ data = values.parse_json(path.read_text(encoding="utf-8"))
87
+ except (OSError, ValueError) as e:
88
+ raise errors.NaiError(errors.BAD_ARGS, f"cannot read Vibe file {path}: {e}") from e
89
+ return _sources(data, path, strength, information_extracted, model)
90
+ embedded = _embedded(path)
91
+ if embedded is not None:
92
+ return _sources(embedded, path, strength, information_extracted, model)
93
+ png = images.to_png(images.open_image(path))
94
+ return [
95
+ _checked(
96
+ VibeSource(
97
+ name=path.stem,
98
+ image_b64=base64.b64encode(png).decode(),
99
+ encodings={},
100
+ strength=DEFAULT_STRENGTH if strength is None else strength,
101
+ information_extracted=default_information_extracted(model)
102
+ if information_extracted is None
103
+ else information_extracted,
104
+ )
105
+ )
106
+ ]
107
+
108
+
109
+ def _embedded(path: Path) -> dict[str, Any] | None:
110
+ try:
111
+ # The official import reads the first, which an export into the image puts right after IHDR
112
+ text = next((t for key, t in png_text_entries(path.read_bytes()) if key == _PNG_KEYWORD), None)
113
+ except OSError as e:
114
+ raise errors.NaiError(errors.BAD_ARGS, f"cannot read image {path}: {e}") from e
115
+ if text is None:
116
+ return None
117
+ try:
118
+ data = values.parse_json(base64.b64decode(text))
119
+ except (binascii.Error, ValueError):
120
+ return None
121
+ if isinstance(data, dict) and data.get("identifier") in (IDENTIFIER, BUNDLE_IDENTIFIER):
122
+ return data
123
+ return None
124
+
125
+
126
+ def _sources(
127
+ data: Any, path: Path, strength: float | None, information_extracted: float | None, model: str
128
+ ) -> list[VibeSource]:
129
+ identifier = data.get("identifier") if isinstance(data, dict) else None
130
+ if identifier == IDENTIFIER:
131
+ return [_source(data, path.stem, strength, information_extracted, model)]
132
+ if identifier == BUNDLE_IDENTIFIER:
133
+ vibes = data.get("vibes")
134
+ if not isinstance(vibes, list) or not vibes or not all(isinstance(v, dict) for v in vibes):
135
+ raise errors.NaiError(errors.BAD_ARGS, f"{path.name} holds no Vibes")
136
+ return [_source(v, f"{path.stem} {i}", strength, information_extracted, model) for i, v in enumerate(vibes, 1)]
137
+ raise errors.NaiError(errors.BAD_ARGS, f"{path.name} is not a Vibe file")
138
+
139
+
140
+ def _source(
141
+ data: dict[str, Any], name: str, strength: float | None, information_extracted: float | None, model: str
142
+ ) -> VibeSource:
143
+ info = data.get("importInfo")
144
+ info = info if isinstance(info, dict) else {}
145
+ name = data.get("name") or name
146
+ mask = info.get("mask")
147
+ if mask is not None and not _is_base64(mask):
148
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} has an invalid mask")
149
+ image = _image(data.get("image"), name)
150
+ encodings = _encodings(data.get("encodings"), name)
151
+ _check_id(data, name, encodings)
152
+ stored_info = _stored(info, "information_extracted", default_information_extracted(model), name)
153
+ # The official client locks the slider of a Vibe without its image, since it cannot be encoded again
154
+ if image is None and information_extracted is not None and information_extracted != stored_info:
155
+ raise errors.NaiError(
156
+ errors.BAD_ARGS,
157
+ f"Vibe {name!r} has no source image, so its information extracted stays at {_js_number(stored_info)}",
158
+ )
159
+ return _checked(
160
+ VibeSource(
161
+ name=str(name),
162
+ image_b64=image,
163
+ encodings=encodings,
164
+ strength=strength if strength is not None else _stored(info, "strength", DEFAULT_STRENGTH, name),
165
+ information_extracted=stored_info if information_extracted is None else information_extracted,
166
+ mask=mask,
167
+ entry=data,
168
+ )
169
+ )
170
+
171
+
172
+ def _check_id(data: dict[str, Any], name: str, encodings: dict[str, dict[str, dict[str, Any]]]) -> None:
173
+ """The official import refuses a Vibe whose id does not match its image, or its first encoding."""
174
+ if data.get("type") not in ("image", "encoding"):
175
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} is neither an image nor an encoding Vibe")
176
+ vibe_id = data.get("id")
177
+ if not isinstance(vibe_id, str) or not _ID.fullmatch(vibe_id):
178
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} has no valid id")
179
+ if data.get("type") == "image" and _sha256(str(data.get("image") or "")) != vibe_id:
180
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r}: its image does not match its id")
181
+ if data.get("type") == "encoding":
182
+ first = next((v for by_model in encodings.values() for v in by_model.values()), None)
183
+ if first is None:
184
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} holds no encoding")
185
+ if _sha256(first.get("encoding") or "") != vibe_id:
186
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r}: its encoding does not match its id")
187
+ thumbnail = data.get("thumbnail")
188
+ if thumbnail and not (isinstance(thumbnail, str) and _THUMBNAIL.match(thumbnail)):
189
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} has an invalid thumbnail")
190
+
191
+
192
+ def from_settings(path: str | Path) -> list[VibeSource]:
193
+ """The Vibes kept in a generated image's settings, as the official import restores them: encodings for the
194
+ model that made the image, with their strengths and information extracted."""
195
+ path = Path(path)
196
+ raw = read_raw(path)
197
+ try:
198
+ settings = values.parse_json(raw["Comment"])
199
+ except (KeyError, ValueError):
200
+ settings = None
201
+ if not isinstance(settings, dict):
202
+ raise errors.NaiError(errors.BAD_ARGS, f"{path.name} has no generation settings")
203
+ encodings = settings.get("reference_image_multiple")
204
+ if not isinstance(encodings, list) or not encodings:
205
+ raise errors.NaiError(errors.BAD_ARGS, f"{path.name} keeps no Vibes in its settings")
206
+ model = model_of(settings, raw.get("Source")) or ""
207
+ key = MODEL_KEYS.get(model)
208
+ if key is None:
209
+ raise errors.NaiError(errors.BAD_ARGS, f"{path.name} was not made with a model that has Vibes")
210
+ out = []
211
+ for i, encoding in enumerate(encodings):
212
+ name = f"{path.stem} {i + 1}"
213
+ if not encoding or not is_encoding(encoding):
214
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} keeps an invalid encoding")
215
+ strength = _listed(settings, "reference_strength_multiple", i, DEFAULT_STRENGTH, name)
216
+ info = _listed(
217
+ settings, "reference_information_extracted_multiple", i, default_information_extracted(model), name
218
+ )
219
+ out.append(_checked(VibeSource(name, None, {key: {"unknown": {"encoding": encoding}}}, strength, info)))
220
+ return out
221
+
222
+
223
+ def _listed(settings: dict[str, Any], key: str, index: int, default: float, name: str) -> float:
224
+ values = settings.get(key)
225
+ value = values[index] if isinstance(values, list) and index < len(values) else None
226
+ return _stored({key: value}, key, default, name)
227
+
228
+
229
+ def _image(value: Any, name: str) -> str | None:
230
+ """The source image in base64, checked on load so a broken file fails before anything is paid for."""
231
+ if value is None or value == "":
232
+ return None
233
+ if not isinstance(value, str):
234
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} holds an image that cannot be read")
235
+ # Line breaks are allowed, as browsers' base64 readers allow them
236
+ value = "".join(value.split())
237
+ try:
238
+ decode.size_of_bytes(base64.b64decode(value, validate=True))
239
+ except decode.BAD_IMAGE as e:
240
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} holds an image that cannot be read") from e
241
+ return value
242
+
243
+
244
+ def check_image(source: VibeSource) -> None:
245
+ """Decode the whole source image before paying to encode it; loading a file checked only its header."""
246
+ if source.image_b64 is None:
247
+ return
248
+ try:
249
+ decode.verify(base64.b64decode(source.image_b64))
250
+ except Image.DecompressionBombError as e:
251
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {source.name!r} holds an image past the pixel limit") from e
252
+ except decode.BAD_IMAGE as e:
253
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {source.name!r} holds a damaged image") from e
254
+
255
+
256
+ def is_encoding(value: Any) -> bool:
257
+ """Text a request can carry as an encoding."""
258
+ return isinstance(value, str) and values.unsendable(value) is None
259
+
260
+
261
+ def _encodings(value: Any, name: str) -> dict[str, dict[str, dict[str, Any]]]:
262
+ """{model key: {parameters key: {encoding, ...}}}; the official import rejects any other shape."""
263
+ if value is None:
264
+ return {}
265
+ well_formed = isinstance(value, dict) and all(
266
+ isinstance(by_model, dict)
267
+ and all(isinstance(v, dict) and is_encoding(v.get("encoding", "")) for v in by_model.values())
268
+ for by_model in value.values()
269
+ )
270
+ if not well_formed:
271
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} has malformed encodings")
272
+ return value
273
+
274
+
275
+ def _stored(info: dict[str, Any], key: str, default: float, name: str) -> float:
276
+ value = info.get(key)
277
+ # A missing or null value takes the default, as in the official import
278
+ if value is None:
279
+ return default
280
+ if not values.is_number(value):
281
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {name!r} stores an invalid {key}: {value!r}")
282
+ return float(value)
283
+
284
+
285
+ def _checked(source: VibeSource) -> VibeSource:
286
+ # The official client lets strength go past its slider, so it only has to be a finite number
287
+ if not math.isfinite(source.strength):
288
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {source.name!r} has an invalid strength: {source.strength}")
289
+ check_range("information extracted", source.information_extracted, models.INFORMATION_EXTRACTED_RANGE)
290
+ return source
291
+
292
+
293
+ def stored_encoding(source: VibeSource, model: str) -> str | None:
294
+ """The encoding the Vibe keeps for these settings; None when its image is to be looked up or encoded."""
295
+ by_model = source.encodings.get(MODEL_KEYS.get(model, ""), {})
296
+ wanted = by_model.get(params_key(source.information_extracted, source.mask))
297
+ if wanted and wanted.get("encoding"):
298
+ return wanted["encoding"]
299
+ if source.image_b64 is None:
300
+ # Without the source image only the stored information-extracted value can be used
301
+ for variant in by_model.values():
302
+ if variant.get("encoding"):
303
+ return variant["encoding"]
304
+ raise errors.NaiError(
305
+ errors.BAD_ARGS, f"Vibe {source.name!r} has no encoding for {model} and no image to re-encode"
306
+ )
307
+ return None
308
+
309
+
310
+ def _is_base64(value: Any) -> bool:
311
+ if not isinstance(value, str) or not value.isascii():
312
+ return False
313
+ try:
314
+ # Line breaks are allowed, as for the image
315
+ base64.b64decode("".join(value.split()), validate=True)
316
+ except (binascii.Error, TypeError, ValueError):
317
+ return False
318
+ return True
319
+
320
+
321
+ def encoding_key(source: VibeSource, model: str) -> str:
322
+ """What one encoding serves: the image, the model, the information extracted and the mask."""
323
+ key = f"{source.image_b64}|{model}|{_js_number(source.information_extracted)}"
324
+ if source.mask is not None:
325
+ key += f"|{_js_text(source.mask)}"
326
+ return key
327
+
328
+
329
+ def _js_number(value: float) -> str:
330
+ return str(int(value)) if float(value).is_integer() else repr(float(value))
331
+
332
+
333
+ def _js_text(value: Any) -> str:
334
+ if isinstance(value, bool):
335
+ return "true" if value else "false"
336
+ if isinstance(value, int | float):
337
+ return _js_number(value)
338
+ if isinstance(value, dict | list):
339
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
340
+ return str(value)
341
+
342
+
343
+ @dataclass(frozen=True)
344
+ class Encode:
345
+ """One encoding to pay for, and the positions of the Vibes it serves."""
346
+
347
+ source: VibeSource
348
+ positions: tuple[int, ...]
349
+
350
+
351
+ def encodes(pending: list[tuple[int, VibeSource]], model: str) -> list[Encode]:
352
+ """The Vibes still to encode, one paid encoding for each set of Vibes that would get the same one."""
353
+ groups: dict[str, list[tuple[int, VibeSource]]] = {}
354
+ for i, source in pending:
355
+ groups.setdefault(encoding_key(source, model), []).append((i, source))
356
+ return [Encode(group[0][1], tuple(i for i, _ in group)) for group in groups.values()]
357
+
358
+
359
+ def thumbnail(png: bytes) -> str:
360
+ """The image scaled to 256 on its longer side and saved as a JPEG data URL, transparency on black, as the
361
+ official client keeps it with an image Vibe."""
362
+ with Image.open(io.BytesIO(png)) as img:
363
+ img.load()
364
+ scale = _THUMBNAIL_SIDE / max(img.size)
365
+ small = resample.lanczos(img.convert("RGBA"), math.floor(img.width * scale), math.floor(img.height * scale))
366
+ out = io.BytesIO()
367
+ resample.fill_background(small, (0, 0, 0)).save(out, "JPEG", quality=_THUMBNAIL_QUALITY)
368
+ return "data:image/jpeg;base64," + base64.b64encode(out.getvalue()).decode()
369
+
370
+
371
+ def export(source: VibeSource, model: str, encoding: str | None, without_image: bool) -> dict[str, Any]:
372
+ """One Vibe as the official export writes it: the stored entry, any new encoding, and this use's settings
373
+ as importInfo. without_image keeps only the encoding for this model and settings, as the official export
374
+ can."""
375
+ if source.entry is not None:
376
+ data = dict(source.entry)
377
+ else:
378
+ image_b64 = source.image_b64 or ""
379
+ data = {
380
+ "identifier": IDENTIFIER,
381
+ "version": VERSION,
382
+ "type": "image",
383
+ "image": image_b64,
384
+ "id": _sha256(image_b64),
385
+ "encodings": {},
386
+ "name": source.name,
387
+ "thumbnail": thumbnail(base64.b64decode(image_b64)),
388
+ "createdAt": int(time.time() * 1000),
389
+ }
390
+ key, params = MODEL_KEYS[model], params_key(source.information_extracted, source.mask)
391
+ encodings = {m: dict(variants) for m, variants in (data.get("encodings") or {}).items()}
392
+ if encoding is not None and data.get("type") == "image":
393
+ settings = {"information_extracted": source.information_extracted}
394
+ if source.mask is not None:
395
+ settings["mask"] = source.mask
396
+ encodings.setdefault(key, {})[params] = {"encoding": encoding, "params": settings}
397
+ data["encodings"] = encodings
398
+ info = {"model": model, "information_extracted": source.information_extracted, "strength": source.strength}
399
+ if source.mask is not None:
400
+ info["mask"] = source.mask
401
+ data["importInfo"] = info
402
+ if without_image and data.get("type") == "image":
403
+ kept = encodings.get(key, {}).get(params)
404
+ if not kept or not kept.get("encoding"):
405
+ raise errors.NaiError(errors.BAD_ARGS, f"Vibe {source.name!r} has no encoding for {model} to keep")
406
+ data = {**data, "id": _sha256(kept["encoding"]), "type": "encoding", "encodings": {key: {"unknown": kept}}}
407
+ data.pop("image", None)
408
+ data.pop("thumbnail", None)
409
+ return _official_fields(data)
410
+
411
+
412
+ def _sha256(text: str) -> str:
413
+ return hashlib.sha256(text.encode()).hexdigest()
414
+
415
+
416
+ def _official_fields(data: dict[str, Any]) -> dict[str, Any]:
417
+ out = {k: data[k] for k in _ENTRY_FIELDS if data.get(k) is not None}
418
+ out["encodings"] = {
419
+ model: {params: _variant(v) for params, v in variants.items()} for model, variants in out["encodings"].items()
420
+ }
421
+ return out
422
+
423
+
424
+ def _variant(value: dict[str, Any]) -> dict[str, Any]:
425
+ out: dict[str, Any] = {"encoding": value.get("encoding")}
426
+ params = value.get("params")
427
+ if isinstance(params, dict):
428
+ out["params"] = {k: params[k] for k in _PARAMS_FIELDS if params.get(k) is not None}
429
+ return out
430
+
431
+
432
+ def bundle(entries: list[dict[str, Any]]) -> dict[str, Any]:
433
+ return {"identifier": BUNDLE_IDENTIFIER, "version": VERSION, "vibes": entries}
434
+
435
+
436
+ def dumps(data: dict[str, Any]) -> str:
437
+ """Indented by two spaces, as the official export writes it."""
438
+ return values.to_json(_js_values(data), indent=2)
439
+
440
+
441
+ def _js_values(value: Any) -> Any:
442
+ # JSON.stringify writes 1.0 as 1
443
+ if isinstance(value, float) and value.is_integer():
444
+ return int(value)
445
+ if isinstance(value, dict):
446
+ return {k: _js_values(v) for k, v in value.items()}
447
+ if isinstance(value, list):
448
+ return [_js_values(v) for v in value]
449
+ return value
450
+
451
+
452
+ def embed(png: bytes, text: str) -> bytes:
453
+ """The PNG with text in an uncompressed naidata iTXt chunk right after IHDR, as base64 of its UTF-8, the way
454
+ the official export writes a bundle into an image. Bundles it held before are dropped."""
455
+ chunk = decode.itxt(_PNG_KEYWORD, base64.b64encode(text.encode()).decode("ascii"))
456
+ chunks = list(decode.png_chunks(png))
457
+ if not chunks or chunks[0][0] != b"IHDR":
458
+ raise errors.NaiError(errors.BAD_ARGS, "the image to hold the Vibes is not a PNG")
459
+ kept = [png[start:end] for kind, data, start, end in chunks[1:] if not _holds_bundle(kind, data)]
460
+ return png[: chunks[0][3]] + chunk + b"".join(kept)
461
+
462
+
463
+ def _holds_bundle(kind: bytes, data: bytes) -> bool:
464
+ return kind in decode.TEXT_CHUNKS and data.split(b"\0", 1)[0] == _PNG_KEYWORD.encode("latin1")
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: nai-cli
3
+ Version: 0.1.0
4
+ Summary: Command-line client for NovelAI image generation
5
+ Project-URL: Homepage, https://github.com/obzawa/nai-cli
6
+ Project-URL: Repository, https://github.com/obzawa/nai-cli
7
+ Project-URL: Documentation, https://github.com/obzawa/nai-cli/blob/main/docs/usage.md
8
+ Project-URL: Changelog, https://github.com/obzawa/nai-cli/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/obzawa/nai-cli/issues
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY_NOTICES.md
13
+ Keywords: cli,image-generation,novelai
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: End Users/Desktop
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Multimedia :: Graphics
25
+ Requires-Python: >=3.11
26
+ Requires-Dist: argon2-cffi>=23.1
27
+ Requires-Dist: httpx>=0.27
28
+ Requires-Dist: numpy>=1.26
29
+ Requires-Dist: pillow>=10.1
30
+ Requires-Dist: regex>=2024.11.6
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: ruff>=0.8; extra == 'dev'
34
+ Provides-Extra: local
35
+ Requires-Dist: onnxruntime>=1.17; extra == 'local'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # nai-cli
39
+
40
+ English | [中文](https://github.com/obzawa/nai-cli/blob/v0.1.0/README.zh.md)
41
+
42
+ nai-cli is an unofficial command-line client for [NovelAI](https://novelai.net) image generation. It covers text to image, image to image, inpainting, Enhance, upscaling, the Director tools and Vibes on V5, V4.5 and V4, and reads the settings stored in images so they can be generated again.
43
+
44
+ It builds requests by the same rules as the official web client, so the same settings and seed produce the same image; the [parity notes](https://github.com/obzawa/nai-cli/blob/v0.1.0/docs/official-parity.md#intentional-differences) list the exceptions. Every command prints JSON, one object or one line per job, which makes it easy to call from scripts and other programs.
45
+
46
+ Documentation: [usage guide](https://github.com/obzawa/nai-cli/blob/v0.1.0/docs/usage.md), [official client parity](https://github.com/obzawa/nai-cli/blob/v0.1.0/docs/official-parity.md), [compatibility](https://github.com/obzawa/nai-cli/blob/v0.1.0/docs/usage.md#compatibility)
47
+
48
+ ## Install
49
+
50
+ Python 3.11 or later is required:
51
+
52
+ ```sh
53
+ pipx install nai-cli
54
+ ```
55
+
56
+ This installs the `nai` command in an environment of its own. `uv tool install nai-cli` and `pip install nai-cli` work as well. Reading tags from images and masking objects run on your computer and need `pipx install "nai-cli[local]"`.
57
+
58
+ ## Configure
59
+
60
+ Create a persistent API token in NovelAI under Account Settings (it starts with `pst-`), then create a config file:
61
+
62
+ ```sh
63
+ nai config init
64
+ ```
65
+
66
+ The command prints the path of the new file. Put the token in its `novelai_token` field, or set the `NOVELAI_TOKEN` environment variable instead. Once the token works, `nai account` shows your balance.
67
+
68
+ ## Usage
69
+
70
+ ```sh
71
+ nai gen --prompt "1girl, rooftop, night" --dry-run
72
+ nai gen --prompt @prompt.txt --size landscape
73
+ nai inpaint --image a.png --region ellipse:0.62,0.40,0.80,0.58 --prompt "1girl, rooftop, night, open hand" --preview
74
+ nai enhance --image a.png
75
+ nai meta a.png
76
+ nai batch jobs.jsonl --dry-run
77
+ ```
78
+
79
+ `--dry-run` builds and prices the request without sending anything paid. The `prompt` and `negative` fields of the output hold the final text, including the quality tags and UC preset added automatically; without `--dry-run`, the saved files are listed in `images`. `@prompt.txt` reads the prompt from a file. `inpaint` repaints an area given in fractions of the image and composites the result back onto it, and `--preview` saves an image marking that area before anything is sent. `enhance` upscales and refines an image with the settings stored in it, and `meta` reads those settings so that `nai gen` can reproduce the image. `batch` runs a list of commands, one per line, and prints a JSON line for each, so other programs can queue work and resume it after a failure.
80
+
81
+ `nai --help` lists all commands, and `nai COMMAND --help` shows their options. The [usage guide](https://github.com/obzawa/nai-cli/blob/v0.1.0/docs/usage.md) covers each command, the output format and the error codes.
82
+
83
+ ## Agent skill
84
+
85
+ nai-cli includes a skill in the [Agent Skills](https://agentskills.io) format that teaches AI agents to use it: dry-running before spending Anlas, asking before exceeding the spending limit, recovering from errors and repainting part of an image. Install it with:
86
+
87
+ ```sh
88
+ npx skills add obzawa/nai-cli
89
+ ```
90
+
91
+ This installs it for the current project; add `-g` to install it for all projects. The skill itself is in [skills/nai-cli](https://github.com/obzawa/nai-cli/blob/v0.1.0/skills/nai-cli).
92
+
93
+ ## Development
94
+
95
+ See [CONTRIBUTING.md](https://github.com/obzawa/nai-cli/blob/v0.1.0/CONTRIBUTING.md) for setting up, the checks a change must pass and how to report bugs; coding agents follow [AGENTS.md](https://github.com/obzawa/nai-cli/blob/v0.1.0/AGENTS.md).
96
+
97
+ ## Acknowledgements
98
+
99
+ Thanks to [NovelAI](https://novelai.net) for the models and the service. Many of the defaults and conveniences follow [NAI Launcher](https://github.com/Aaalice233/Aaalice_NAI_Launcher), and image resizing is ported from [Pica](https://github.com/nodeca/pica).
100
+
101
+ ## License
102
+
103
+ [MIT](https://github.com/obzawa/nai-cli/blob/v0.1.0/LICENSE)
104
+
105
+ Third-party code and its licenses are listed in [THIRD_PARTY_NOTICES.md](https://github.com/obzawa/nai-cli/blob/v0.1.0/THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,75 @@
1
+ nai_cli/__init__.py,sha256=VjG-CE25zaxLg2fmAgorkrscxu9l8yqjQGn-4szr7QM,86
2
+ nai_cli/__main__.py,sha256=svawZjUBxT5YF8lPUxdkCSwiJPADfKMBpk9bdKvCzdE,103
3
+ nai_cli/api.py,sha256=YS_YHNBz-PQyuD4-xALmKyYl3O1T1jAvyEJJl6ChjOA,22325
4
+ nai_cli/auth.py,sha256=zo8UxWFsis4avSGuSss10ioZ_9FfDlkxx8BIx5vih9Q,9810
5
+ nai_cli/batch.py,sha256=QprVtC3gyZVJxH99G3HMndqq9810Bbakj4FEY2Es-Yg,4443
6
+ nai_cli/caches.py,sha256=3G8q-Dl-2VKHYWCP9hFZT519im-Ku_MFlxNniLiKdI0,2083
7
+ nai_cli/charge.py,sha256=QS8ryBiDcfVy62NxTyKpk-kIcATRGYf0HepAeMTfcWs,9548
8
+ nai_cli/cli.py,sha256=DyvkxeczLQcpLQZXKWjD28LZAusj14hYHbY64zLXk1s,4326
9
+ nai_cli/comfyui.py,sha256=yRW5hQYcIBzg9y-Bqip3V0FrvyAGlBHlod6geVJdu0k,6862
10
+ nai_cli/config.py,sha256=4DWbUzjv9Ri-A7UT83rlJwHBsnCP2WaoM3rWW4DFRdI,14186
11
+ nai_cli/cost.py,sha256=j9ROSA-nbTLREt5aPLWDv91HLkTp6E18HoEJj_eINfI,4231
12
+ nai_cli/decode.py,sha256=qAvd7Rhrd_9SzfGaE0XFf6XgF6AKe0Ie0AL2odtmmjM,3236
13
+ nai_cli/enhance.py,sha256=FDrFsLQtfjhp_3l6Pp0-lJXegSXXXhQlUxX-cBUqpfk,5021
14
+ nai_cli/errors.py,sha256=cbG0G0FWzHDRRL2NbNVDM7gpON1xQX9tpbNNMibFlU0,1244
15
+ nai_cli/fs.py,sha256=1MDVhY_KeonegdUrTnH3t8JxsXUngLQtodFw8q1E2Pc,6786
16
+ nai_cli/grid.py,sha256=8lPZ8kVgQKoVaFckVCwRauvWYkebcqYkriL3J7sZTgw,9191
17
+ nai_cli/images.py,sha256=ztdH9iJIZd11J_ythpKceavKKITwGj7dNIgjL4tDYiA,10505
18
+ nai_cli/import_image.py,sha256=asGMdT8FSaf-6MbxblcYcT9Tf85aImMUI0Ri8fBvDgM,10317
19
+ nai_cli/inpaint.py,sha256=R2qrnZ9eeS2tzthJSxgXydfNeXCtg3fTlYfHP4FVjzw,20294
20
+ nai_cli/ledger.py,sha256=gtjGWpB7nNpgREq1LYkER_9RI3ipVkagsKpetRPkEio,4762
21
+ nai_cli/lint.py,sha256=DL8_Uj9UBKlj6Mt84tbHI_gciZc_hTwH6LeOe7FXfHs,11129
22
+ nai_cli/local_models.py,sha256=JNPjShheZtm9Kd-aoZWm7dyMBvtpKVkdzTwsj_4IDT8,4541
23
+ nai_cli/meta.py,sha256=3K42WPgRaHogAeJ2PzcE1jGeIDjmGR3NseLpbiUeBTI,25270
24
+ nai_cli/models.py,sha256=0xcy49r2cgVKu64Y4BNJOnBXtSEJf8t4Dpj18O59yBY,10269
25
+ nai_cli/naming.py,sha256=U5cBrMwD6WtmUEgihnoiqzIjHUe4TTZtRP92h0BbsSk,15549
26
+ nai_cli/parser.py,sha256=0JKBWMMxzLG2_Bjqf3D3JqlZC5FR9Be3T5wuBhx0ckc,27827
27
+ nai_cli/pixel_snap.py,sha256=nETGYK_jnnJ9fZtekl3HIhIPenlefvNEe7fycB69RhY,21940
28
+ nai_cli/presets.py,sha256=3nmS-G-wbXuTpvKfaKIjUw1b43nDE_N2xeEw0kcZhyE,10940
29
+ nai_cli/prompt.py,sha256=K7TX7e7htfubaGgsL_netDcYCGF_H3vGyqHnn8SfvPs,17611
30
+ nai_cli/random_prompt.py,sha256=pTU4MANUGFtK2u8riZ_srlcpIkOmjr-QYACD6xhgq_M,11782
31
+ nai_cli/request.py,sha256=A3lNvsDBHyRIASV8m402Bi7bV8nB33jCGzWZG89uO_U,22794
32
+ nai_cli/rerun.py,sha256=LpG1MNEr6tO4hs1yyVSmWogJ-1IxM9FKN3d1oQlEOGo,8260
33
+ nai_cli/resample.py,sha256=F8DyMWf9K0ylJdFeDMuEapl3M5nIe1v4cHt-uSLU_jI,5740
34
+ nai_cli/sam.py,sha256=lWDL5EEa0wpYR7hFE5tWo59IYcaq4cpaddreu6s2LKc,3019
35
+ nai_cli/share.py,sha256=37uucDqCjFF9jBwCDUXECts6w_nCsJceDorrMLYEMNk,16778
36
+ nai_cli/sheet.py,sha256=3N2rWadF0dQcBPgm0Eb_Q2pVEFoCVaxacO-Pq1znK1A,3382
37
+ nai_cli/tagger.py,sha256=cGgCH_7xMRQ3PEP5WC6Q6KJvV_Ovu7pUiPT_TB0V0xI,18689
38
+ nai_cli/tags.py,sha256=XUcq2kQ0VNnKqcFO1g9_SLeFy49sM6vR4GAKGxCjqYI,1410
39
+ nai_cli/tidy.py,sha256=m7d_no12CbgMcK8fBPY5f9f3opkfP2LI6hHAi2LDeI0,6332
40
+ nai_cli/tokenizer.py,sha256=WfSdMBB0MWsW1eVs0i6lNPtBRdBNbWBFessS0OUcNrA,12289
41
+ nai_cli/values.py,sha256=CDaNLYIxHI4Q0hT9KNKb17DMywpCzbWMKKAWm3C7NpU,4181
42
+ nai_cli/vibe.py,sha256=RK8vhWzxzQY9UqONyhhEerVS7AjtYp7D-ZLMaKt-0Kg,20148
43
+ nai_cli/commands/__init__.py,sha256=fEEMjdQhAryRnfGJv6tYyS826qjC_zyoIlHPAkeEpBU,1790
44
+ nai_cli/commands/account.py,sha256=gV74gOWR0T9j5httjC1A9BTHO5sr3jLlLtteK8OFEwA,3437
45
+ nai_cli/commands/batch.py,sha256=pPzMwtcxRslkjkvnDZtDmye5vbz4qQ6hiofPcdjRsfg,5419
46
+ nai_cli/commands/config.py,sha256=HkCWQITKdOPzoh5TyyqbM8NmG-2LJ9Y0gv0Cqp-k1fI,2040
47
+ nai_cli/commands/context.py,sha256=Cz0X4eVE4JkHuD77AtNrU9PWSWMzew0twdr5hITLH08,7988
48
+ nai_cli/commands/copies.py,sha256=h7BYrgiXMZenkZATzMYUsOkt_Opsoj24BC8BYONtxrY,5886
49
+ nai_cli/commands/cost.py,sha256=fm1Sl4cgNNRLoP_xjzOraJtxus2xVgIglnFNL20_7Yw,2798
50
+ nai_cli/commands/generate.py,sha256=Rfpr_efrIjLNea7-omkWAitYN3e4rndrN_m12J9Hcj4,10308
51
+ nai_cli/commands/generation.py,sha256=v5Fbo2ZTWk_vpM_5rnm-GyKpwacVpXw20CZZRaBcw8c,20740
52
+ nai_cli/commands/grid.py,sha256=CmCvU5iTxOv0oLTD1kPQg3l-8wInUj2k2bLW9RwH1Vw,3927
53
+ nai_cli/commands/image_tools.py,sha256=Yy7YB73Dx_4SzplAFYFcbbm9rzewXmOrfW9WgyUSOlE,9714
54
+ nai_cli/commands/interrogate.py,sha256=sy8M42BSUX6c9KnluFoIiNYt2GUUzroFNhXP64qFEHQ,3360
55
+ nai_cli/commands/lint.py,sha256=cn_FY8jKM3LlxCBu-ZKSBaISx-LwgZ2eovjZSoqcGy4,723
56
+ nai_cli/commands/local.py,sha256=e-qklPXYCGMHKfcqiULxa6yMTuNZKSmIjrmAebF-688,2465
57
+ nai_cli/commands/meta.py,sha256=xzjU1bXyFW2g7nLKY9AwPKrcaO7wPDTdQpsNkvj3yIM,4015
58
+ nai_cli/commands/models.py,sha256=DMLHYCuwwG6Yko3vbWBPH9e_wEU-TiUQQw1iKA_CTpk,2188
59
+ nai_cli/commands/output.py,sha256=YpFZb5FtpPrsP_iUAjFbms2-8E9-wbJZwcHB91eeyTM,6437
60
+ nai_cli/commands/redact.py,sha256=YK5zWYTNWG-X6VeFaX7mRZFJVl9V-mMUgLf4mAg52KM,1739
61
+ nai_cli/commands/references.py,sha256=0lDjFPjPzT8gciQJ31_3hvc8a-pJMoF-DQCi5G8e6gs,3093
62
+ nai_cli/commands/spec.py,sha256=3mOdqRbtIbKgJ6uNaUIkbxDhMqhgGpXCyer54zZ3SQ0,9748
63
+ nai_cli/commands/stats.py,sha256=3xkReAWCswCnqGVfwgEsDlwmvhKYcB0dMN0NF1FGzZc,1784
64
+ nai_cli/commands/strip.py,sha256=dnTp_Y1LM_GMhhgjSD40quvVmqPRzITYXarNO-s672E,450
65
+ nai_cli/commands/tags.py,sha256=SXwGydAHYaa8RWflUjNlUZUrBpvZZFsplkw_p275eAg,1077
66
+ nai_cli/commands/texts.py,sha256=DQObL-P75hQgf2MGP19uXYfK1OVcY4q5Zxe_1WjJodU,3043
67
+ nai_cli/commands/vibe.py,sha256=-BTNtzGrRRCtl2QXXmeWaS_v45A0J2lotMq-3wI2kYI,6520
68
+ nai_cli/commands/watermark.py,sha256=1f-q1smaeHkdtiKNAoHDURLEmn_KcFMCCDRwCGNDvWU,2643
69
+ nai_cli/data/random_prompt.json,sha256=-d12QDvMltIdkY4cZaEkgPLBLEtdt3lL-AXyt2DSwmQ,100765
70
+ nai_cli-0.1.0.dist-info/METADATA,sha256=0aWJBVEN86j3Ox_7woUVdqGbrP3i_72z78pIJ5h2RAI,5768
71
+ nai_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
72
+ nai_cli-0.1.0.dist-info/entry_points.txt,sha256=x5b9mPtVpPKzmfG9JmCPmKHahkY075GNFWUr437Zg5I,41
73
+ nai_cli-0.1.0.dist-info/licenses/LICENSE,sha256=uq16MZTt2VGCfgecl6590eCbL9AsatB3c6bQ89lJk_k,1077
74
+ nai_cli-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=2xM00Xr0bz2TQpCjQJOExdiNIYrRi5LF7IhrX2VePfM,3303
75
+ nai_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nai = nai_cli.cli:main