This repository was archived by the owner on Jun 30, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_entrypoint.py
More file actions
408 lines (322 loc) · 14.4 KB
/
Copy pathcli_entrypoint.py
File metadata and controls
408 lines (322 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""
cli_entrypoint.py — CLI front-end for the SDXL batch queue.
Usage
─────
python cli_entrypoint.py --workload workload.json
python cli_entrypoint.py --workload workload.json \\
--models-cfg models_cfg.json \\
--nodes-cfg nodes_cfg.json
JSON config schemas
───────────────────
--models-cfg → SDXLModelsCfg fields (see models_cfg_template.json)
--nodes-cfg → { "latent": {...}, "sampler": {...},
"ipadapter": {...}, "upscale": {...}, "rembg": {...} }
(see nodes_cfg_template.json)
All keys are optional; missing keys use built-in defaults.
"""
from __future__ import annotations
import argparse
import json
import os
import signal
import sys
import threading
import time
from pathlib import Path
from comfy_script.runtime import load
load()
src_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "src")
if src_path not in sys.path:
sys.path.insert(0, src_path)
from src.configs import (
ConfigRegistry,
IPAdapterConfig,
KSamplerConfig,
LatentConfig,
RembgConfig,
UpscaleConfig,
)
from src.lora_models import SomeLORA, union_lora_list_adapter
from src.models_cfg import SDXLModelsCfg
from src.queue import GroupStats, QueueReporter, SilentReporter, process_queue
# ── ANSI helpers ──────────────────────────────────────────────────────────────
_RESET = "\033[0m"
_BOLD = "\033[1m"
_GREEN = "\033[32m"
_RED = "\033[31m"
_YELLOW = "\033[33m"
_CYAN = "\033[36m"
_DIM = "\033[2m"
def _g(s: str) -> str:
return f"{_GREEN}{_BOLD}{s}{_RESET}" # bold green
def _r(s: str) -> str:
return f"{_RED}{_BOLD}{s}{_RESET}" # bold red
def _y(s: str) -> str:
return f"{_YELLOW}{s}{_RESET}" # yellow
def _c(s: str) -> str:
return f"{_CYAN}{s}{_RESET}" # cyan
def _b(s: str) -> str:
return f"{_BOLD}{s}{_RESET}" # bold
def _d(s: str) -> str:
return f"{_DIM}{s}{_RESET}" # dim
def _stats_line(stats: GroupStats) -> str:
return (
f"Всього {_b(str(stats.total))}, "
f"згенеровано {_g(str(stats.done))}, "
f"залишилось {_c(str(stats.remaining))}, "
f"помилка {_r(str(stats.errors))}"
)
def _is_jupyter() -> bool:
try:
shell = get_ipython().__class__.__name__ # type: ignore[name-defined]
return shell in ("ZMQInteractiveShell", "TerminalInteractiveShell")
except NameError:
return False
# ── Spinner / pipeline display ────────────────────────────────────────────────
_SPINNER_CHARS = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
class PipelineDisplay:
"""
Shows an in-place animated spinner with the pipeline stage list
while a workflow is running.
Terminal mode — uses \\r to update a single line in place.
Jupyter mode — prints static lines (no \\r tricks needed).
"""
def __init__(self, img_name: str, stages: list[str], jupyter: bool = False):
self._name = img_name
self._stages = stages
self._jupyter = jupyter
self._stop = threading.Event()
self._thread: threading.Thread | None = None
# ── Stage formatting ──────────────────────────────────────────────────────
def _pending_pipeline(self) -> str:
return _d(" → ".join(self._stages))
def _done_pipeline(self, ok: bool) -> str:
icon = "✓" if ok else "✗"
color = _g if ok else _r
parts = [color(f"{icon} {s}") for s in self._stages]
return f" {_g('→') if ok else _r('→')} ".join(parts)
# ── Spinner thread ────────────────────────────────────────────────────────
def _spin(self) -> None:
idx = 0
stages_str = self._pending_pipeline()
start = time.time()
while not self._stop.is_set():
char = _SPINNER_CHARS[idx % len(_SPINNER_CHARS)]
elapsed = int(time.time() - start)
line = f" {_c(char)} {stages_str} {_d(f'[{elapsed:03d}s]')}"
print(f"\r{line} ", end="", flush=True)
idx += 1
time.sleep(0.1)
# Clear the spinner line so finish() can overwrite cleanly.
print("\r" + " " * 80 + "\r", end="", flush=True)
# ── Public API ────────────────────────────────────────────────────────────
def start(self) -> None:
if self._jupyter:
print(f" Конвеєр: {self._pending_pipeline()}", flush=True)
print(f" Генерація...", flush=True)
else:
self._thread = threading.Thread(target=self._spin, daemon=True)
self._thread.start()
def finish(self, duration: float, ok: bool = True) -> None:
self._stop.set()
if self._thread:
self._thread.join()
pipeline = self._done_pipeline(ok)
if self._jupyter:
print(f" Конвеєр: {pipeline}")
else:
print(f" {pipeline} {_d(f'[{duration:.1f}s]')}", flush=True)
# ── Reporter implementation ───────────────────────────────────────────────────
class CliReporter:
"""
Translates queue lifecycle events into formatted terminal output.
No tqdm — raw Python prints + ANSI codes only.
"""
def __init__(self) -> None:
self._jupyter = _is_jupyter()
self._display: PipelineDisplay | None = None
self._sep = _d("─" * 60)
# ── Separator ─────────────────────────────────────────────────────────────
def _line(self) -> None:
print(self._sep)
# ── QueueReporter protocol ────────────────────────────────────────────────
def on_groups_found(self, count: int) -> None:
print()
print(f"{_b('Всього знайдено груп:')} {_c(str(count))}")
def on_group_start(self, name: str, stats: GroupStats) -> None:
print()
self._line()
print(f"{_b('Почато обробку групи:')} {_y(name)}")
print(f" {_stats_line(stats)}")
def on_image_start(self, name: str, stages: list[str]) -> None:
print()
print(f" {_b('Почато створення зображення:')} {name}")
self._display = PipelineDisplay(name, stages, jupyter=self._jupyter)
self._display.start()
def on_image_done(self, name: str, duration: float, stats: GroupStats) -> None:
if self._display:
self._display.finish(duration, ok=True)
self._display = None
print(f" {_g('✓')} Завершено: {_b(name)} {_d(f'({duration:.1f}s)')}")
self._line()
print(f" {_stats_line(stats)}")
def on_image_error(
self, name: str, duration: float, exc: Exception, stats: GroupStats
) -> None:
if self._display:
self._display.finish(duration, ok=False)
self._display = None
print(f" {_r('✗')} Помилка: {_b(name)} — {_r(str(exc))}")
self._line()
print(f" {_stats_line(stats)}")
def on_group_done(self, name: str, path: Path, stats: GroupStats) -> None:
print()
print(f"{_g('✓')} Генерація групи {_b(name)} завершена")
print(f" {_stats_line(stats)}")
print(f" Збережено у: {_c(str(path))}")
self._line()
def on_fatal(self, message: str) -> None:
print(f"\n{_r('FATAL:')} {message}", file=sys.stderr)
# ── Graceful interrupt ────────────────────────────────────────────────────────
def _install_signal_handler(stop_flag: list[bool]) -> None:
"""SIGUSR1 → finish current image, then stop."""
def _handler(*_):
stop_flag[0] = True
print(
f"\n{_y('!' * 60)}\n"
f"{_y('SIGUSR1 отримано — завершую поточне зображення, після зупинюсь...')}\n"
f"{_y('!' * 60)}\n",
flush=True,
)
try:
signal.signal(signal.SIGUSR1, _handler)
print(_d(f"PID {os.getpid()} | м'яка зупинка: kill -USR1 {os.getpid()}"))
except (OSError, AttributeError):
# Windows — SIGUSR1 not available
pass
# ── Config loaders ────────────────────────────────────────────────────────────
_CFG_CLASSES = {
"latent": LatentConfig,
"sampler": KSamplerConfig,
"ipadapter": IPAdapterConfig,
"upscale": UpscaleConfig,
"rembg": RembgConfig,
}
def _load_nodes_cfg(path: str) -> ConfigRegistry:
"""
Parse nodes_cfg.json into a ConfigRegistry.
Expected shape (all keys optional):
{
"latent": { "width": 1024, "height": 1024 },
"sampler": { "steps": 30, "cfg": 6.5, ... },
"ipadapter": { "weight": 0.55, ... },
"upscale": { "upscale_by": 4.0, ... },
"rembg": { "threshold": 0.5, ... }
}
"""
raw = json.loads(Path(path).read_text(encoding="utf-8"))
registry = ConfigRegistry()
for key, cls in _CFG_CLASSES.items():
if key in raw:
registry = registry.with_cfg(key, cls.model_validate(raw[key]))
return registry
# ── CLI entrypoint ────────────────────────────────────────────────────────────
def main() -> None:
ap = argparse.ArgumentParser(
description="Comfyui automation batch generation — CLI",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
examples:
python cli_entrypoint.py --workload workload.json
python cli_entrypoint.py --workload workload.json --models-cfg models_cfg.json
python cli_entrypoint.py --workload workload.json \\
--models-cfg models_cfg.json \\
--nodes-cfg nodes_cfg.json \\
-o /path/to/export_folder/ \\
--lora lora.json 0 1 \\
--lora lora2.json \\
--lora lora3.json 5 0
""",
)
ap.add_argument(
"--workload",
required=True,
metavar="FILE",
help="Path to workload.json",
)
ap.add_argument(
"--models-cfg",
metavar="FILE",
help="Path to models_cfg.json (SDXLModelsCfg fields)",
)
ap.add_argument(
"--nodes-cfg",
metavar="FILE",
help=(
"Path to nodes_cfg.json "
"(latent/sampler/ipadapter/upscale/rembg keys, all optional)"
),
)
ap.add_argument(
"--output",
"-o",
type=Path,
metavar="DIR",
help=(
"Path to export folder, default in DATA_DIRECORY/export or root_save_folder from workfload.json if exist"
),
)
ap.add_argument(
"--lora",
action="append",
nargs="+",
metavar=("FILE", "IDXS"),
help=(
"Path to lora.json file(s)"
"file must contain list with LocalLORA or CivitaiLORA model(s)"
"IDXS is indices of loras in that list"
"Local LORA (file_name\strength_model\strength_clip\clip_skip\triger_words, triger_words and clip_skip - optional)"
"Civitai LORA (lora_air\lora_name\strength_model\strength_clip\clip_skip\triger_words; triger_words and clip_skip - optional)"
),
)
args = ap.parse_args()
# ── Load configs ──────────────────────────────────────────────────────────
models_cfg = SDXLModelsCfg.model_validate_json(Path(args.models_cfg).read_text())
configs = _load_nodes_cfg(args.nodes_cfg) if args.nodes_cfg else ConfigRegistry()
loras: list[SomeLORA] = []
if args.lora:
for entry in args.lora:
# entry[0] - lora.json file path
# entry[1:] - lora list indices to apply
file_path = Path(entry[0])
try:
indices = [int(i) for i in entry[1:]]
if not file_path.exists:
print(f"Warning: File {file_path} not found.")
continue
file_content = file_path.read_text()
loras_from_file = union_lora_list_adapter.validate_json(file_content)
for i in indices:
loras.append(loras_from_file[i])
except ValueError:
print(f"Error: indices for {file_path} must be integers.")
except Exception as e:
print(f"Error parsing {file_path}: {e}")
# ── Graceful stop ─────────────────────────────────────────────────────────
stop_flag: list[bool] = [False]
_install_signal_handler(stop_flag)
# ── Run ───────────────────────────────────────────────────────────────────
reporter = CliReporter()
process_queue(
config_path=args.workload,
models_cfg=models_cfg,
loras=loras,
output_folder=args.output,
configs=configs,
reporter=reporter,
stop_flag=stop_flag,
)
status = "ПЕРЕРВАНО" if stop_flag[0] else "ЗАВЕРШЕНО"
print(f"\n{_b(status)}: {Path(args.workload).stem}\n")
if __name__ == "__main__":
main()