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.
- nai_cli/__init__.py +3 -0
- nai_cli/__main__.py +5 -0
- nai_cli/api.py +529 -0
- nai_cli/auth.py +240 -0
- nai_cli/batch.py +126 -0
- nai_cli/caches.py +56 -0
- nai_cli/charge.py +231 -0
- nai_cli/cli.py +110 -0
- nai_cli/comfyui.py +194 -0
- nai_cli/commands/__init__.py +61 -0
- nai_cli/commands/account.py +79 -0
- nai_cli/commands/batch.py +142 -0
- nai_cli/commands/config.py +57 -0
- nai_cli/commands/context.py +201 -0
- nai_cli/commands/copies.py +138 -0
- nai_cli/commands/cost.py +70 -0
- nai_cli/commands/generate.py +257 -0
- nai_cli/commands/generation.py +550 -0
- nai_cli/commands/grid.py +99 -0
- nai_cli/commands/image_tools.py +248 -0
- nai_cli/commands/interrogate.py +77 -0
- nai_cli/commands/lint.py +24 -0
- nai_cli/commands/local.py +62 -0
- nai_cli/commands/meta.py +102 -0
- nai_cli/commands/models.py +62 -0
- nai_cli/commands/output.py +165 -0
- nai_cli/commands/redact.py +48 -0
- nai_cli/commands/references.py +87 -0
- nai_cli/commands/spec.py +245 -0
- nai_cli/commands/stats.py +54 -0
- nai_cli/commands/strip.py +15 -0
- nai_cli/commands/tags.py +32 -0
- nai_cli/commands/texts.py +71 -0
- nai_cli/commands/vibe.py +151 -0
- nai_cli/commands/watermark.py +70 -0
- nai_cli/config.py +369 -0
- nai_cli/cost.py +114 -0
- nai_cli/data/random_prompt.json +2536 -0
- nai_cli/decode.py +87 -0
- nai_cli/enhance.py +137 -0
- nai_cli/errors.py +40 -0
- nai_cli/fs.py +209 -0
- nai_cli/grid.py +244 -0
- nai_cli/images.py +250 -0
- nai_cli/import_image.py +235 -0
- nai_cli/inpaint.py +476 -0
- nai_cli/ledger.py +146 -0
- nai_cli/lint.py +302 -0
- nai_cli/local_models.py +135 -0
- nai_cli/meta.py +606 -0
- nai_cli/models.py +308 -0
- nai_cli/naming.py +426 -0
- nai_cli/parser.py +611 -0
- nai_cli/pixel_snap.py +525 -0
- nai_cli/presets.py +276 -0
- nai_cli/prompt.py +457 -0
- nai_cli/random_prompt.py +285 -0
- nai_cli/request.py +621 -0
- nai_cli/rerun.py +177 -0
- nai_cli/resample.py +133 -0
- nai_cli/sam.py +63 -0
- nai_cli/share.py +392 -0
- nai_cli/sheet.py +86 -0
- nai_cli/tagger.py +464 -0
- nai_cli/tags.py +44 -0
- nai_cli/tidy.py +176 -0
- nai_cli/tokenizer.py +313 -0
- nai_cli/values.py +114 -0
- nai_cli/vibe.py +464 -0
- nai_cli-0.1.0.dist-info/METADATA +105 -0
- nai_cli-0.1.0.dist-info/RECORD +75 -0
- nai_cli-0.1.0.dist-info/WHEEL +4 -0
- nai_cli-0.1.0.dist-info/entry_points.txt +2 -0
- nai_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- nai_cli-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +56 -0
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
"""Settings of the generation commands, resolved once from options, an imported image and the config."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from nai_cli import (
|
|
10
|
+
comfyui,
|
|
11
|
+
config,
|
|
12
|
+
enhance,
|
|
13
|
+
errors,
|
|
14
|
+
images,
|
|
15
|
+
import_image,
|
|
16
|
+
inpaint,
|
|
17
|
+
meta,
|
|
18
|
+
models,
|
|
19
|
+
presets,
|
|
20
|
+
random_prompt,
|
|
21
|
+
request,
|
|
22
|
+
tidy,
|
|
23
|
+
vibe,
|
|
24
|
+
)
|
|
25
|
+
from nai_cli.commands import output, texts
|
|
26
|
+
from nai_cli.commands.context import Context
|
|
27
|
+
from nai_cli.commands.references import PreciseRef, VibeRef, precise_ref, vibe_ref
|
|
28
|
+
|
|
29
|
+
ACTIONS = {
|
|
30
|
+
"gen": "generate",
|
|
31
|
+
"lint": "generate",
|
|
32
|
+
"i2i": "img2img",
|
|
33
|
+
"enhance": "img2img",
|
|
34
|
+
"variations": "img2img",
|
|
35
|
+
"inpaint": "infill",
|
|
36
|
+
}
|
|
37
|
+
# They start from the settings of the image they work on
|
|
38
|
+
FROM_IMAGE = ("enhance", "variations")
|
|
39
|
+
_TEXT_OPTIONS = ("prompt", "neg", "char", "char_neg")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Origin(Enum):
|
|
43
|
+
TYPED = "typed"
|
|
44
|
+
# Kept as stored: tidied only by switches given for this run, never by the config, and without fixed tags
|
|
45
|
+
IMAGE = "image"
|
|
46
|
+
# Filled in for the user, as the official client fills a new character's box; kept like IMAGE
|
|
47
|
+
MODEL = "model"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Text:
|
|
52
|
+
value: str
|
|
53
|
+
origin: Origin = Origin.TYPED
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class CharacterText:
|
|
58
|
+
prompt: Text
|
|
59
|
+
negative: Text
|
|
60
|
+
position: tuple[float, float] | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Tidy:
|
|
65
|
+
convert_sd_weights: bool = False
|
|
66
|
+
format_prompt: bool = False
|
|
67
|
+
underscores: bool = False
|
|
68
|
+
space_numeric_close: bool = False
|
|
69
|
+
|
|
70
|
+
def apply(self, text: str) -> str:
|
|
71
|
+
if self.convert_sd_weights:
|
|
72
|
+
text = tidy.convert_sd_weights(text)
|
|
73
|
+
if self.format_prompt:
|
|
74
|
+
text = tidy.format_prompt(text, self.underscores)
|
|
75
|
+
return tidy.space_numeric_closings(text) if self.space_numeric_close else text
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class Fixed:
|
|
80
|
+
"""Tags joined around a text typed for this run: (prefix, suffix)."""
|
|
81
|
+
|
|
82
|
+
prompt: tuple[str, str] = ("", "")
|
|
83
|
+
negative: tuple[str, str] = ("", "")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class InpaintArea:
|
|
88
|
+
mask: Path | None
|
|
89
|
+
regions: tuple[str, ...]
|
|
90
|
+
grow: int
|
|
91
|
+
expand: str | None
|
|
92
|
+
focus: bool | None
|
|
93
|
+
focus_padding: int
|
|
94
|
+
strength: float
|
|
95
|
+
preview: bool
|
|
96
|
+
keep_raw: bool
|
|
97
|
+
# Where object regions find the SAM model
|
|
98
|
+
sam_dir: Path
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Blank:
|
|
103
|
+
size: tuple[int, int]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True)
|
|
107
|
+
class FromImage:
|
|
108
|
+
image: Path
|
|
109
|
+
# None sizes the request as the official client sizes an imported image
|
|
110
|
+
size: tuple[int, int] | None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True)
|
|
114
|
+
class Enhanced:
|
|
115
|
+
image: Path
|
|
116
|
+
plan: enhance.Plan
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass(frozen=True)
|
|
120
|
+
class Repaint:
|
|
121
|
+
image: Path
|
|
122
|
+
# Without focus; None lets the area decide
|
|
123
|
+
size: tuple[int, int] | None
|
|
124
|
+
area: InpaintArea
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
Canvas = Blank | FromImage | Enhanced | Repaint
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True)
|
|
131
|
+
class GenSettings:
|
|
132
|
+
command: str
|
|
133
|
+
action: str
|
|
134
|
+
model: models.Model
|
|
135
|
+
prompt: Text
|
|
136
|
+
negative: Text
|
|
137
|
+
characters: tuple[CharacterText, ...]
|
|
138
|
+
use_coords: bool
|
|
139
|
+
tidy: dict[Origin, Tidy]
|
|
140
|
+
fixed: Fixed | None
|
|
141
|
+
canvas: Canvas
|
|
142
|
+
# The config's size, which sizes imported images as the official client's current size does
|
|
143
|
+
current_size: tuple[int, int]
|
|
144
|
+
steps: int | None
|
|
145
|
+
cfg: float | None
|
|
146
|
+
sampler: str
|
|
147
|
+
noise_schedule: str
|
|
148
|
+
cfg_rescale: float
|
|
149
|
+
seed: int | None
|
|
150
|
+
n: int | None
|
|
151
|
+
quality: str
|
|
152
|
+
uc_preset: str
|
|
153
|
+
negative_verbatim: bool
|
|
154
|
+
official_nsfw: bool
|
|
155
|
+
auto_text: bool
|
|
156
|
+
normalize_vibes: bool
|
|
157
|
+
transparent: bool
|
|
158
|
+
premultiplied_alpha: bool
|
|
159
|
+
furry: bool
|
|
160
|
+
variety: bool
|
|
161
|
+
legacy_uc: bool
|
|
162
|
+
strength: float
|
|
163
|
+
noise: float
|
|
164
|
+
# Vibes the image's settings keep come first, as the official import puts them in the list
|
|
165
|
+
stored_vibes: tuple[vibe.VibeSource, ...]
|
|
166
|
+
vibes: tuple[VibeRef, ...]
|
|
167
|
+
references: tuple[PreciseRef, ...]
|
|
168
|
+
# The draws of the source image's ||a|b|| groups, which the official client sends again
|
|
169
|
+
drawn: meta.Drawn | None
|
|
170
|
+
output: output.Output
|
|
171
|
+
dry_run: bool
|
|
172
|
+
yes: bool
|
|
173
|
+
show_body: bool
|
|
174
|
+
warnings: tuple[str, ...]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def resolve(opts: dict[str, Any], ctx: Context, command: str) -> GenSettings:
|
|
178
|
+
cfg = ctx.config
|
|
179
|
+
d = cfg.defaults
|
|
180
|
+
if command == "enhance" and opts.get("size"):
|
|
181
|
+
raise errors.NaiError(errors.BAD_ARGS, "Enhance sizes the request with --scale; --size is not allowed")
|
|
182
|
+
typed = texts.read_typed(opts, _TEXT_OPTIONS, ctx)
|
|
183
|
+
chosen = models.resolve(opts["model"]) if opts.get("model") else None
|
|
184
|
+
default = models.resolve(d.get("model"))
|
|
185
|
+
|
|
186
|
+
def configured(model: models.Model) -> models.Model:
|
|
187
|
+
picked = models.with_effort(model, opts.get("effort"), d.get("effort"))
|
|
188
|
+
return models.with_hidden_options(picked, bool(d.get("v5_hidden_options")))
|
|
189
|
+
|
|
190
|
+
imported = _imported(opts, command, chosen, default, configured)
|
|
191
|
+
if command in FROM_IMAGE and imported is None and not typed["prompt"] and not opts.get("random_prompt"):
|
|
192
|
+
raise errors.NaiError(errors.NO_METADATA, "the image has no generation settings; describe it with --prompt")
|
|
193
|
+
got = imported or import_image.Imported(configured(chosen or default))
|
|
194
|
+
model = got.model
|
|
195
|
+
warnings = list(got.warnings)
|
|
196
|
+
written = _random_prompt(opts, typed) or _comfyui(opts, d, typed, model)
|
|
197
|
+
characters, use_coords = (
|
|
198
|
+
(written.characters, written.use_coords)
|
|
199
|
+
if written is not None
|
|
200
|
+
else _characters(typed, opts.get("char_pos"), got, model)
|
|
201
|
+
)
|
|
202
|
+
sampler = models.resolve_sampler(_first(opts.get("sampler"), got.sampler, d.get("sampler"), "k_euler_ancestral"))
|
|
203
|
+
canvas = _canvas(opts, got, cfg, command, model, warnings)
|
|
204
|
+
premultiplied = _first(
|
|
205
|
+
opts.get("premultiplied_alpha"), got.premultiplied_alpha, d.get("premultiplied_alpha"), False
|
|
206
|
+
)
|
|
207
|
+
if opts.get("premultiplied_alpha") and not models.for_action(model, ACTIONS[command]).transparent:
|
|
208
|
+
warnings.append(f"{model.name} makes no transparent images, so --premultiplied-alpha has no effect")
|
|
209
|
+
strength, noise = _image_strength(opts, command, canvas)
|
|
210
|
+
return GenSettings(
|
|
211
|
+
command=command,
|
|
212
|
+
action=ACTIONS[command],
|
|
213
|
+
model=model,
|
|
214
|
+
prompt=written.prompt if written is not None else _text(typed["prompt"], got.prompt),
|
|
215
|
+
negative=_text(typed["neg"], got.negative),
|
|
216
|
+
characters=characters,
|
|
217
|
+
use_coords=use_coords,
|
|
218
|
+
tidy=_tidy(opts, d),
|
|
219
|
+
fixed=None if opts.get("fixed_tags") is False else _fixed(d),
|
|
220
|
+
canvas=canvas,
|
|
221
|
+
current_size=presets.resolve_size(d.get("size")),
|
|
222
|
+
steps=_first(opts.get("steps"), got.steps, d.get("steps")),
|
|
223
|
+
cfg=_first(opts.get("cfg"), got.cfg, d.get("cfg")),
|
|
224
|
+
sampler=sampler,
|
|
225
|
+
noise_schedule=_noise_schedule(opts, got, d, model, sampler),
|
|
226
|
+
cfg_rescale=_first(opts.get("cfg_rescale"), got.cfg_rescale, d.get("cfg_rescale"), 0.0),
|
|
227
|
+
seed=_first(opts.get("seed"), got.seed),
|
|
228
|
+
n=_samples(opts, d, command),
|
|
229
|
+
quality=_quality(opts, got, d, model),
|
|
230
|
+
uc_preset=_uc_preset(opts, got, d, model),
|
|
231
|
+
negative_verbatim=_first(opts.get("neg_verbatim"), got.negative_verbatim, False),
|
|
232
|
+
official_nsfw=_first(opts.get("official_nsfw"), got.official_nsfw, d.get("official_nsfw"), False),
|
|
233
|
+
auto_text=_first(opts.get("auto_text"), got.auto_text, True),
|
|
234
|
+
normalize_vibes=_first(opts.get("normalize_vibes"), got.normalize_vibes, True),
|
|
235
|
+
transparent=_first(opts.get("transparent"), got.transparent, False),
|
|
236
|
+
premultiplied_alpha=premultiplied,
|
|
237
|
+
furry=_first(opts.get("furry"), got.furry, False),
|
|
238
|
+
variety=_first(opts.get("variety"), got.variety, False),
|
|
239
|
+
legacy_uc=_first(opts.get("legacy_uc"), got.legacy_uc, False),
|
|
240
|
+
strength=strength,
|
|
241
|
+
noise=noise,
|
|
242
|
+
stored_vibes=_stored_vibes(opts, got),
|
|
243
|
+
vibes=tuple(vibe_ref(v) for v in opts.get("vibe") or []),
|
|
244
|
+
references=tuple(precise_ref(r) for r in opts.get("ref") or []),
|
|
245
|
+
drawn=_drawn(canvas) if command in (*FROM_IMAGE, "inpaint") else None,
|
|
246
|
+
output=output.resolve(opts.get("output"), cfg),
|
|
247
|
+
dry_run=bool(opts.get("dry_run")) or ctx.dry_run,
|
|
248
|
+
yes=bool(opts.get("yes")),
|
|
249
|
+
show_body=bool(opts.get("show_body")),
|
|
250
|
+
warnings=tuple(warnings),
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _first(*values: Any) -> Any:
|
|
255
|
+
"""Command line, then the imported image, then the config, then the built-in default."""
|
|
256
|
+
return next((v for v in values if v is not None), None)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _imported(
|
|
260
|
+
opts: dict[str, Any],
|
|
261
|
+
command: str,
|
|
262
|
+
chosen: models.Model | None,
|
|
263
|
+
default: models.Model,
|
|
264
|
+
configured: Callable[[models.Model], models.Model],
|
|
265
|
+
) -> import_image.Imported | None:
|
|
266
|
+
if command in FROM_IMAGE:
|
|
267
|
+
# Everything but the seed: the official client starts from the image's settings with a new seed every time
|
|
268
|
+
parts = tuple(p for p in import_image.PARTS if p != "seed")
|
|
269
|
+
try:
|
|
270
|
+
return import_image.from_image(opts["image"], parts, chosen, default, configured, rework=True)
|
|
271
|
+
except errors.NaiError as e:
|
|
272
|
+
if e.code != errors.NO_METADATA:
|
|
273
|
+
raise
|
|
274
|
+
return None
|
|
275
|
+
if not opts.get("from_image"):
|
|
276
|
+
return None
|
|
277
|
+
parts = import_image.parse_parts(opts.get("import_parts"))
|
|
278
|
+
return import_image.from_image(
|
|
279
|
+
opts["from_image"],
|
|
280
|
+
parts,
|
|
281
|
+
chosen,
|
|
282
|
+
default,
|
|
283
|
+
configured,
|
|
284
|
+
clean_brackets=bool(opts.get("clean_brackets")),
|
|
285
|
+
drawn_prompts=bool(opts.get("actual_prompts")),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _text(typed: str | None, imported: str | None) -> Text:
|
|
290
|
+
if typed is not None:
|
|
291
|
+
return Text(typed)
|
|
292
|
+
return Text(imported, Origin.IMAGE) if imported is not None else Text("")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _characters(
|
|
296
|
+
typed: dict[str, Any], positions: list[str] | None, got: import_image.Imported, model: models.Model
|
|
297
|
+
) -> tuple[tuple[CharacterText, ...], bool]:
|
|
298
|
+
"""Characters given replace the image's, along with their negatives and positions, as the import dialog does
|
|
299
|
+
unless told to append."""
|
|
300
|
+
if typed["char"] is None and typed["char_neg"] is None and positions is None:
|
|
301
|
+
chars = got.characters or []
|
|
302
|
+
return tuple(
|
|
303
|
+
CharacterText(
|
|
304
|
+
Text(c.prompt, Origin.IMAGE),
|
|
305
|
+
Text(c.negative, Origin.IMAGE),
|
|
306
|
+
(c.x, c.y) if c.x is not None and c.y is not None else None,
|
|
307
|
+
)
|
|
308
|
+
for c in chars
|
|
309
|
+
), bool(got.use_coords)
|
|
310
|
+
prompts, negatives = typed["char"] or [], typed["char_neg"] or []
|
|
311
|
+
if len(negatives) > len(prompts):
|
|
312
|
+
raise errors.NaiError(errors.BAD_ARGS, f"{len(negatives)} --char-neg for {len(prompts)} --char")
|
|
313
|
+
preset = Text(model.character_negative, Origin.MODEL)
|
|
314
|
+
chars = tuple(
|
|
315
|
+
CharacterText(Text(text), Text(negatives[i]) if i < len(negatives) else preset)
|
|
316
|
+
for i, text in enumerate(prompts)
|
|
317
|
+
)
|
|
318
|
+
return _placed(chars, positions), bool(positions)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@dataclass(frozen=True)
|
|
322
|
+
class _Written:
|
|
323
|
+
"""A prompt and characters that replace the image's and --char."""
|
|
324
|
+
|
|
325
|
+
prompt: Text
|
|
326
|
+
characters: tuple[CharacterText, ...]
|
|
327
|
+
use_coords: bool
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _random_prompt(opts: dict[str, Any], typed: dict[str, Any]) -> _Written | None:
|
|
331
|
+
"""A random prompt and characters, which replace the image's as the dice button replaces the editor's."""
|
|
332
|
+
if not opts.get("random_prompt"):
|
|
333
|
+
return None
|
|
334
|
+
if typed["prompt"] is not None or typed["char"] is not None or typed["char_neg"] is not None:
|
|
335
|
+
raise errors.NaiError(
|
|
336
|
+
errors.BAD_ARGS, "--random-prompt writes the prompt and characters; leave out --prompt and --char"
|
|
337
|
+
)
|
|
338
|
+
if opts.get("char_pos"):
|
|
339
|
+
raise errors.NaiError(errors.BAD_ARGS, "--random-prompt places its characters itself; leave out --char-pos")
|
|
340
|
+
drawn = random_prompt.generate(random_prompt.Recipe(opts["random_prompt"]))
|
|
341
|
+
negative = Text(random_prompt.CHARACTER_NEGATIVE, Origin.MODEL)
|
|
342
|
+
return _Written(
|
|
343
|
+
Text(drawn.prompt),
|
|
344
|
+
tuple(CharacterText(Text(c), negative, random_prompt.CHARACTER_CENTER) for c in drawn.characters),
|
|
345
|
+
False,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _comfyui(opts: dict[str, Any], d: dict[str, Any], typed: dict[str, Any], model: models.Model) -> _Written | None:
|
|
350
|
+
"""A ComfyUI multi-character prompt split into characters; off by default because a single | also divides
|
|
351
|
+
official prompts."""
|
|
352
|
+
if not _first(opts.get("comfyui_characters"), d.get("comfyui_characters"), False) or typed["prompt"] is None:
|
|
353
|
+
return None
|
|
354
|
+
found = comfyui.split(typed["prompt"])
|
|
355
|
+
if found is None:
|
|
356
|
+
return None
|
|
357
|
+
if typed["char"] is not None or typed["char_neg"] is not None or opts.get("char_pos"):
|
|
358
|
+
raise errors.NaiError(
|
|
359
|
+
errors.BAD_ARGS,
|
|
360
|
+
"the prompt gives the characters with --comfyui-characters; leave out --char, --char-neg and --char-pos",
|
|
361
|
+
)
|
|
362
|
+
placed = any(c.center is not None for c in found.characters)
|
|
363
|
+
taken: list[tuple[float, float]] = []
|
|
364
|
+
for c in found.characters:
|
|
365
|
+
# A character without a region goes to the first free place, as one added in the editor does
|
|
366
|
+
taken.append(c.center or request.default_center(taken, model.freeform_position))
|
|
367
|
+
negative = Text(model.character_negative, Origin.MODEL)
|
|
368
|
+
return _Written(
|
|
369
|
+
Text(found.base),
|
|
370
|
+
tuple(
|
|
371
|
+
CharacterText(Text(c.prompt), negative, center if placed else None)
|
|
372
|
+
for c, center in zip(found.characters, taken, strict=True)
|
|
373
|
+
),
|
|
374
|
+
placed,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _placed(characters: tuple[CharacterText, ...], positions: list[str] | None) -> tuple[CharacterText, ...]:
|
|
379
|
+
"""--char-pos for each character, checked within 0-1."""
|
|
380
|
+
if not positions:
|
|
381
|
+
return characters
|
|
382
|
+
if len(positions) != len(characters):
|
|
383
|
+
raise errors.NaiError(errors.BAD_ARGS, f"{len(positions)} --char-pos for {len(characters)} characters")
|
|
384
|
+
out = []
|
|
385
|
+
for c, pos in zip(characters, positions, strict=True):
|
|
386
|
+
try:
|
|
387
|
+
x, y = (float(v) for v in pos.split(","))
|
|
388
|
+
except ValueError:
|
|
389
|
+
raise errors.NaiError(errors.BAD_ARGS, f"position must be x,y: {pos}") from None
|
|
390
|
+
# Checked before focus maps it into the crop, which clamps it
|
|
391
|
+
if not (0 <= x <= 1 and 0 <= y <= 1):
|
|
392
|
+
raise errors.NaiError(errors.BAD_ARGS, f"character positions must be within 0-1: {pos}")
|
|
393
|
+
out.append(CharacterText(c.prompt, c.negative, (x, y)))
|
|
394
|
+
return tuple(out)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _tidy(opts: dict[str, Any], d: dict[str, Any]) -> dict[Origin, Tidy]:
|
|
398
|
+
def switch(name: str, from_config: bool) -> bool:
|
|
399
|
+
value = opts.get(name)
|
|
400
|
+
if value is not None:
|
|
401
|
+
return value
|
|
402
|
+
return d.get(name, False) if from_config else False
|
|
403
|
+
|
|
404
|
+
underscores = d.get("format_underscores", False)
|
|
405
|
+
return {
|
|
406
|
+
origin: Tidy(
|
|
407
|
+
switch("convert_sd_weights", origin is Origin.TYPED),
|
|
408
|
+
switch("format_prompt", origin is Origin.TYPED),
|
|
409
|
+
underscores,
|
|
410
|
+
switch("space_numeric_close", origin is Origin.TYPED),
|
|
411
|
+
)
|
|
412
|
+
for origin in Origin
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _fixed(d: dict[str, Any]) -> Fixed:
|
|
417
|
+
return Fixed(
|
|
418
|
+
(d.get("prompt_prefix", ""), d.get("prompt_suffix", "")),
|
|
419
|
+
(d.get("negative_prefix", ""), d.get("negative_suffix", "")),
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _canvas(
|
|
424
|
+
opts: dict[str, Any],
|
|
425
|
+
got: import_image.Imported,
|
|
426
|
+
cfg: config.Config,
|
|
427
|
+
command: str,
|
|
428
|
+
model: models.Model,
|
|
429
|
+
warnings: list[str],
|
|
430
|
+
) -> Canvas:
|
|
431
|
+
given = presets.resolve_size(opts["size"]) if opts.get("size") else None
|
|
432
|
+
if command == "enhance":
|
|
433
|
+
plan = enhance.plan(
|
|
434
|
+
*images.size_of(opts["image"]),
|
|
435
|
+
model,
|
|
436
|
+
opts.get("level"),
|
|
437
|
+
opts.get("scale"),
|
|
438
|
+
opts.get("strength"),
|
|
439
|
+
opts.get("noise"),
|
|
440
|
+
)
|
|
441
|
+
return Enhanced(Path(opts["image"]), plan)
|
|
442
|
+
# Inpainting sizes the request from the image being repainted
|
|
443
|
+
if command == "inpaint":
|
|
444
|
+
return Repaint(Path(opts["image"]), given, _inpaint_area(opts, cfg.local.sam_dir))
|
|
445
|
+
size = given or _imported_size(got, warnings)
|
|
446
|
+
if ACTIONS[command] == "img2img":
|
|
447
|
+
return FromImage(Path(opts["image"]), size)
|
|
448
|
+
return Blank(size or presets.resolve_size(cfg.defaults.get("size")))
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _imported_size(got: import_image.Imported, warnings: list[str]) -> tuple[int, int] | None:
|
|
452
|
+
if got.size is not None and got.size_note:
|
|
453
|
+
warnings.append(got.size_note)
|
|
454
|
+
return got.size
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _samples(opts: dict[str, Any], d: dict[str, Any], command: str) -> int | None:
|
|
458
|
+
"""None for variations, whose count follows the size."""
|
|
459
|
+
if opts.get("n") is not None:
|
|
460
|
+
return opts["n"]
|
|
461
|
+
if command == "enhance":
|
|
462
|
+
return 1
|
|
463
|
+
if command == "variations":
|
|
464
|
+
return None
|
|
465
|
+
return d.get("n", 1)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _quality(opts: dict[str, Any], got: import_image.Imported, d: dict[str, Any], model: models.Model) -> str:
|
|
469
|
+
chosen = _first(opts.get("quality"), got.quality)
|
|
470
|
+
# The config's light applies to every model; those without the tier keep the standard one
|
|
471
|
+
if chosen is None and d.get("quality") == "light" and "light" not in presets.quality_tiers(model):
|
|
472
|
+
return "standard"
|
|
473
|
+
return presets.resolve_quality(model, _first(chosen, d.get("quality")))
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _uc_preset(opts: dict[str, Any], got: import_image.Imported, d: dict[str, Any], model: models.Model) -> str:
|
|
477
|
+
chosen = _first(opts.get("uc_preset"), got.uc_preset)
|
|
478
|
+
# The config's preset applies to every model; one without it takes the closest it has
|
|
479
|
+
if chosen is None and d.get("uc_preset") is not None:
|
|
480
|
+
return presets.carry_uc_preset(presets.uc_preset_name(str(d["uc_preset"])), model)
|
|
481
|
+
return presets.resolve_uc_preset(model, chosen)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _noise_schedule(
|
|
485
|
+
opts: dict[str, Any], got: import_image.Imported, d: dict[str, Any], model: models.Model, sampler: str
|
|
486
|
+
) -> str:
|
|
487
|
+
chosen = _first(opts.get("noise_schedule"), got.noise_schedule, d.get("noise_schedule"))
|
|
488
|
+
keeps_schedule = model.noise_schedule and not model.is_v5
|
|
489
|
+
schedule = chosen or (models.default_noise_schedule(sampler) if keeps_schedule else "karras")
|
|
490
|
+
offered = models.NOISE_SCHEDULES
|
|
491
|
+
if schedule not in offered:
|
|
492
|
+
raise errors.NaiError(
|
|
493
|
+
errors.BAD_ARGS, f"{model.name} does not take the noise schedule {schedule}", choices=offered
|
|
494
|
+
)
|
|
495
|
+
return schedule
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _image_strength(opts: dict[str, Any], command: str, canvas: Canvas) -> tuple[float, float]:
|
|
499
|
+
if isinstance(canvas, Enhanced):
|
|
500
|
+
return canvas.plan.strength, canvas.plan.noise
|
|
501
|
+
if command == "variations":
|
|
502
|
+
default_strength, default_noise = enhance.VARIATION_STRENGTH, enhance.VARIATION_NOISE
|
|
503
|
+
else:
|
|
504
|
+
default_strength, default_noise = 0.7, 0.0
|
|
505
|
+
return _first(opts.get("strength"), default_strength), _first(opts.get("noise"), default_noise)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _inpaint_area(opts: dict[str, Any], sam_dir: Path) -> InpaintArea:
|
|
509
|
+
if not (opts.get("mask") or opts.get("region") or opts.get("expand")):
|
|
510
|
+
raise errors.NaiError(errors.BAD_ARGS, "inpaint needs --mask, --region or --expand")
|
|
511
|
+
if opts.get("size") and opts.get("focus"):
|
|
512
|
+
raise errors.NaiError(
|
|
513
|
+
errors.BAD_ARGS, "--focus sizes the request from the crop and cannot be combined with --size"
|
|
514
|
+
)
|
|
515
|
+
padding = _first(opts.get("focus_padding"), inpaint.DEFAULT_FOCUS_PADDING)
|
|
516
|
+
low, high = inpaint.FOCUS_PADDING_RANGE
|
|
517
|
+
if not low <= padding <= high:
|
|
518
|
+
raise errors.NaiError(errors.BAD_ARGS, f"--focus-padding must be within {low}-{high} pixels")
|
|
519
|
+
grow = _first(opts.get("grow"), 0)
|
|
520
|
+
if grow < 0:
|
|
521
|
+
raise errors.NaiError(errors.BAD_ARGS, "--grow cannot be negative")
|
|
522
|
+
return InpaintArea(
|
|
523
|
+
mask=Path(opts["mask"]) if opts.get("mask") else None,
|
|
524
|
+
regions=tuple(opts.get("region") or ()),
|
|
525
|
+
grow=grow,
|
|
526
|
+
expand=opts.get("expand"),
|
|
527
|
+
focus=opts.get("focus"),
|
|
528
|
+
focus_padding=padding,
|
|
529
|
+
strength=_first(opts.get("inpaint_strength"), 1.0),
|
|
530
|
+
preview=bool(opts.get("preview")),
|
|
531
|
+
keep_raw=bool(opts.get("keep_raw")),
|
|
532
|
+
sam_dir=sam_dir,
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _stored_vibes(opts: dict[str, Any], got: import_image.Imported) -> tuple[vibe.VibeSource, ...]:
|
|
537
|
+
if opts.get("vibes_from"):
|
|
538
|
+
return tuple(vibe.from_settings(opts["vibes_from"]))
|
|
539
|
+
return tuple(got.vibes or ())
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _drawn(canvas: Canvas) -> meta.Drawn | None:
|
|
543
|
+
"""What the image being enhanced, varied or repainted drew, which the official client sends again."""
|
|
544
|
+
if isinstance(canvas, Blank):
|
|
545
|
+
return None
|
|
546
|
+
try:
|
|
547
|
+
return meta.drawn(meta.read_raw(canvas.image))
|
|
548
|
+
except errors.NaiError:
|
|
549
|
+
# An image without settings has nothing drawn to send again
|
|
550
|
+
return None
|
nai_cli/commands/grid.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""grid: run a command once per cell of settings varied along two axes, then save a labelled sheet of the images."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from nai_cli import errors, fs, grid, images, naming, sheet
|
|
8
|
+
from nai_cli.commands import batch
|
|
9
|
+
from nai_cli.commands.context import Context
|
|
10
|
+
from nai_cli.commands.texts import text_arg
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class GridSettings:
|
|
15
|
+
grid: grid.Grid
|
|
16
|
+
options: batch.RunOptions
|
|
17
|
+
sheet: bool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def resolve(opts: dict[str, Any], ctx: Context) -> GridSettings:
|
|
21
|
+
try:
|
|
22
|
+
x = grid.parse_axis([_entry(e) for e in opts.get("x") or []])
|
|
23
|
+
y = grid.parse_axis([_entry(e) for e in opts.get("y") or []])
|
|
24
|
+
built = grid.build(list(opts.get("job") or []), x, y, ctx.parse_job)
|
|
25
|
+
options = batch.run_options(opts, ctx)
|
|
26
|
+
except errors.NaiError as e:
|
|
27
|
+
raise batch.as_summary(e) from None
|
|
28
|
+
return GridSettings(built, options, opts.get("sheet") is not False)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _entry(text: str) -> tuple[str, str]:
|
|
32
|
+
name, sep, values = text.partition("=")
|
|
33
|
+
if not sep:
|
|
34
|
+
raise errors.NaiError(errors.BAD_ARGS, f"an axis is PARAM=VALUES: {text}")
|
|
35
|
+
# @FILE gives the values from a file, one prompt per line
|
|
36
|
+
return name, text_arg(values)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def run(s: GridSettings, ctx: Context) -> dict[str, Any]:
|
|
40
|
+
g = s.grid
|
|
41
|
+
if not s.options.dry_run:
|
|
42
|
+
_try_cells(g, ctx)
|
|
43
|
+
ran = batch.run_jobs(tuple(c.job for c in g.cells), set(), s.options, ctx)
|
|
44
|
+
layout: dict[str, Any] = {
|
|
45
|
+
"columns": g.columns,
|
|
46
|
+
"rows": g.rows,
|
|
47
|
+
"x": g.x.title if g.x else None,
|
|
48
|
+
"y": g.y.title if g.y else None,
|
|
49
|
+
}
|
|
50
|
+
if s.sheet and not s.options.dry_run:
|
|
51
|
+
try:
|
|
52
|
+
layout["sheet"] = _save_sheet(g, ran.results)
|
|
53
|
+
except KeyboardInterrupt:
|
|
54
|
+
ran.totals.code = 130
|
|
55
|
+
layout["sheet"] = None
|
|
56
|
+
except (OSError, ValueError, errors.NaiError) as e:
|
|
57
|
+
# The cells are paid for and saved; only the sheet is missing
|
|
58
|
+
layout["sheet"] = None
|
|
59
|
+
layout["sheet_error"] = str(e)
|
|
60
|
+
return batch.summary(ran, s.options.dry_run, grid=layout)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _try_cells(g: grid.Grid, ctx: Context) -> None:
|
|
64
|
+
"""Every cell as a dry run before the first is sent, so a value the command refuses, such as steps past the
|
|
65
|
+
limit, fails the grid before any cell is paid for."""
|
|
66
|
+
for cell in g.cells:
|
|
67
|
+
result, code = ctx.run_job(cell.job.argv, ctx.job(cell.job.argv, dry_run=True))
|
|
68
|
+
if code == 130 or ctx.shared.interrupted:
|
|
69
|
+
raise batch.as_summary(errors.NaiError(errors.INTERRUPTED, "interrupted"))
|
|
70
|
+
if code:
|
|
71
|
+
message = f"cell {cell.job.id} cannot run, so no cell was sent: {result.get('message')}"
|
|
72
|
+
raise batch.as_summary(errors.NaiError(result.get("code") or errors.BAD_ARGS, message))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _save_sheet(g: grid.Grid, results: dict[str, dict[str, Any]]) -> str | None:
|
|
76
|
+
"""NAME_grid.png beside the first image; nothing when no cell made one."""
|
|
77
|
+
files = {c.job.id: _first_image(results.get(c.job.id)) for c in g.cells}
|
|
78
|
+
first = next((f for f in files.values() if f is not None), None)
|
|
79
|
+
if first is None:
|
|
80
|
+
return None
|
|
81
|
+
rows: list[list[Any]] = [[None] * g.columns for _ in range(g.rows)]
|
|
82
|
+
for c in g.cells:
|
|
83
|
+
path = files[c.job.id]
|
|
84
|
+
rows[c.row][c.column] = images.open_image(path) if path is not None else None
|
|
85
|
+
picture = sheet.render(
|
|
86
|
+
sheet.Sheet(
|
|
87
|
+
rows,
|
|
88
|
+
list(g.x.labels) if g.x else [],
|
|
89
|
+
list(g.y.labels) if g.y else [],
|
|
90
|
+
g.x.title if g.x else "",
|
|
91
|
+
g.y.title if g.y else "",
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
return str(fs.create_numbered(naming.copy_path(first, "grid"), images.to_png(picture)))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _first_image(result: dict[str, Any] | None) -> Path | None:
|
|
98
|
+
found = (result or {}).get("images") or []
|
|
99
|
+
return Path(found[0]) if found and result and result.get("ok") else None
|