"""在无头模式或使用替代前端运行 ComfyUI 时使用 API 节点
你可以通过在 prompt 中包含 API key 来执行包含 API 节点的 ComfyUI 工作流。
API key 需要添加到 payload 的 `extra_data` 字段中。
下面我们展示一个如何实现的示例。
更多信息请参考:
- API 节点概述: https://docs.comfy.org/zh-CN/tutorials/api-nodes/overview
- 要生成 API key,请登录这里: https://platform.comfy.org/login
"""
import json
from urllib import request
SERVER_URL = "http://127.0.0.1:8188"
# 我们有一个包含 API 节点的 prompt/job(API 格式的工作流)。
workflow_with_api_nodes = """{
"11": {
"inputs": {
"prompt": "A dreamy, surreal half-body portrait of a young woman meditating. She has a short, straight bob haircut dyed in pastel pink, with soft bangs covering her forehead. Her eyes are gently closed, and her hands are raised in a calm, open-palmed meditative pose, fingers slightly curved, as if levitating or in deep concentration. She wears a colorful dress made of patchwork-like pastel tiles, featuring clouds, stars, and rainbows. Around her float translucent, iridescent soap bubbles reflecting the rainbow hues. The background is a fantastical sky filled with cotton-candy clouds and vivid rainbow waves, giving the entire scene a magical, dreamlike atmosphere. Emphasis on youthful serenity, whimsical ambiance, and vibrant soft lighting.",
"prompt_upsampling": false,
"seed": 589991183902375,
"aspect_ratio": "1:1",
"raw": false,
"image_prompt_strength": 0.4000000000000001,
"image_prompt": [
"14",
0
]
},
"class_type": "FluxProUltraImageNode",
"_meta": {
"title": "Flux 1.1 [pro] Ultra Image"
}
},
"12": {
"inputs": {
"filename_prefix": "ComfyUI",
"images": [
"11",
0
]
},
"class_type": "SaveImage",
"_meta": {
"title": "Save Image"
}
},
"14": {
"inputs": {
"image": "example.png"
},
"class_type": "LoadImage",
"_meta": {
"title": "Load Image"
}
}
}"""
prompt = json.loads(workflow_with_api_nodes)
payload = {
"prompt": prompt,
# 将 `api_key_comfy_org` 添加到 payload 中。
# 如果你需要处理多个客户端,可以先从关联的用户获取 key。
"extra_data": {
"api_key_comfy_org": "comfyui-87d01e28d*******************************************************" # 替换为实际的 key
},
}
data = json.dumps(payload).encode("utf-8")
req = request.Request(f"{SERVER_URL}/prompt", data=data)
# 发送请求
request.urlopen(req)