forked from lightningpixel/modly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
1360 lines (1157 loc) · 63.9 KB
/
Copy pathagent.py
File metadata and controls
1360 lines (1157 loc) · 63.9 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Minimal agent-friendly CLI for the local Modly API.
The Electron app normally owns the FastAPI server. This tool is intentionally
small and stdlib-only so automation agents can call a running Modly instance,
optionally start only the FastAPI backend, and always receive parseable JSON.
"""
from __future__ import annotations
import argparse
import json
import mimetypes
import os
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
def _int_env(primary: str, fallback: str, default: int) -> int:
value = os.environ.get(primary, os.environ.get(fallback, str(default)))
try:
return int(value)
except (TypeError, ValueError):
return default
def _float_env(primary: str, fallback: str, default: float) -> float:
value = os.environ.get(primary, os.environ.get(fallback, str(default)))
try:
return float(value)
except (TypeError, ValueError):
return default
DEFAULT_BASE_URL = os.environ.get("MODLY_API_URL", "http://127.0.0.1:8765")
DEFAULT_TIMEOUT_SECONDS = _int_env("MODLY_CLI_TIMEOUT", "MODLY_AGENT_TIMEOUT", 1800)
DEFAULT_POLL_SECONDS = _float_env("MODLY_CLI_POLL_SECONDS", "MODLY_AGENT_POLL_SECONDS", 2.0)
EXPORT_FORMATS = ("glb", "stl", "obj", "ply")
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp"}
WORKFLOW_ASSET_SUFFIXES = {".glb", ".gltf", ".obj", ".stl", ".ply"}
class ModlyCliError(RuntimeError):
"""Expected user/API failure that should be reported as JSON."""
def __init__(self, message: str, *, code: str = "MODLY_CLI_ERROR", http_status: int | None = None) -> None:
super().__init__(message)
self.message = message
self.code = code
self.http_status = http_status
def _json_print(data: dict[str, Any], *, compact: bool = False) -> None:
if compact:
print(json.dumps(data, separators=(",", ":"), sort_keys=True))
else:
print(json.dumps(data, indent=2, sort_keys=True))
def _request_json(
method: str,
url: str,
*,
timeout: float,
data: bytes | None = None,
headers: dict[str, str] | None = None,
) -> Any:
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise ModlyCliError(f"HTTP {exc.code} from {url}: {detail}", code=f"HTTP_{exc.code}", http_status=exc.code) from exc
except urllib.error.URLError as exc:
raise ModlyCliError(f"Cannot reach Modly API at {url}: {exc.reason}", code="API_UNAVAILABLE") from exc
try:
return json.loads(raw) if raw else {}
except json.JSONDecodeError as exc:
raise ModlyCliError(f"Expected JSON from {url}, got: {raw[:500]}", code="INVALID_JSON_RESPONSE") from exc
def _download(url: str, dest: Path, *, timeout: float) -> int:
dest.parent.mkdir(parents=True, exist_ok=True)
try:
with urllib.request.urlopen(url, timeout=timeout) as resp, dest.open("wb") as fh:
total = 0
while True:
chunk = resp.read(1024 * 1024)
if not chunk:
return total
fh.write(chunk)
total += len(chunk)
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise ModlyCliError(f"HTTP {exc.code} while downloading {url}: {detail}", code=f"HTTP_{exc.code}", http_status=exc.code) from exc
except urllib.error.URLError as exc:
raise ModlyCliError(f"Cannot download {url}: {exc.reason}", code="DOWNLOAD_FAILED") from exc
except OSError as exc:
raise ModlyCliError(f"Cannot write to {dest}: {exc}", code="WRITE_FAILED") from exc
def _multipart_form(fields: dict[str, str], file_field: str, file_path: Path) -> tuple[bytes, str]:
boundary = f"----modly-cli-{time.time_ns()}"
parts: list[bytes] = []
for name, value in fields.items():
parts.extend([
f"--{boundary}\r\n".encode(),
f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode(),
str(value).encode("utf-8"),
b"\r\n",
])
content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
parts.extend([
f"--{boundary}\r\n".encode(),
f'Content-Disposition: form-data; name="{file_field}"; filename="{file_path.name}"\r\n'.encode(),
f"Content-Type: {content_type}\r\n\r\n".encode(),
file_path.read_bytes(),
b"\r\n",
f"--{boundary}--\r\n".encode(),
])
return b"".join(parts), f"multipart/form-data; boundary={boundary}"
def _workspace_relative_path(output_url: str) -> str:
parsed = urllib.parse.urlparse(output_url)
path = parsed.path if parsed.scheme else output_url
prefix = "/workspace/"
if path.startswith(prefix):
return _validate_workspace_path(urllib.parse.unquote(path[len(prefix):]))
return _validate_workspace_path(urllib.parse.unquote(path))
def _is_windows_drive_component(component: str) -> bool:
return len(component) >= 2 and component[0].isalpha() and component[1] == ":"
def _validate_workspace_path(workspace_path: str) -> str:
value = str(workspace_path)
normalized = value.replace("\\", "/")
parts = normalized.split("/")
if (
not value
or value.startswith(("/", "\\"))
or urllib.parse.urlparse(value).scheme
or any(part == ".." for part in parts)
or any(_is_windows_drive_component(part) for part in parts)
):
raise ModlyCliError(f"Invalid workspace path: {workspace_path}", code="INVALID_WORKSPACE_PATH")
return value
def _export_workspace_path(base_url: str, workspace_path: str, fmt: str, dest: Path, *, timeout: float) -> int:
workspace_path = _validate_workspace_path(workspace_path)
export_url = f"{base_url.rstrip('/')}/export/{urllib.parse.quote(fmt)}?{urllib.parse.urlencode({'path': workspace_path})}"
return _download(export_url, dest, timeout=timeout)
def _try_health(base_url: str, timeout: float) -> dict[str, Any] | None:
try:
health = _request_json("GET", f"{base_url.rstrip('/')}/health", timeout=timeout)
except ModlyCliError:
return None
return health if isinstance(health, dict) else {"raw": health}
def _require_health(base_url: str, timeout: float) -> dict[str, Any]:
health = _request_json("GET", f"{base_url.rstrip('/')}/health", timeout=timeout)
return health if isinstance(health, dict) else {"raw": health}
def _model_catalog(base_url: str, timeout: float) -> list[dict[str, Any]]:
data = _request_json("GET", f"{base_url.rstrip('/')}/model/all", timeout=timeout)
if not isinstance(data, list):
raise ModlyCliError(f"Expected /model/all to return a list, got: {data}", code="INVALID_MODEL_CATALOG")
return [model for model in data if isinstance(model, dict)]
def _model_ids(models: list[dict[str, Any]]) -> set[str]:
return {str(model["id"]) for model in models if model.get("id")}
def _validate_model_id(base_url: str, request_timeout: float, model_id: str, models: list[dict[str, Any]] | None = None) -> str:
models = models if models is not None else _model_catalog(base_url, request_timeout)
ids = _model_ids(models)
if model_id not in ids:
available = ", ".join(sorted(ids)) or "(none)"
raise ModlyCliError(
f"Unknown model id '{model_id}'. Use one of: {available}",
code="INVALID_MODEL_ID",
)
return model_id
def _recovery_meta(base_url: str, run_id: str, *, legacy: bool = False, kind: str = "workflow-run", extra: dict[str, Any] | None = None) -> dict[str, Any]:
prefix = "python tools/modly-cli/agent.py"
if base_url.rstrip("/") != DEFAULT_BASE_URL.rstrip("/"):
prefix = f"{prefix} --base-url {base_url.rstrip('/')}"
if legacy:
group = "legacy job"
cancel = "legacy cancel"
elif kind == "process-run":
group = "process-run status"
cancel = "process-run cancel"
else:
group = "workflow-run status"
cancel = "workflow-run cancel"
meta = {
"status_command": f"{prefix} {group} {run_id}",
"cancel_command": f"{prefix} {cancel} {run_id}",
"legacy": legacy,
}
if extra:
meta.update(extra)
return meta
def _unsupported_process(message: str = "This process is not available through the canonical process-run contract.") -> ModlyCliError:
return ModlyCliError(message, code="UNSUPPORTED_PROCESS")
def _request_supported_contract(method: str, url: str, *, timeout: float, data: bytes | None = None, headers: dict[str, str] | None = None) -> Any:
try:
return _request_json(method, url, timeout=timeout, data=data, headers=headers)
except ModlyCliError as exc:
if exc.http_status == 404:
raise _unsupported_process() from exc
raise
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _windows_env_paths(name: str) -> list[Path]:
value = os.environ.get(name)
if value:
return [Path(value)]
paths: list[Path] = []
if os.name == "posix":
users_dir = Path("/mnt/c/Users")
roots: list[Path] = []
if users_dir.exists():
try:
roots = sorted(p for p in users_dir.glob("*") if p.is_dir())
except PermissionError:
roots = []
for root in roots:
try:
if name == "LOCALAPPDATA":
candidate = root / "AppData" / "Local"
elif name == "APPDATA":
candidate = root / "AppData" / "Roaming"
else:
continue
if candidate.exists():
paths.append(candidate)
except PermissionError:
continue
return paths
def _windows_env_path(name: str) -> Path | None:
paths = _windows_env_paths(name)
return paths[0] if paths else None
def _default_api_dir() -> Path | None:
repo_api = _repo_root() / "api"
if (repo_api / "main.py").exists():
return repo_api
for local in _windows_env_paths("LOCALAPPDATA"):
installed = local / "Programs" / "Modly" / "resources" / "api"
if (installed / "main.py").exists():
return installed
return None
def _default_python(api_dir: Path) -> Path | None:
candidates = [
api_dir / ".venv" / "Scripts" / "python.exe",
api_dir / ".venv" / "bin" / "python",
]
for appdata in _windows_env_paths("APPDATA"):
candidates.append(appdata / "Modly" / "dependencies" / "venv" / "Scripts" / "python.exe")
candidates.append(Path(sys.executable))
for candidate in candidates:
if candidate.exists():
return candidate
return None
def _load_modly_settings() -> dict[str, Any]:
candidates: list[Path] = []
for appdata in _windows_env_paths("APPDATA"):
candidates.append(appdata / "Modly" / "settings.json")
candidates.append(Path.home() / ".config" / "Modly" / "settings.json")
for path in candidates:
if path.exists():
try:
data = json.loads(path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError):
return {}
return {}
def _resolve_serve_config(args: argparse.Namespace) -> tuple[Path, Path, dict[str, str], list[str], str]:
api_dir = Path(args.api_dir).expanduser().resolve() if getattr(args, "api_dir", None) else _default_api_dir()
if not api_dir or not (api_dir / "main.py").exists():
raise ModlyCliError("Could not find Modly api directory; pass --api-dir")
python = Path(args.python).expanduser().resolve() if getattr(args, "python", None) else _default_python(api_dir)
if not python or not python.exists():
raise ModlyCliError("Could not find Modly Python environment; pass --python")
settings = _load_modly_settings()
env = os.environ.copy()
hf_token = getattr(args, "hf_token", None) or settings.get("hfToken") or os.environ.get("HF_TOKEN", "")
env.update({
"PYTHONUNBUFFERED": "1",
"MODELS_DIR": getattr(args, "models_dir", None) or settings.get("modelsDir") or str(Path.home() / ".modly" / "models"),
"WORKSPACE_DIR": getattr(args, "workspace_dir", None) or settings.get("workspaceDir") or str(Path.home() / ".modly" / "workspace"),
"EXTENSIONS_DIR": getattr(args, "extensions_dir", None) or settings.get("extensionsDir") or "",
"SELECTED_MODEL_ID": getattr(args, "model", None) or os.environ.get("SELECTED_MODEL_ID", ""),
"HUGGING_FACE_HUB_TOKEN": hf_token,
"HF_TOKEN": hf_token,
})
cmd = [str(python), "-m", "uvicorn", "main:app", "--host", args.host, "--port", str(args.port)]
base_url = f"http://{args.host}:{args.port}"
return api_dir, python, env, cmd, base_url
def _start_backend(cmd: list[str], *, api_dir: Path, env: dict[str, str], detach: bool) -> subprocess.Popen[Any]:
kwargs: dict[str, Any] = {"cwd": str(api_dir), "env": env}
if detach:
kwargs.update({
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
})
if os.name != "nt":
kwargs["start_new_session"] = True
else:
kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
return subprocess.Popen(cmd, **kwargs)
def cmd_health(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
data = _request_json("GET", f"{base_url}/health", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "health": data}, compact=args.compact)
return 0
def cmd_status(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
health = _request_json("GET", f"{base_url}/health", timeout=args.request_timeout)
model = _request_json("GET", f"{base_url}/model/status", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "health": health, "model": model}, compact=args.compact)
return 0
def cmd_models(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
data = _request_json("GET", f"{base_url}/model/all", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "models": data, "meta": {"canonical": "model list"}}, compact=args.compact)
return 0
def cmd_model_status(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
data = _request_json("GET", f"{base_url}/model/status", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "model": data}, compact=args.compact)
return 0
def cmd_model_list(args: argparse.Namespace) -> int:
return cmd_models(args)
def _parse_params(params_json: str | None, params_file: str | None) -> dict[str, Any]:
if params_file:
text = Path(params_file).expanduser().read_text(encoding="utf-8")
else:
text = params_json or "{}"
try:
parsed = json.loads(text)
except json.JSONDecodeError as exc:
raise ModlyCliError(f"params must be valid JSON: {exc}") from exc
if not isinstance(parsed, dict):
raise ModlyCliError("params must be a JSON object")
return parsed
def _choose_auto_model(base_url: str, request_timeout: float) -> str:
active = _request_json("GET", f"{base_url.rstrip('/')}/model/status", timeout=request_timeout)
if not isinstance(active, dict) or not active.get("id"):
raise ModlyCliError(f"Could not resolve active model id: {active}", code="MODEL_NOT_READY")
return _validate_model_id(base_url, request_timeout, str(active["id"]))
def _resolve_model_id(args: argparse.Namespace, base_url: str) -> str:
model_id = args.model
if not model_id or model_id == "auto":
return _choose_auto_model(base_url, args.request_timeout)
if model_id == "active":
active = _request_json("GET", f"{base_url}/model/status", timeout=args.request_timeout)
if not isinstance(active, dict) or not active.get("id"):
raise ModlyCliError(f"Could not resolve active model id: {active}", code="MODEL_NOT_READY")
return _validate_model_id(base_url, args.request_timeout, str(active["id"]))
return _validate_model_id(base_url, args.request_timeout, str(model_id))
def cmd_params(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
model_id = _resolve_model_id(args, base_url)
query = ""
if model_id:
query = "?" + urllib.parse.urlencode({"model_id": model_id})
params = _request_json("GET", f"{base_url}/model/params{query}", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "model_id": model_id, "params": params, "meta": {"canonical": "model params"}}, compact=args.compact)
return 0
def cmd_job(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
status = _request_json("GET", f"{base_url}/generate/status/{urllib.parse.quote(args.job_id)}", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "job_id": args.job_id, "status": status, "meta": _recovery_meta(base_url, args.job_id, legacy=True)}, compact=args.compact)
return 0
def cmd_cancel(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
result = _request_json("POST", f"{base_url}/generate/cancel/{urllib.parse.quote(args.job_id)}", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "job_id": args.job_id, "cancel": result, "meta": _recovery_meta(base_url, args.job_id, legacy=True)}, compact=args.compact)
return 0
def _load_comfy_workflow(workflow: str, *, host: str, timeout: float) -> dict[str, Any]:
path = Path(workflow).expanduser()
if path.exists():
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ModlyCliError(f"workflow must be valid JSON: {path}: {exc}") from exc
if not isinstance(data, dict):
raise ModlyCliError(f"workflow JSON must be an object: {path}")
return data
candidates = [workflow, f"{workflow}.json"] if not workflow.endswith(".json") else [workflow]
for name in candidates:
quoted = urllib.parse.quote(name.lstrip("/"), safe="/")
for prefix in ("/userdata/workflows/", "/api/userdata/workflows/", "/userdata/", "/api/userdata/"):
try:
data = _request_json("GET", f"{host.rstrip('/')}{prefix}{quoted}", timeout=timeout)
except ModlyCliError:
continue
if isinstance(data, dict):
return data
search_roots: list[Path] = []
for value in [os.environ.get("COMFYUI_WORKFLOW_DIR"), os.environ.get("COMFYUI_USER_DIR")]:
if value:
search_roots.append(Path(value).expanduser())
search_roots.extend([
Path.home() / "ComfyUI" / "user" / "default" / "workflows",
Path.home() / "Documents" / "ComfyUI" / "user" / "default" / "workflows",
])
for appdata in _windows_env_paths("APPDATA"):
search_roots.extend([
appdata / "ComfyUI" / "user" / "default" / "workflows",
appdata / "comfyui" / "user" / "default" / "workflows",
])
for root in search_roots:
for name in candidates:
candidate = root / name
if candidate.exists():
try:
data = json.loads(candidate.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ModlyCliError(f"workflow must be valid JSON: {candidate}: {exc}") from exc
if isinstance(data, dict):
return data
raise ModlyCliError(f"Could not find ComfyUI workflow '{workflow}'. Pass a JSON path or set COMFYUI_WORKFLOW_DIR.")
def _patch_comfy_workflow(workflow: dict[str, Any], *, prompt: str | None, seed: int | None) -> dict[str, Any]:
workflow = json.loads(json.dumps(workflow))
nodes = workflow.get("prompt", workflow)
if not isinstance(nodes, dict):
raise ModlyCliError("ComfyUI workflow must be API format (top-level node-id object, or {'prompt': {...}})")
if "nodes" in workflow and "links" in workflow:
raise ModlyCliError("ComfyUI workflow is editor format; export it as API format first")
if prompt is not None:
patched = False
for node in nodes.values():
if not isinstance(node, dict):
continue
class_type = str(node.get("class_type", "")).lower()
inputs = node.get("inputs") if isinstance(node.get("inputs"), dict) else {}
text = str(inputs.get("text", "")).lower()
if "cliptextencode" in class_type and "negative" not in text:
inputs["text"] = prompt
patched = True
break
if not patched:
for node in nodes.values():
if isinstance(node, dict) and isinstance(node.get("inputs"), dict):
inputs = node["inputs"]
for key in ("prompt", "positive", "text"):
if key in inputs and isinstance(inputs[key], str):
inputs[key] = prompt
patched = True
break
if patched:
break
if not patched:
raise ModlyCliError("Could not find a text/prompt input to patch in ComfyUI workflow")
if seed is not None:
for node in nodes.values():
if not isinstance(node, dict) or not isinstance(node.get("inputs"), dict):
continue
inputs = node["inputs"]
for key in ("seed", "noise_seed"):
if key in inputs and isinstance(inputs[key], int):
inputs[key] = seed
return nodes
def _run_comfy_workflow(args: argparse.Namespace) -> dict[str, Any]:
host = args.comfy_url.rstrip("/")
workflow = _load_comfy_workflow(args.workflow, host=host, timeout=args.request_timeout)
prompt = getattr(args, "prompt", None)
seed = getattr(args, "seed", None)
graph = _patch_comfy_workflow(workflow, prompt=prompt, seed=seed)
payload = json.dumps({"prompt": graph, "client_id": "modly-cli"}).encode("utf-8")
queued = _request_json("POST", f"{host}/prompt", timeout=args.request_timeout, data=payload, headers={"Content-Type": "application/json"})
prompt_id = queued.get("prompt_id") if isinstance(queued, dict) else None
if not prompt_id:
raise ModlyCliError(f"ComfyUI did not return prompt_id: {queued}")
deadline = time.monotonic() + args.timeout
history: dict[str, Any] = {}
while time.monotonic() < deadline:
data = _request_json("GET", f"{host}/history/{urllib.parse.quote(str(prompt_id))}", timeout=args.request_timeout)
if isinstance(data, dict) and str(prompt_id) in data:
history = data[str(prompt_id)] if isinstance(data[str(prompt_id)], dict) else {"raw": data[str(prompt_id)]}
break
if getattr(args, "progress", False) and not getattr(args, "quiet", False):
print(json.dumps({"phase": "comfy", "prompt_id": prompt_id, "status": "running"}), file=sys.stderr)
time.sleep(args.poll)
if not history:
raise ModlyCliError(f"Timed out waiting for ComfyUI prompt {prompt_id}", code="TIMEOUT")
return {"ok": True, "comfy_url": host, "workflow": args.workflow, "prompt_id": str(prompt_id), "history": history}
def _iter_comfy_file_refs(value: Any) -> list[dict[str, Any]]:
refs: list[dict[str, Any]] = []
if isinstance(value, dict):
filename = value.get("filename")
if isinstance(filename, str) and filename:
refs.append(value)
for child in value.values():
refs.extend(_iter_comfy_file_refs(child))
elif isinstance(value, list):
for child in value:
refs.extend(_iter_comfy_file_refs(child))
return refs
def _comfy_ref_suffix(ref: dict[str, Any]) -> str:
filename = str(ref.get("filename") or "")
return Path(urllib.parse.urlparse(filename).path).suffix.lower()
def _find_comfy_file_ref(history: dict[str, Any], suffixes: set[str]) -> dict[str, Any] | None:
outputs = history.get("outputs") if isinstance(history.get("outputs"), dict) else history
for ref in _iter_comfy_file_refs(outputs):
if _comfy_ref_suffix(ref) in suffixes:
return ref
return None
def _comfy_view_url(host: str, ref: dict[str, Any]) -> str:
query = urllib.parse.urlencode({
"filename": ref.get("filename", ""),
"subfolder": ref.get("subfolder", ""),
"type": ref.get("type", "output"),
})
return f"{host.rstrip('/')}/view?{query}"
def _download_comfy_ref(host: str, ref: dict[str, Any], dest: Path, *, timeout: float) -> int:
return _download(_comfy_view_url(host, ref), dest, timeout=timeout)
def _temp_path_for_comfy_ref(ref: dict[str, Any], *, default_suffix: str) -> Path:
suffix = _comfy_ref_suffix(ref) or default_suffix
tmp = tempfile.NamedTemporaryFile(delete=False, prefix="modly-comfy-", suffix=suffix)
tmp.close()
return Path(tmp.name)
def _download_comfy_image_output(args: argparse.Namespace, comfy: dict[str, Any]) -> dict[str, Any]:
host = str(comfy["comfy_url"])
prompt_id = str(comfy["prompt_id"])
history = comfy["history"] if isinstance(comfy.get("history"), dict) else {}
image_ref = _find_comfy_file_ref(history, IMAGE_SUFFIXES)
if not image_ref:
raise ModlyCliError(f"ComfyUI prompt {prompt_id} completed without a supported image output", code="NO_WORKFLOW_OUTPUT")
out_path: Path | None = getattr(args, "comfy_output", None)
if out_path:
out = Path(out_path).expanduser().resolve()
else:
out = _temp_path_for_comfy_ref(image_ref, default_suffix=".png")
bytes_written = _download_comfy_ref(host, image_ref, out, timeout=args.request_timeout)
return {
"ok": True,
"comfy_url": host,
"workflow": comfy["workflow"],
"prompt_id": prompt_id,
"image_path": str(out),
"bytes_written": bytes_written,
"image": image_ref,
}
def _run_comfy_image(args: argparse.Namespace) -> dict[str, Any]:
comfy = _run_comfy_workflow(args)
return _download_comfy_image_output(args, comfy)
def cmd_comfy_image(args: argparse.Namespace) -> int:
result = _run_comfy_image(args)
result["meta"] = {"experimental": True, "canonical": False}
_json_print(result, compact=args.compact)
return 0
def cmd_generate_from_workflow(args: argparse.Namespace) -> int:
comfy = _run_comfy_workflow(args)
host = str(comfy["comfy_url"])
prompt_id = str(comfy["prompt_id"])
history = comfy["history"] if isinstance(comfy.get("history"), dict) else {}
asset_ref = _find_comfy_file_ref(history, WORKFLOW_ASSET_SUFFIXES)
if asset_ref:
if not args.output:
raise ModlyCliError("--output is required when a workflow produces a direct 3D asset", code="OUTPUT_REQUIRED")
export_dest = Path(args.output).expanduser().resolve()
bytes_written = _download_comfy_ref(host, asset_ref, export_dest, timeout=args.request_timeout)
_json_print({
"ok": True,
"source": "comfy-workflow",
"output_type": "asset",
"export_path": str(export_dest),
"bytes_written": bytes_written,
"workflow": comfy["workflow"],
"prompt_id": prompt_id,
"comfy_url": host,
"asset": asset_ref,
"meta": {"experimental": True, "canonical": False},
}, compact=args.compact)
return 0
comfy_image = _download_comfy_image_output(args, comfy)
_require_health(args.base_url.rstrip("/"), args.request_timeout)
output = Path(args.output).expanduser().resolve() if args.output else None
result = _generate_one(args, Path(str(comfy_image["image_path"])), output)
result["source"] = "comfy-workflow"
result["output_type"] = "image"
result["comfy"] = comfy_image
result.setdefault("meta", {})["experimental"] = True
_json_print(result, compact=args.compact)
return 0
def _canonical_generation_params(args: argparse.Namespace) -> dict[str, Any]:
params = _parse_params(getattr(args, "params_json", None), getattr(args, "params_file", None))
params.setdefault("remesh", getattr(args, "remesh", "quad"))
params.setdefault("enable_texture", bool(getattr(args, "enable_texture", True)))
params.setdefault("texture_resolution", getattr(args, "texture_resolution", 1024))
return params
def _workflow_workspace_path(status: dict[str, Any]) -> str:
scene_candidate = status.get("scene_candidate")
if isinstance(scene_candidate, dict) and scene_candidate.get("workspace_path"):
return _validate_workspace_path(str(scene_candidate["workspace_path"]))
output_url = str(status.get("output_url") or "")
if output_url:
return _workspace_relative_path(output_url)
raise ModlyCliError(f"Workflow run completed without an output path: {status}", code="MISSING_OUTPUT")
def _start_workflow_run(args: argparse.Namespace, image_path: Path, *, base_url: str, model_id: str, params: dict[str, Any]) -> tuple[str, dict[str, Any]]:
fields = {
"model_id": model_id,
"params": json.dumps(params, separators=(",", ":")),
}
if getattr(args, "collection", None):
fields["collection"] = str(args.collection)
body, content_type = _multipart_form(fields, "image", image_path)
started = _request_json(
"POST",
f"{base_url}/workflow-runs/from-image",
timeout=args.request_timeout,
data=body,
headers={"Content-Type": content_type},
)
run_id = started.get("run_id") if isinstance(started, dict) else None
if not run_id:
raise ModlyCliError(f"Modly did not return a run_id: {started}", code="MISSING_RUN_ID")
return str(run_id), started if isinstance(started, dict) else {"raw": started}
def _poll_workflow_run(args: argparse.Namespace, *, base_url: str, run_id: str, progress_label: str = "workflow-run") -> tuple[dict[str, Any], str]:
deadline = time.monotonic() + args.timeout
last_status: dict[str, Any] = {}
while time.monotonic() < deadline:
status = _request_json("GET", f"{base_url}/workflow-runs/{urllib.parse.quote(str(run_id))}", timeout=args.request_timeout)
last_status = status if isinstance(status, dict) else {"raw": status}
state = last_status.get("status")
if state == "done":
return last_status, _workflow_workspace_path(last_status)
if state in {"error", "cancelled"}:
raise ModlyCliError(f"Workflow run {run_id} ended with status {state}: {last_status}", code="WORKFLOW_RUN_FAILED")
if getattr(args, "progress", False) and not getattr(args, "quiet", False):
progress = last_status.get("progress", 0)
step = last_status.get("step", "")
print(json.dumps({"phase": progress_label, "run_id": run_id, "status": state, "progress": progress, "step": step}), file=sys.stderr)
time.sleep(args.poll)
raise ModlyCliError(f"Timed out waiting for workflow run {run_id}. Last status: {last_status}", code="TIMEOUT")
def _run_workflow_run(
args: argparse.Namespace,
image_path: Path,
*,
base_url: str,
model_id: str,
params: dict[str, Any],
wait: bool,
) -> tuple[str, dict[str, Any], str | None]:
run_id, started = _start_workflow_run(args, image_path, base_url=base_url, model_id=model_id, params=params)
if not wait:
return run_id, started, None
status, rel_path = _poll_workflow_run(args, base_url=base_url, run_id=run_id)
return run_id, status, rel_path
def cmd_workflow_run_start(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
image_path = Path(args.image).expanduser().resolve()
if not image_path.exists() or not image_path.is_file():
raise ModlyCliError(f"image file not found: {image_path}", code="IMAGE_NOT_FOUND")
model_id = _resolve_model_id(args, base_url)
params = _canonical_generation_params(args)
run_id, status, rel_path = _run_workflow_run(args, image_path, base_url=base_url, model_id=model_id, params=params, wait=getattr(args, "wait", False))
payload: dict[str, Any] = {
"ok": True,
"base_url": base_url,
"image": str(image_path),
"model_id": model_id,
"run": {"kind": "workflowRun", "id": run_id},
"status": status,
"meta": _recovery_meta(base_url, run_id),
}
if rel_path:
payload["workspace_path"] = rel_path
_json_print(payload, compact=args.compact)
return 0
def cmd_workflow_run_status(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
status = _request_json("GET", f"{base_url}/workflow-runs/{urllib.parse.quote(args.run_id)}", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "run": {"kind": "workflowRun", "id": args.run_id}, "status": status, "meta": _recovery_meta(base_url, args.run_id)}, compact=args.compact)
return 0
def cmd_workflow_run_cancel(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
result = _request_json("POST", f"{base_url}/workflow-runs/{urllib.parse.quote(args.run_id)}/cancel", timeout=args.request_timeout)
_json_print({"ok": True, "base_url": base_url, "run": {"kind": "workflowRun", "id": args.run_id}, "cancel": result, "meta": _recovery_meta(base_url, args.run_id)}, compact=args.compact)
return 0
def _ensure_no_external_texture_process(args: argparse.Namespace) -> None:
if getattr(args, "texture_model", "auto") not in (None, "", "auto"):
raise _unsupported_process()
if getattr(args, "texture_params_json", None) or getattr(args, "texture_params_file", None):
raise _unsupported_process()
def _run_generation_job(
args: argparse.Namespace,
image_path: Path,
*,
base_url: str,
model_id: str,
params: dict[str, Any],
progress_label: str,
) -> tuple[str, dict[str, Any], str]:
fields = {
"model_id": model_id,
"collection": args.collection,
"remesh": args.remesh,
"enable_texture": "true" if getattr(args, "enable_texture", True) else "false",
"texture_resolution": str(getattr(args, "texture_resolution", 1024)),
"params": json.dumps(params, separators=(",", ":")),
}
body, content_type = _multipart_form(fields, "image", image_path)
started = _request_json(
"POST",
f"{base_url}/generate/from-image",
timeout=args.request_timeout,
data=body,
headers={"Content-Type": content_type},
)
job_id = started.get("job_id") if isinstance(started, dict) else None
if not job_id:
raise ModlyCliError(f"Modly did not return a job_id: {started}")
deadline = time.monotonic() + args.timeout
last_status: dict[str, Any] = {}
while time.monotonic() < deadline:
status = _request_json("GET", f"{base_url}/generate/status/{urllib.parse.quote(str(job_id))}", timeout=args.request_timeout)
last_status = status if isinstance(status, dict) else {"raw": status}
state = last_status.get("status")
if state == "done":
output_url = str(last_status.get("output_url") or "")
if not output_url:
raise ModlyCliError(f"Job completed without output_url: {last_status}")
return str(job_id), last_status, _workspace_relative_path(output_url)
if state in {"error", "cancelled"}:
raise ModlyCliError(f"Job {job_id} ended with status {state}: {last_status}")
if getattr(args, "progress", False) and not getattr(args, "quiet", False):
progress = last_status.get("progress", 0)
step = last_status.get("step", "")
print(json.dumps({"phase": progress_label, "job_id": job_id, "status": state, "progress": progress, "step": step}), file=sys.stderr)
time.sleep(args.poll)
raise ModlyCliError(f"Timed out waiting for job {job_id}. Last status: {last_status}")
def _generate_one(args: argparse.Namespace, image_path: Path, output_path: Path | None = None) -> dict[str, Any]:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
image_path = image_path.expanduser().resolve()
if not image_path.exists() or not image_path.is_file():
raise ModlyCliError(f"image file not found: {image_path}", code="IMAGE_NOT_FOUND")
_ensure_no_external_texture_process(args)
params = _canonical_generation_params(args)
model_id = _resolve_model_id(args, base_url)
run_id, status, rel_path = _run_workflow_run(
args,
image_path,
base_url=base_url,
model_id=model_id,
params=params,
wait=True,
)
assert rel_path is not None
export_dest = None
bytes_written = None
if not getattr(args, "no_export", False):
export_dest = output_path or image_path.resolve().parent / f"{Path(rel_path).stem}.{args.format}"
export_dest = export_dest.expanduser().resolve()
bytes_written = _export_workspace_path(base_url, rel_path, args.format, export_dest, timeout=args.request_timeout)
result: dict[str, Any] = {
"ok": True,
"base_url": base_url,
"image": str(image_path),
"model_id": model_id,
"run": {"kind": "workflowRun", "id": run_id},
"status": status,
"workspace_path": rel_path,
"texture_enabled": bool(params.get("enable_texture")),
"export_format": args.format,
"meta": _recovery_meta(base_url, run_id),
}
if export_dest is not None:
result["export_path"] = str(export_dest)
result["bytes_written"] = bytes_written
return result
def cmd_generate(args: argparse.Namespace) -> int:
output = Path(args.output).expanduser().resolve() if args.output else None
result = _generate_one(args, Path(args.image), output)
_json_print(result, compact=args.compact)
return 0
def cmd_legacy_generate(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
image_path = Path(args.image).expanduser().resolve()
if not image_path.exists() or not image_path.is_file():
raise ModlyCliError(f"image file not found: {image_path}", code="IMAGE_NOT_FOUND")
params = _parse_params(getattr(args, "params_json", None), getattr(args, "params_file", None))
model_id = _resolve_model_id(args, base_url)
job_id, status, rel_path = _run_generation_job(
args,
image_path,
base_url=base_url,
model_id=model_id,
params=params,
progress_label="legacy-generate",
)
export_dest = None
bytes_written = None
if not getattr(args, "no_export", False):
export_dest = Path(args.output).expanduser().resolve() if args.output else image_path.resolve().parent / f"{Path(rel_path).stem}.{args.format}"
bytes_written = _export_workspace_path(base_url, rel_path, args.format, export_dest, timeout=args.request_timeout)
payload: dict[str, Any] = {
"ok": True,
"base_url": base_url,
"image": str(image_path),
"model_id": model_id,
"job_id": job_id,
"status": status,
"workspace_path": rel_path,
"export_format": args.format,
"meta": _recovery_meta(base_url, job_id, legacy=True),
}
if export_dest is not None:
payload["export_path"] = str(export_dest)
payload["bytes_written"] = bytes_written
_json_print(payload, compact=args.compact)
return 0
def cmd_export(args: argparse.Namespace) -> int:
base_url = args.base_url.rstrip("/")
_require_health(base_url, args.request_timeout)
dest = Path(args.output).expanduser().resolve()
bytes_written = _export_workspace_path(base_url, args.path, args.format, dest, timeout=args.request_timeout)
_json_print({
"ok": True,
"base_url": base_url,
"workspace_path": args.path,
"export_format": args.format,
"export_path": str(dest),
"bytes_written": bytes_written,
}, compact=args.compact)
return 0
def _iter_images(input_dir: Path) -> list[Path]:
if not input_dir.exists() or not input_dir.is_dir():
raise ModlyCliError(f"input directory not found: {input_dir}")
return sorted(p for p in input_dir.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES)
def _manifest_jobs(path: Path, fallback_output_dir: Path | None, default_format: str) -> list[tuple[Path, Path | None, str]]:
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ModlyCliError(f"manifest must be valid JSON: {exc}") from exc
entries = raw.get("jobs", raw.get("images")) if isinstance(raw, dict) else raw
if not isinstance(entries, list):
raise ModlyCliError("manifest must be a JSON list or object with a jobs/images list")
jobs: list[tuple[Path, Path | None, str]] = []
for index, entry in enumerate(entries):
if isinstance(entry, str):
image = Path(entry)
fmt = default_format
output = None
elif isinstance(entry, dict):
image_value = entry.get("image") or entry.get("image_path") or entry.get("path")
if not image_value:
raise ModlyCliError(f"manifest entry {index} is missing image")
image = Path(str(image_value))