How To Execute Workflows via ComfyUI API Calls for stable diffusion

Spread the love
(Last Updated On: August 24, 2023)

 

How To Execute Workflows via ComfyUI API Calls for stable diffusion? Pretty simple with a bit of Python script. The example in this post can be found on Gist. To call a workflow, simply export is as API format, then execute Python with the script and some parameters.

 

Quick Start to Execute a workflow via API Call

  1. Requisites: Get the script api_comfyui-img2img.py and save your workflow in API format.
python api_comfyui-img2img.py -w <path>\ComfyUI-workflow-recolor-api.json -i <path>\image-grey.jpg -o outputPrefix

 

Detailed Steps to execute a workflow via ComfyUI API Call

Pre-requisites:

  • Install ComfyUI-Manager
    1. cd ComfyUI\custom_nodes\ && git clone https://github.com/ltdrdata/ComfyUI-Manager
    2. Restart ComfyUI

 

  1. Install ComfyUI-Custom-Scripts:
    1. In the Manager, select Install Custom Nodes:
      ComfyUI Manager install custom Nodes
    2. Then search for Custom-Scripts and Install
      ComfyUI Manager install Custom-Scripts
    3. alternatively via command line: cd ComfyUI\custom_nodes\ && git clone https://github.com/pythongosssss/ComfyUI-Custom-Scripts
    4. Restart ComfyUI
  2. enable dev mode options:
    ComfyUI Manager enable dev mode options
  3. Build your workflow then save workflow in API format:
    ComfyUI Save API format
  4. execute python api_comfyui-img2img.py -w <path>\ComfyUI-workflow-recolor-api.json -i <path>\image-grey.jpg -o outputPrefix

Saving image outside the output folder is not allowed, that’s why the output is actually a prefix

 

The ComfyUI API Calls Python script explained

# What really matters is the way we inject the workflow to the API
# the workflow is JSON text coming from a file:
prompt = json.load(file)
# or a string:
prompt = json.loads(prompt_text_example_1)

# then we nest it under a "prompt" key:
p = {"prompt": prompt}
# then we encode it to UTF8:
data = json.dumps(p).encode('utf-8')
# then we create an http POST:
req =  urllib.request.Request(comfyUrl, data=data)
with urllib.request.urlopen(req) as response:
  # Do stuff with complete data == wait for a reply. Unfortunately Comfy does not reply anything
  answer = response.read()

That’s it! ComfyUI will not wait after you inject the POST because of its queuing system. You can send many queries one after another and the files will generate in order.

Want to API call h2oGPT instead?

Questions? Comments?

Team Cook

Bachelor in IT, father, Photograph, Communist slayer, I also build useful tools for my community and destroy repetitive tasks for the past 20 years. "Who controls the information, controls the future."

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x