comfyui-backup / orchestrator /orchestrator.py
maroccasting's picture
Upload orchestrator/orchestrator.py
82680ef verified
Raw
History Blame Contribute Delete
13.1 kB
#!/usr/bin/env python3
"""
orchestrator.py — drives ComfyUI's REST API to generate a storyboard.
WHAT THIS DOES:
1. Reads shots.yaml (your storyboard, one block per shot)
2. Loads single_shot_template.json (the reusable ~43-node pipeline)
3. For each shot: overrides prompt text + character/location refs, submits
to ComfyUI's /prompt endpoint, waits for completion, moves to next shot
4. No canvas editing, no manual node clicking — fully automated
REQUIREMENTS:
pip install requests pyyaml --break-system-packages
USAGE:
# 1. Make sure ComfyUI is running (python main.py --listen 0.0.0.0 --port 8188)
# 2. Edit shots.yaml to add/change shots
# 3. Run:
python orchestrator.py
# Run only specific shots (comma-separated IDs):
python orchestrator.py --only B1_Jim_Seated_Table,B2_Jim_BarCounter_Facing
# Point at a different ComfyUI instance:
python orchestrator.py --host http://localhost:8188
"""
import argparse
import copy
import json
import sys
import time
from pathlib import Path
import requests
import yaml
# ============================================================================
# NODE ID MAP — which node in the template each field maps to
# (These IDs come from single_shot_template.json — don't change unless you
# re-extract the template from a different pipeline)
# ============================================================================
NODE = {
"pos": 20, # CLIPTextEncodeFlux POS (widgets: [clip_l, t5, guidance])
"neg": 21, # CLIPTextEncodeFlux NEG
"ipa": 23, # ApplyFluxIPAdapter (widgets: [weight])
"pulid_s1": 24, # ApplyPulidFlux Stage 1 (widgets: [weight, ...])
"cn_apply": 25, # ControlNetApplyAdvanced (widgets: [strength, start%, end%])
"face_pos": 35, # CLIPTextEncodeFlux face POS
"face_neg": 36, # CLIPTextEncodeFlux face NEG
"pulid_s2": 34, # ApplyPulidFlux Stage 2
"save_final": 39, # SaveImage FINAL (widgets: [filename_prefix])
"save_s1": 28, # SaveImage Stage1 (widgets: [filename_prefix])
}
# Reference image LoadImage nodes — keyed by character/location name
REF_NODE = {
"jim_body": 16,
"jim_face": 17,
"barbara_body": 18,
"barbara_face": 19,
}
# Which LoadImage node the ControlNetApplyAdvanced (id 25) should pull its
# depth image from, depending on shot['location']. The template has TWO
# depth preprocessors already wired (12=LOC1, 13=LOC2); we just need the
# CN Apply node's "image" INPUT to point at the correct one at submit time.
DEPTH_NODE = {"loc1": "12", "loc2": "13"}
DEFAULT_NEG = (
"low quality, bad anatomy, extra limbs, missing limbs, watermark, "
"blurry, deformed face, extra fingers, duplicate, ugly"
)
DEFAULT_FACE_NEG = "low quality, bad anatomy, blurry, deformed face"
def load_template(path: str) -> dict:
with open(path) as f:
return json.load(f)
def workflow_to_api_format(wf: dict) -> dict:
"""
Convert the UI-style workflow (nodes/links arrays, used for canvas display)
into the API prompt format ComfyUI's /prompt endpoint expects
(a flat dict of node_id -> {class_type, inputs}).
"""
link_map = {l[0]: l for l in wf["links"]}
api = {}
for n in wf["nodes"]:
node_id = str(n["id"])
inputs = {}
# Wire up input links
for i, inp in enumerate(n.get("inputs", [])):
lid = inp.get("link")
if lid is not None:
l = link_map[lid]
src_node, src_slot = l[1], l[2]
inputs[inp["name"]] = [str(src_node), src_slot]
# Wire up widget values (order matters — matches node's widget order)
widget_names = [i["name"] for i in n.get("inputs", []) if i.get("link") is None]
# Simpler: ComfyUI API expects widget values merged into inputs by name.
# We rely on the fact that widgets_values order matches the node's
# default widget schema — this works for all nodes used in this template.
wv = n.get("widgets_values", [])
# Map widget index -> input name using the node's *own* declared widget slots.
# ComfyUI stores this implicitly; for our known node types we hardcode below.
api[node_id] = {"class_type": n["type"], "inputs": inputs, "_widgets": wv}
return api
def apply_shot_overrides(wf: dict, shot: dict, char_registry: dict) -> dict:
"""Return a deep-copied workflow with this shot's values patched in."""
wf = copy.deepcopy(wf)
by_id = {n["id"]: n for n in wf["nodes"]}
char = shot["character"]
guidance = shot.get("guidance", 4.5)
neg_guidance = shot.get("neg_guidance", 3.5)
# ---- Prompts ----
by_id[NODE["pos"]]["widgets_values"] = [
shot["clip_l"].strip(), shot["t5"].strip(), guidance
]
by_id[NODE["neg"]]["widgets_values"] = [
"", shot.get("neg", DEFAULT_NEG), neg_guidance
]
by_id[NODE["face_pos"]]["widgets_values"] = [
shot["face_clip_l"].strip(), shot["face_t5"].strip(), guidance
]
by_id[NODE["face_neg"]]["widgets_values"] = [
"", shot.get("face_neg", DEFAULT_FACE_NEG), neg_guidance
]
# ---- Character reference images (IPA body ref + PuLID face ref) ----
body_ref_id = REF_NODE[f"{char}_body"]
face_ref_id = REF_NODE[f"{char}_face"]
body_fname = char_registry[char]["body_image"]
face_fname = char_registry[char]["face_image"]
by_id[body_ref_id]["widgets_values"] = [body_fname, "image"]
by_id[face_ref_id]["widgets_values"] = [face_fname, "image"]
# ---- IPA / PuLID weights (allow per-shot override, else registry default) ----
ipa_weight = shot.get("ipa_weight", char_registry[char].get("ipa_weight", 0.43))
by_id[NODE["ipa"]]["widgets_values"] = [ipa_weight]
pulid_s1_weight = shot.get("pulid_s1_weight", 0.85)
by_id[NODE["pulid_s1"]]["widgets_values"][0] = pulid_s1_weight
pulid_s2_weight = shot.get("pulid_s2_weight", 0.95)
by_id[NODE["pulid_s2"]]["widgets_values"][0] = pulid_s2_weight
# ---- ControlNet strength (allow per-shot override) ----
cn_strength = shot.get("cn_strength", 0.45)
cn_end = shot.get("cn_end", 0.65)
by_id[NODE["cn_apply"]]["widgets_values"] = [cn_strength, 0.0, cn_end]
# ---- Location routing: rewire ControlNetApplyAdvanced's image input ----
depth_node_id = int(DEPTH_NODE[shot["location"]])
cn_node = by_id[NODE["cn_apply"]]
# input[3] is "image" on ControlNetApplyAdvanced
for link in wf["links"]:
if link[3] == NODE["cn_apply"] and link[4] == 3:
link[1] = depth_node_id # rewire source node
link[2] = 0 # output slot 0 (IMAGE)
# ---- Output filenames ----
by_id[NODE["save_final"]]["widgets_values"] = [f"{shot['id']}_FINAL"]
by_id[NODE["save_s1"]]["widgets_values"] = [f"{shot['id']}_Stage1"]
return wf
def fetch_widget_schemas(host: str) -> dict:
"""
Fetch real widget name schemas from ComfyUI's /object_info endpoint.
This replaces the old hardcoded WIDGET_SCHEMA — it works regardless of
which version of custom nodes is installed, and handles ComfyUI's own
typos in node input names (e.g. 'ipadatper' in LoadFluxIPAdapter).
Widget inputs are those whose type is a primitive (STRING, INT, FLOAT,
BOOLEAN) or a combo list — as opposed to node connection types like
MODEL, CLIP, LATENT which are satisfied by links, not widget values.
"""
resp = requests.get(f"{host}/object_info", timeout=10)
resp.raise_for_status()
info = resp.json()
PRIMITIVE_TYPES = {"STRING", "INT", "FLOAT", "BOOLEAN"}
schemas = {}
for node_type, node_info in info.items():
widget_names = []
all_inputs = {}
all_inputs.update(node_info.get("input", {}).get("required", {}))
all_inputs.update(node_info.get("input", {}).get("optional", {}))
for name, spec in all_inputs.items():
if not spec:
continue
input_type = spec[0]
# Lists = combo boxes (widget); uppercase strings = node connections
if isinstance(input_type, list) or input_type in PRIMITIVE_TYPES:
widget_names.append(name)
schemas[node_type] = widget_names
return schemas
# Module-level schema cache — populated at startup by fetch_widget_schemas()
WIDGET_SCHEMA: dict = {}
# UI-only widget indices to skip when building the API payload.
# These values exist in the canvas widgets_values array but are NOT real
# node inputs — they're inserted by the ComfyUI frontend and absent from
# object_info. Keyed by node type, values are sets of indices to skip.
SKIP_WIDGET_INDICES: dict = {
"KSampler": {1}, # index 1 = "control_after_generate" (randomize/fixed)
"KSamplerAdvanced": {1, 4}, # same concept, two occurrences
}
def ui_workflow_to_prompt_payload(wf: dict) -> dict:
"""
Convert UI graph format to ComfyUI's API prompt dict format.
ComfyUI needs: {node_id: {"class_type": ..., "inputs": {name: value_or_link}}}
WIDGET_SCHEMA must be populated before calling this (done in main()).
"""
link_map = {l[0]: l for l in wf["links"]}
prompt = {}
for n in wf["nodes"]:
node_id = str(n["id"])
class_type = n["type"]
inputs = {}
# Linked inputs — satisfied by connections from other nodes
linked_names = set()
for inp in n.get("inputs", []):
lid = inp.get("link")
if lid is not None:
l = link_map[lid]
inputs[inp["name"]] = [str(l[1]), l[2]]
linked_names.add(inp["name"])
# Widget inputs — map widgets_values positionally onto widget names.
# SKIP_WIDGET_INDICES lists widgets_values positions that are UI-only
# (they exist in the canvas JSON but are NOT sent to the API).
# KSampler index 1 = "control_after_generate" (randomize/fixed) is a
# frontend-only widget absent from object_info — must be skipped here.
wv = n.get("widgets_values", [])
schema = WIDGET_SCHEMA.get(class_type, [])
skip = SKIP_WIDGET_INDICES.get(class_type, set())
wi = 0 # position in schema
for vi, val in enumerate(wv):
if vi in skip:
continue # skip UI-only value at this index
if wi >= len(schema):
break
name = schema[wi]
wi += 1
if name in linked_names:
continue # input satisfied by a link, not a widget
inputs[name] = val
prompt[node_id] = {"class_type": class_type, "inputs": inputs}
return prompt
def submit_and_wait(host: str, prompt_payload: dict, shot_id: str, timeout: int = 600):
"""Submit to ComfyUI /prompt and poll /history until this prompt completes."""
resp = requests.post(f"{host}/prompt", json={"prompt": prompt_payload})
resp.raise_for_status()
data = resp.json()
prompt_id = data["prompt_id"]
print(f" [{shot_id}] submitted, prompt_id={prompt_id}")
start = time.time()
while time.time() - start < timeout:
h = requests.get(f"{host}/history/{prompt_id}").json()
if prompt_id in h:
status = h[prompt_id].get("status", {})
if status.get("completed"):
print(f" [{shot_id}] done in {time.time()-start:.1f}s")
return h[prompt_id]
if status.get("status_str") == "error":
print(f" [{shot_id}] FAILED: {status}")
return None
time.sleep(3)
print(f" [{shot_id}] TIMEOUT after {timeout}s")
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="http://localhost:8188")
ap.add_argument("--shots", default="shots.yaml")
ap.add_argument("--template", default="single_shot_template.json")
ap.add_argument("--characters", default="characters.yaml")
ap.add_argument("--only", default=None,
help="Comma-separated shot IDs to run (default: all)")
args = ap.parse_args()
with open(args.characters) as f:
char_registry = yaml.safe_load(f)
with open(args.shots) as f:
shots = yaml.safe_load(f)
template = load_template(args.template)
if args.only:
wanted = set(args.only.split(","))
shots = [s for s in shots if s["id"] in wanted]
# Fetch real widget schemas from the live ComfyUI instance
global WIDGET_SCHEMA
print(f"Fetching node schemas from {args.host} ...")
WIDGET_SCHEMA = fetch_widget_schemas(args.host)
print(f" got schemas for {len(WIDGET_SCHEMA)} node types\n")
print(f"Running {len(shots)} shot(s) against {args.host}\n")
for shot in shots:
wf = apply_shot_overrides(template, shot, char_registry)
prompt_payload = ui_workflow_to_prompt_payload(wf)
submit_and_wait(args.host, prompt_payload, shot["id"])
print("\nAll shots submitted.")
if __name__ == "__main__":
main()