run_workflow.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. #!/usr/bin/env python3
  2. """
  3. run_workflow.py — Inject parameters into a ComfyUI workflow, submit it, monitor
  4. execution, and download outputs.
  5. Improvements over v1:
  6. - Cloud-aware URL routing (handles /api prefix and /history_v2 / /experiment/models renames)
  7. - API key from CLI flag OR $COMFY_CLOUD_API_KEY env var
  8. - WebSocket progress monitoring (--ws), with HTTP polling fallback
  9. - Streaming download (no whole-file buffering — handles GB-size video outputs)
  10. - Path-traversal-safe output writes
  11. - Subfolder-aware download paths (no silent overwrites)
  12. - Retry with exponential backoff on transient errors
  13. - Status-error correctly classified before "completed: true"
  14. - Image upload helper (--input-image NAME=PATH)
  15. - Auto-randomize seed when value is -1 or omitted on a randomize-seed flag
  16. - Auto-extends timeout heuristically for video workflows
  17. - Editor-format detection with helpful error
  18. - Doesn't pollute extra_data.api_key_comfy_org with the cloud auth key
  19. unless --partner-key is provided (correct semantic per cloud docs)
  20. Usage:
  21. # Local server
  22. python3 run_workflow.py --workflow workflow_api.json \
  23. --args '{"prompt": "a cat", "seed": 42}' \
  24. --output-dir ./outputs
  25. # Cloud server (API key from env var)
  26. export COMFY_CLOUD_API_KEY="comfyui-xxxxxxx"
  27. python3 run_workflow.py --workflow workflow_api.json \
  28. --args '{"prompt": "a cat"}' \
  29. --host https://cloud.comfy.org \
  30. --output-dir ./outputs
  31. # With image input (auto-uploads, then references)
  32. python3 run_workflow.py --workflow img2img.json \
  33. --input-image image=./photo.png \
  34. --args '{"prompt": "make it cyberpunk"}'
  35. # WebSocket real-time progress
  36. python3 run_workflow.py --workflow flux_dev.json \
  37. --args '{"prompt": "..."}' \
  38. --ws
  39. Stdlib-only by default (Python 3.10+). Will use `requests`/`websocket-client`
  40. if installed for nicer behavior.
  41. """
  42. from __future__ import annotations
  43. import argparse
  44. import copy
  45. import json
  46. import sys
  47. import time
  48. from pathlib import Path
  49. from typing import Any
  50. from urllib.parse import urlencode, urlparse
  51. # Local import — _common.py sits next to this script.
  52. sys.path.insert(0, str(Path(__file__).resolve().parent))
  53. from _common import (
  54. DEFAULT_LOCAL_HOST, ENV_API_KEY,
  55. coerce_seed, emit_json, http_get, http_post, http_request,
  56. is_cloud_host, is_link, log, looks_like_video_workflow,
  57. media_type_from_filename, new_client_id, resolve_api_key, resolve_url,
  58. safe_path_join, unwrap_workflow,
  59. )
  60. # =============================================================================
  61. # Runner
  62. # =============================================================================
  63. class WorkflowRunError(Exception):
  64. """Raised when a workflow run fails (validation, execution, timeout)."""
  65. def __init__(self, status: str, message: str, **details: Any):
  66. super().__init__(message)
  67. self.status = status
  68. self.message = message
  69. self.details = details
  70. def to_dict(self) -> dict:
  71. d = {"status": self.status, "error": self.message}
  72. d.update(self.details)
  73. return d
  74. class ComfyRunner:
  75. def __init__(
  76. self,
  77. host: str = DEFAULT_LOCAL_HOST,
  78. api_key: str | None = None,
  79. client_id: str | None = None,
  80. partner_key: str | None = None,
  81. ):
  82. self.host = host.rstrip("/")
  83. self.api_key = api_key
  84. self.partner_key = partner_key
  85. self.is_cloud = is_cloud_host(self.host)
  86. self.client_id = client_id or new_client_id()
  87. @property
  88. def headers(self) -> dict[str, str]:
  89. h: dict[str, str] = {}
  90. if self.api_key:
  91. h["X-API-Key"] = self.api_key
  92. return h
  93. def _url(self, path: str) -> str:
  94. return resolve_url(self.host, path, is_cloud=self.is_cloud)
  95. # ---------- server health ----------
  96. def check_server(self) -> tuple[bool, dict | None]:
  97. try:
  98. r = http_get(self._url("/system_stats"), headers=self.headers, retries=2)
  99. if r.status == 200:
  100. try:
  101. return True, r.json()
  102. except Exception:
  103. return True, None
  104. return False, {"http_status": r.status, "body": r.text()[:500]}
  105. except Exception as e:
  106. return False, {"error": str(e)}
  107. # ---------- upload ----------
  108. def upload_image(self, path: Path, *, image_type: str = "input", overwrite: bool = True,
  109. endpoint: str = "/upload/image", extra_form: dict | None = None) -> dict:
  110. """Upload an image file via multipart. Returns server-side ref dict."""
  111. if not path.exists():
  112. raise FileNotFoundError(f"input image not found: {path}")
  113. # Stream the file via a handle to avoid OOM on huge inputs (16MP+ photos).
  114. with path.open("rb") as fh:
  115. files = {"image": (path.name, fh)}
  116. form = {"type": image_type}
  117. if overwrite:
  118. form["overwrite"] = "true"
  119. if extra_form:
  120. form.update({k: str(v) for k, v in extra_form.items()})
  121. r = http_request(
  122. "POST", self._url(endpoint),
  123. headers=self.headers, files=files, form=form,
  124. timeout=300, retries=2,
  125. )
  126. if r.status != 200:
  127. raise WorkflowRunError(
  128. "upload_failed",
  129. f"Upload of {path.name} failed: HTTP {r.status}",
  130. body=r.text()[:500],
  131. )
  132. try:
  133. return r.json()
  134. except Exception:
  135. return {"name": path.name}
  136. def upload_mask(self, path: Path, original_ref: dict) -> dict:
  137. """Upload an inpaint mask, linked to a previously uploaded source image.
  138. `original_ref` should be the dict returned by `upload_image()` for the
  139. source image (or `{"filename": ..., "subfolder": ..., "type": "input"}`).
  140. """
  141. return self.upload_image(
  142. path,
  143. endpoint="/upload/mask",
  144. extra_form={
  145. "subfolder": "clipspace",
  146. "original_ref": json.dumps(original_ref),
  147. },
  148. )
  149. # ---------- submit ----------
  150. def submit(self, workflow: dict) -> dict:
  151. payload: dict[str, Any] = {"prompt": workflow, "client_id": self.client_id}
  152. if self.partner_key:
  153. payload["extra_data"] = {"api_key_comfy_org": self.partner_key}
  154. r = http_post(self._url("/prompt"), headers=self.headers, json_body=payload, timeout=120)
  155. try:
  156. body = r.json()
  157. except Exception:
  158. body = {"raw": r.text()[:500]}
  159. if r.status != 200:
  160. return {"_http_error": r.status, "body": body}
  161. return body
  162. # ---------- HTTP polling ----------
  163. def poll_status(self, prompt_id: str, *, timeout: float = 300.0,
  164. initial_interval: float = 1.5, max_interval: float = 8.0) -> dict:
  165. start = time.time()
  166. interval = initial_interval
  167. while time.time() - start < timeout:
  168. if self.is_cloud:
  169. r = http_get(
  170. self._url(f"/job/{prompt_id}/status"),
  171. headers=self.headers, retries=2, timeout=30,
  172. )
  173. if r.status == 200:
  174. try:
  175. data = r.json()
  176. except Exception:
  177. data = {}
  178. s = data.get("status")
  179. if s == "completed":
  180. return {"status": "success", "data": data}
  181. if s in {"failed",}:
  182. return {"status": "error", "data": data}
  183. if s == "cancelled":
  184. return {"status": "cancelled", "data": data}
  185. # pending / in_progress → continue
  186. elif r.status == 404:
  187. # Cloud sometimes 404s briefly between submit and dispatcher pickup
  188. pass
  189. else:
  190. # transient error — retry loop covers it
  191. pass
  192. else:
  193. # Local: /history/{id} grows once execution completes
  194. r = http_get(
  195. self._url(f"/history/{prompt_id}"),
  196. headers=self.headers, retries=2, timeout=30,
  197. )
  198. if r.status == 200:
  199. try:
  200. data = r.json() or {}
  201. except Exception:
  202. data = {}
  203. entry = data.get(prompt_id)
  204. if isinstance(entry, dict):
  205. st = entry.get("status") or {}
  206. # IMPORTANT: check error first — `completed: true` can coexist with errors
  207. status_str = st.get("status_str")
  208. if status_str == "error":
  209. return {"status": "error", "data": entry}
  210. if st.get("completed", False):
  211. return {"status": "success", "outputs": entry.get("outputs", {})}
  212. # not in history yet → continue polling
  213. time.sleep(interval)
  214. interval = min(max_interval, interval * 1.4)
  215. return {"status": "timeout", "elapsed": time.time() - start}
  216. # ---------- WebSocket monitoring ----------
  217. def monitor_ws(self, prompt_id: str, *, timeout: float = 300.0,
  218. on_progress: Any = None) -> dict:
  219. """Connect to /ws and listen until execution_success / execution_error.
  220. Falls back to HTTP polling if `websocket-client` is not installed.
  221. Returns same shape as poll_status.
  222. """
  223. try:
  224. import websocket # type: ignore[import-not-found]
  225. except ImportError:
  226. log("websocket-client not installed; falling back to HTTP polling")
  227. return self.poll_status(prompt_id, timeout=timeout)
  228. # Build WS URL. Preserve any base-path components the user gave us
  229. # (e.g. http://example.com/comfyui → ws://example.com/comfyui/ws).
  230. parsed = urlparse(self.host)
  231. scheme = "wss" if parsed.scheme == "https" else "ws"
  232. netloc = parsed.netloc
  233. base_path = parsed.path.rstrip("/")
  234. ws_url = f"{scheme}://{netloc}{base_path}/ws?clientId={self.client_id}"
  235. if self.is_cloud and self.api_key:
  236. ws_url += f"&token={self.api_key}"
  237. outputs: dict[str, Any] = {}
  238. error_payload: dict[str, Any] | None = None
  239. success = False
  240. seen_executed = False
  241. ws = websocket.create_connection(ws_url, timeout=timeout)
  242. try:
  243. ws.settimeout(timeout)
  244. deadline = time.time() + timeout
  245. while time.time() < deadline:
  246. msg = ws.recv()
  247. if isinstance(msg, bytes):
  248. # Binary preview frame — ignore for now; ws_monitor.py prints them
  249. continue
  250. try:
  251. payload = json.loads(msg)
  252. except Exception:
  253. continue
  254. mtype = payload.get("type", "")
  255. mdata = payload.get("data", {}) or {}
  256. # Filter to our job (cloud broadcasts; local filters via client_id)
  257. pid = mdata.get("prompt_id")
  258. if pid is not None and pid != prompt_id:
  259. continue
  260. if mtype == "progress":
  261. if callable(on_progress):
  262. on_progress({
  263. "type": "progress",
  264. "value": mdata.get("value"),
  265. "max": mdata.get("max"),
  266. "node": mdata.get("node"),
  267. })
  268. elif mtype == "progress_state":
  269. if callable(on_progress):
  270. on_progress({"type": "progress_state", "nodes": mdata.get("nodes", {})})
  271. elif mtype == "executing":
  272. node = mdata.get("node")
  273. if callable(on_progress):
  274. on_progress({"type": "executing", "node": node})
  275. # When `node` is None on a local server, that signals end-of-run
  276. if node is None and not self.is_cloud and seen_executed:
  277. success = True
  278. break
  279. elif mtype == "executed":
  280. seen_executed = True
  281. nid = mdata.get("node")
  282. out = mdata.get("output") or {}
  283. if nid:
  284. outputs[nid] = out
  285. elif mtype == "notification":
  286. if callable(on_progress):
  287. on_progress({"type": "notification", "message": mdata.get("value", "")})
  288. elif mtype == "execution_success":
  289. success = True
  290. break
  291. elif mtype == "execution_error":
  292. error_payload = mdata
  293. break
  294. elif mtype == "execution_interrupted":
  295. error_payload = {"interrupted": True, **mdata}
  296. break
  297. finally:
  298. try:
  299. ws.close()
  300. except Exception:
  301. pass
  302. if error_payload is not None:
  303. return {"status": "error", "data": error_payload}
  304. if success:
  305. return {"status": "success", "outputs": outputs}
  306. return {"status": "timeout", "elapsed": timeout}
  307. # ---------- outputs ----------
  308. def get_outputs(self, prompt_id: str) -> dict:
  309. if self.is_cloud:
  310. # Try /jobs/{id} first (returns full job with outputs); fall back to /history_v2
  311. r = http_get(self._url(f"/jobs/{prompt_id}"), headers=self.headers, retries=2)
  312. if r.status == 200:
  313. try:
  314. return (r.json() or {}).get("outputs", {}) or {}
  315. except Exception:
  316. pass
  317. # Fallback
  318. r = http_get(self._url(f"/history/{prompt_id}"), headers=self.headers, retries=2)
  319. if r.status == 200:
  320. try:
  321. body = r.json() or {}
  322. except Exception:
  323. body = {}
  324. if isinstance(body, dict) and prompt_id in body:
  325. return body[prompt_id].get("outputs", {}) or {}
  326. if isinstance(body, dict) and "outputs" in body:
  327. return body["outputs"] or {}
  328. return {}
  329. # Local
  330. r = http_get(self._url(f"/history/{prompt_id}"), headers=self.headers, retries=2)
  331. if r.status != 200:
  332. return {}
  333. try:
  334. body = r.json() or {}
  335. except Exception:
  336. return {}
  337. entry = body.get(prompt_id) or {}
  338. return entry.get("outputs", {}) or {}
  339. def download_output(
  340. self, *, filename: str, subfolder: str, file_type: str,
  341. output_dir: Path, preserve_subfolder: bool = True, overwrite: bool = False,
  342. ) -> Path:
  343. """Stream a single output to disk. Path-traversal-safe."""
  344. params = {"filename": filename, "subfolder": subfolder, "type": file_type}
  345. url = self._url("/view") + "?" + urlencode(params)
  346. # Compute target path safely. If preserve_subfolder, include subfolder in the
  347. # local path; otherwise put the file in output_dir flat.
  348. target_parts: list[str] = []
  349. if preserve_subfolder and subfolder:
  350. target_parts.extend(p for p in subfolder.split("/") if p and p not in {".", ".."})
  351. target_parts.append(filename)
  352. out_path = safe_path_join(output_dir, *target_parts)
  353. if out_path.exists() and not overwrite:
  354. stem, suffix = out_path.stem, out_path.suffix
  355. i = 1
  356. while True:
  357. candidate = out_path.with_name(f"{stem}_{i}{suffix}")
  358. if not candidate.exists():
  359. out_path = candidate
  360. break
  361. i += 1
  362. out_path.parent.mkdir(parents=True, exist_ok=True)
  363. # Stream download. Two-step for cloud: get the 302, then fetch signed URL
  364. # so we don't accidentally send X-API-Key to the storage backend.
  365. # The HTTP transport already strips X-API-Key on cross-host redirect
  366. # via _strip_api_key_on_redirect, so a single follow_redirects=True call
  367. # is safe AND simpler.
  368. r = http_request(
  369. "GET", url, headers=self.headers,
  370. timeout=600, retries=3, follow_redirects=True,
  371. stream=True, sink=out_path,
  372. )
  373. if r.status != 200:
  374. try:
  375. if out_path.exists():
  376. out_path.unlink()
  377. except Exception:
  378. pass
  379. raise WorkflowRunError(
  380. "download_failed",
  381. f"Download of {filename} failed: HTTP {r.status}",
  382. url=url,
  383. )
  384. return out_path
  385. # ---------- queue / cancel ----------
  386. def cancel(self, prompt_id: str | None = None) -> bool:
  387. if prompt_id:
  388. r = http_post(
  389. self._url("/queue"), headers=self.headers,
  390. json_body={"delete": [prompt_id]}, retries=1,
  391. )
  392. return r.status == 200
  393. # Interrupt currently running
  394. r = http_post(self._url("/interrupt"), headers=self.headers, retries=1)
  395. return r.status == 200
  396. # =============================================================================
  397. # Schema / parameter injection
  398. # =============================================================================
  399. def _inline_schema(workflow: dict) -> dict:
  400. """Generate schema using the sibling extract_schema module."""
  401. from extract_schema import extract_schema # noqa: WPS433
  402. return extract_schema(workflow)
  403. def load_schema(schema_path: str | None, workflow: dict) -> dict:
  404. if schema_path:
  405. with open(schema_path, encoding="utf-8-sig") as f:
  406. return json.load(f)
  407. return _inline_schema(workflow)
  408. def inject_params(
  409. workflow: dict, schema: dict, args: dict,
  410. *, randomize_seed_if_unset: bool = False,
  411. ) -> tuple[dict, list[str]]:
  412. """Inject user args into the workflow. Returns (new_workflow, warnings)."""
  413. wf = copy.deepcopy(workflow)
  414. params = schema.get("parameters", {}) or {}
  415. warnings: list[str] = []
  416. # Auto-randomize seed when it's -1 in args, or when randomize_seed_if_unset
  417. # and user didn't pass a seed.
  418. if "seed" in params:
  419. if "seed" in args and args["seed"] in {None, -1, "-1"}:
  420. args = dict(args)
  421. args["seed"] = coerce_seed(args["seed"])
  422. warnings.append(f"seed=-1 expanded to {args['seed']}")
  423. elif randomize_seed_if_unset and "seed" not in args:
  424. args = dict(args)
  425. args["seed"] = coerce_seed(None)
  426. warnings.append(f"seed auto-randomized to {args['seed']}")
  427. for name, value in args.items():
  428. if name not in params:
  429. warnings.append(f"unknown parameter '{name}' (not in schema), skipping")
  430. continue
  431. m = params[name]
  432. nid, field = m["node_id"], m["field"]
  433. node = wf.get(nid)
  434. if not isinstance(node, dict) or "inputs" not in node:
  435. warnings.append(f"node '{nid}' for parameter '{name}' missing in workflow")
  436. continue
  437. # Refuse to overwrite a link with a literal — would silently break wiring
  438. cur = node["inputs"].get(field)
  439. if is_link(cur):
  440. warnings.append(
  441. f"parameter '{name}' targets {nid}.{field} which is currently a link; "
  442. f"refusing to overwrite (set the schema to point at the source node instead)"
  443. )
  444. continue
  445. node["inputs"][field] = value
  446. return wf, warnings
  447. # =============================================================================
  448. # Output download helper
  449. # =============================================================================
  450. def download_outputs(
  451. runner: ComfyRunner, outputs: dict, output_dir: Path,
  452. *, preserve_subfolder: bool = True, overwrite: bool = False,
  453. ) -> list[dict]:
  454. """Walk the outputs dict and download every file. Cloud uses `video` (singular);
  455. local uses `videos` (plural). We accept both."""
  456. output_dir.mkdir(parents=True, exist_ok=True)
  457. downloaded: list[dict] = []
  458. OUTPUT_KEYS = ("images", "gifs", "videos", "video", "audio", "files", "models", "3d")
  459. for node_id, node_output in (outputs or {}).items():
  460. if not isinstance(node_output, dict):
  461. continue
  462. for key in OUTPUT_KEYS:
  463. entries = node_output.get(key)
  464. if not entries:
  465. continue
  466. if not isinstance(entries, list):
  467. entries = [entries]
  468. for fi in entries:
  469. if not isinstance(fi, dict):
  470. continue
  471. filename = fi.get("filename") or ""
  472. if not filename:
  473. continue
  474. subfolder = fi.get("subfolder") or ""
  475. file_type = fi.get("type") or "output"
  476. try:
  477. out_path = runner.download_output(
  478. filename=filename, subfolder=subfolder, file_type=file_type,
  479. output_dir=output_dir, preserve_subfolder=preserve_subfolder,
  480. overwrite=overwrite,
  481. )
  482. downloaded.append({
  483. "file": str(out_path),
  484. "node_id": node_id,
  485. "type": media_type_from_filename(filename),
  486. "filename": filename,
  487. "subfolder": subfolder,
  488. "source_type": file_type,
  489. })
  490. except Exception as e:
  491. log(f"WARN: failed to download {filename}: {e}")
  492. return downloaded
  493. # =============================================================================
  494. # CLI
  495. # =============================================================================
  496. def parse_input_image_arg(spec: str) -> tuple[str, Path]:
  497. """Parse `name=path` (or `path` alone, defaulting to name='image')."""
  498. if "=" in spec:
  499. name, path = spec.split("=", 1)
  500. return name.strip(), Path(path).expanduser()
  501. return "image", Path(spec).expanduser()
  502. def main(argv: list[str] | None = None) -> int:
  503. p = argparse.ArgumentParser(
  504. description="Run a ComfyUI workflow with parameter injection.",
  505. formatter_class=argparse.RawDescriptionHelpFormatter,
  506. )
  507. p.add_argument("--workflow", required=True, help="Path to workflow API JSON file")
  508. p.add_argument("--args", default="{}",
  509. help="JSON parameters to inject (or `@/path/to/args.json`)")
  510. p.add_argument("--schema", help="Path to schema JSON (auto-generated if omitted)")
  511. p.add_argument("--host", default=DEFAULT_LOCAL_HOST, help="ComfyUI server URL")
  512. p.add_argument("--api-key",
  513. help=f"API key for cloud (or set ${ENV_API_KEY} env var)")
  514. p.add_argument("--partner-key",
  515. help="Partner-node API key (extra_data.api_key_comfy_org). "
  516. "Required for Flux Pro / Ideogram / etc. Defaults to --api-key if not set.")
  517. p.add_argument("--output-dir", default="./outputs", help="Directory to save outputs")
  518. p.add_argument("--timeout", type=int, default=0,
  519. help="Max seconds to wait (0=auto: 300 / 900 for video workflows)")
  520. p.add_argument("--input-image", action="append", default=[],
  521. help="Upload local image before running. Format: `name=path` or `path`. "
  522. "The `name` becomes the value injected into the matching schema parameter.")
  523. p.add_argument("--randomize-seed", action="store_true",
  524. help="If schema has a 'seed' parameter and --args didn't set one, randomize it")
  525. p.add_argument("--ws", action="store_true",
  526. help="Use WebSocket for real-time progress (requires `websocket-client`)")
  527. p.add_argument("--no-download", action="store_true", help="Skip downloading outputs")
  528. p.add_argument("--flat-output", action="store_true",
  529. help="Don't preserve server-side subfolder structure when saving outputs")
  530. p.add_argument("--overwrite", action="store_true",
  531. help="Overwrite existing files instead of appending _1, _2, ...")
  532. p.add_argument("--submit-only", action="store_true",
  533. help="Submit and return prompt_id without waiting")
  534. p.add_argument("--client-id", help="Override generated client_id (UUID)")
  535. p.add_argument("--use-partner-key-as-auth", action="store_true",
  536. help="(Compat) Use --partner-key value as cloud X-API-Key. Don't use unless you know why.")
  537. args = p.parse_args(argv)
  538. # ---- Load workflow ----
  539. wf_path = Path(args.workflow).expanduser()
  540. if not wf_path.exists():
  541. emit_json({"error": f"Workflow file not found: {args.workflow}"})
  542. return 1
  543. try:
  544. with wf_path.open(encoding="utf-8-sig") as f:
  545. workflow_raw = json.load(f)
  546. workflow = unwrap_workflow(workflow_raw)
  547. except ValueError as e:
  548. emit_json({"error": str(e)})
  549. return 1
  550. except json.JSONDecodeError as e:
  551. emit_json({"error": f"Invalid JSON in workflow file: {e}"})
  552. return 1
  553. # ---- Parse user args ----
  554. args_str = args.args
  555. if args_str.startswith("@"):
  556. try:
  557. args_str = Path(args_str[1:]).read_text(encoding="utf-8")
  558. except OSError as e:
  559. emit_json({"error": f"Cannot read args file: {e}"})
  560. return 1
  561. try:
  562. user_args = json.loads(args_str) if args_str.strip() else {}
  563. except json.JSONDecodeError as e:
  564. emit_json({"error": f"Invalid --args JSON: {e}"})
  565. return 1
  566. if not isinstance(user_args, dict):
  567. emit_json({"error": "--args must be a JSON object"})
  568. return 1
  569. # ---- Resolve API key ----
  570. api_key = resolve_api_key(args.api_key)
  571. partner_key = args.partner_key or None
  572. if args.use_partner_key_as_auth and not api_key and partner_key:
  573. api_key = partner_key
  574. # ---- Connect ----
  575. runner = ComfyRunner(
  576. host=args.host, api_key=api_key, partner_key=partner_key,
  577. client_id=args.client_id,
  578. )
  579. # Server reachability
  580. ok, info = runner.check_server()
  581. if not ok:
  582. emit_json({
  583. "error": f"Cannot reach server at {args.host}",
  584. "details": info,
  585. "hint": (
  586. "Check `comfy launch --background` is running for local, "
  587. f"or set ${ENV_API_KEY} for cloud."
  588. ),
  589. })
  590. return 1
  591. # ---- Upload input images ----
  592. upload_warnings: list[str] = []
  593. for spec in args.input_image:
  594. try:
  595. param_name, path = parse_input_image_arg(spec)
  596. except Exception as e:
  597. emit_json({"error": f"Bad --input-image spec '{spec}': {e}"})
  598. return 1
  599. try:
  600. ref = runner.upload_image(path)
  601. except Exception as e:
  602. emit_json({"error": f"Upload failed for {path}: {e}"})
  603. return 1
  604. # Register as a user arg so inject_params consumes it through the schema
  605. uploaded_name = ref.get("name") or path.name
  606. if param_name not in user_args:
  607. user_args[param_name] = uploaded_name
  608. # ---- Inject params ----
  609. schema = load_schema(args.schema, workflow)
  610. workflow, inj_warnings = inject_params(
  611. workflow, schema, user_args, randomize_seed_if_unset=args.randomize_seed,
  612. )
  613. warnings = upload_warnings + inj_warnings
  614. for w in warnings:
  615. log(f"WARN: {w}")
  616. # ---- Submit ----
  617. submit_resp = runner.submit(workflow)
  618. if "_http_error" in submit_resp:
  619. emit_json({
  620. "error": "Submission HTTP error",
  621. "http_status": submit_resp["_http_error"],
  622. "body": submit_resp.get("body"),
  623. })
  624. return 1
  625. if isinstance(submit_resp.get("error"), dict):
  626. emit_json({
  627. "error": "Workflow validation failed",
  628. "details": submit_resp["error"],
  629. "node_errors": submit_resp.get("node_errors"),
  630. })
  631. return 1
  632. prompt_id = submit_resp.get("prompt_id")
  633. if not prompt_id:
  634. emit_json({"error": "No prompt_id in submit response", "response": submit_resp})
  635. return 1
  636. node_errors = submit_resp.get("node_errors") or {}
  637. if node_errors:
  638. emit_json({"error": "Workflow validation failed", "node_errors": node_errors})
  639. return 1
  640. if args.submit_only:
  641. emit_json({"status": "submitted", "prompt_id": prompt_id, "warnings": warnings})
  642. return 0
  643. # ---- Wait ----
  644. timeout = args.timeout
  645. if timeout <= 0:
  646. timeout = 900 if looks_like_video_workflow(workflow) else 300
  647. log(f"Submitted: prompt_id={prompt_id}, waiting (timeout={timeout}s)…")
  648. def _on_progress(evt: dict) -> None:
  649. t = evt.get("type")
  650. if t == "progress":
  651. log(f" step {evt.get('value')}/{evt.get('max')} on node {evt.get('node')}")
  652. elif t == "executing":
  653. node = evt.get("node")
  654. if node:
  655. log(f" executing node {node}")
  656. try:
  657. if args.ws:
  658. wait_result = runner.monitor_ws(prompt_id, timeout=timeout, on_progress=_on_progress)
  659. else:
  660. wait_result = runner.poll_status(prompt_id, timeout=timeout)
  661. except KeyboardInterrupt:
  662. log(f"Interrupted — cancelling job {prompt_id} on server…")
  663. try:
  664. runner.cancel(prompt_id)
  665. except Exception as e:
  666. log(f" (cancel request failed: {e})")
  667. emit_json({
  668. "status": "interrupted",
  669. "prompt_id": prompt_id,
  670. "note": "Ctrl+C received; sent cancellation to server.",
  671. })
  672. return 130
  673. if wait_result["status"] == "timeout":
  674. emit_json({
  675. "status": "timeout",
  676. "prompt_id": prompt_id,
  677. "elapsed": wait_result.get("elapsed"),
  678. "hint": "Re-run with larger --timeout, or use --submit-only and check later.",
  679. })
  680. return 1
  681. if wait_result["status"] == "error":
  682. emit_json({"status": "error", "prompt_id": prompt_id, "details": wait_result.get("data")})
  683. return 1
  684. if wait_result["status"] == "cancelled":
  685. emit_json({"status": "cancelled", "prompt_id": prompt_id})
  686. return 1
  687. # ---- Outputs ----
  688. outputs = wait_result.get("outputs")
  689. if not outputs:
  690. outputs = runner.get_outputs(prompt_id)
  691. if args.no_download:
  692. emit_json({
  693. "status": "success", "prompt_id": prompt_id,
  694. "outputs": outputs, "warnings": warnings,
  695. })
  696. return 0
  697. downloaded = download_outputs(
  698. runner, outputs, Path(args.output_dir).expanduser(),
  699. preserve_subfolder=not args.flat_output, overwrite=args.overwrite,
  700. )
  701. emit_json({
  702. "status": "success",
  703. "prompt_id": prompt_id,
  704. "outputs": downloaded,
  705. "warnings": warnings,
  706. })
  707. return 0
  708. if __name__ == "__main__":
  709. sys.exit(main())