当前位置: 首页 > news >正文

03.01.01.ComfyUI Ubuntu:环境搭建篇(集成 调用ComfyUI的API 使用Pythin 中间件方式)

总操作流程:

  • 1、下载安装
  • 2、写代码
  • 3、测试

下载安装

pipinstallwebsocket-client uuid Pillow
  • api: https://docs.comfy.org/zh/development/comfyui-server/api-examples

写代码

方法一:提交即忘(仅 HTTP)

cat>/usr/local/software/ComfyUI/script_examples/test_basic_api.py<<'EOF' import json from urllib import request prompt_text = """ { "3": { "class_type": "KSampler", "inputs": { "cfg": 8, "denoise": 1, "latent_image": [ "5", 0 ], "model": [ "4", 0 ], "negative": [ "7", 0 ], "positive": [ "6", 0 ], "sampler_name": "euler", "scheduler": "normal", "seed": 8566257, "steps": 20 } }, "4": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "stabilityai/stable-diffusion-3-medium/sd3_medium_incl_clips_t5xxlfp16.safetensors" } }, "5": { "class_type": "EmptyLatentImage", "inputs": { "batch_size": 1, "height": 512, "width": 512 } }, "6": { "class_type": "CLIPTextEncode", "inputs": { "clip": [ "4", 1 ], "text": "masterpiece best quality girl" } }, "7": { "class_type": "CLIPTextEncode", "inputs": { "clip": [ "4", 1 ], "text": "bad hands" } }, "8": { "class_type": "VAEDecode", "inputs": { "samples": [ "3", 0 ], "vae": [ "4", 2 ] } }, "9": { "class_type": "SaveImage", "inputs": { "filename_prefix": "ComfyUI", "images": [ "8", 0 ] } } } """ def queue_prompt(prompt): p = {"prompt": prompt} data = json.dumps(p).encode('utf-8') req = request.Request("http://10.3.11.173:8188/prompt", data=data) request.urlopen(req) prompt = json.loads(prompt_text) prompt["6"]["inputs"]["text"] = "画一只小猫咪" prompt["3"]["inputs"]["seed"] = 5 queue_prompt(prompt) EOF

方法二:WebSocket + History(监控执行完成)

cat>/usr/local/software/ComfyUI/script_examples/test_websockets_api.py<<'EOF' import websocket import uuid import json import urllib.request import urllib.parse server_address = "10.3.11.173:8188" client_id = str(uuid.uuid4()) def queue_prompt(prompt, prompt_id): p = {"prompt": prompt, "client_id": client_id, "prompt_id": prompt_id} data = json.dumps(p).encode('utf-8') req = urllib.request.Request("http://{}/prompt".format(server_address), data=data) urllib.request.urlopen(req).read() def get_image(filename, subfolder, folder_type): data = {"filename": filename, "subfolder": subfolder, "type": folder_type} url_values = urllib.parse.urlencode(data) with urllib.request.urlopen("http://{}/view?{}".format(server_address, url_values)) as response: return response.read() def get_history(prompt_id): with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response: return json.loads(response.read()) def get_images(ws, prompt): prompt_id = str(uuid.uuid4()) queue_prompt(prompt, prompt_id) output_images = {} while True: out = ws.recv() if isinstance(out, str): message = json.loads(out) if message['type'] == 'executing': data = message['data'] if data['node'] is None and data['prompt_id'] == prompt_id: break #Execution is done else: # If you want to be able to decode the binary stream for latent previews, here is how you can do it: # bytesIO = BytesIO(out[8:]) # preview_image = Image.open(bytesIO) # This is your preview in PIL image format, store it in a global continue #previews are binary data history = get_history(prompt_id)[prompt_id] for node_id in history['outputs']: node_output = history['outputs'][node_id] images_output = [] if 'images' in node_output: for image in node_output['images']: image_data = get_image(image['filename'], image['subfolder'], image['type']) images_output.append(image_data) output_images[node_id] = images_output return output_images prompt_text = """ { "3": { "class_type": "KSampler", "inputs": { "cfg": 8, "denoise": 1, "latent_image": [ "5", 0 ], "model": [ "4", 0 ], "negative": [ "7", 0 ], "positive": [ "6", 0 ], "sampler_name": "euler", "scheduler": "normal", "seed": 8566257, "steps": 20 } }, "4": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "stabilityai/stable-diffusion-3-medium/sd3_medium_incl_clips_t5xxlfp16.safetensors" } }, "5": { "class_type": "EmptyLatentImage", "inputs": { "batch_size": 1, "height": 512, "width": 512 } }, "6": { "class_type": "CLIPTextEncode", "inputs": { "clip": [ "4", 1 ], "text": "masterpiece best quality girl" } }, "7": { "class_type": "CLIPTextEncode", "inputs": { "clip": [ "4", 1 ], "text": "bad hands" } }, "8": { "class_type": "VAEDecode", "inputs": { "samples": [ "3", 0 ], "vae": [ "4", 2 ] } }, "9": { "class_type": "SaveImage", "inputs": { "filename_prefix": "ComfyUI", "images": [ "8", 0 ] } } } """ prompt = json.loads(prompt_text) #set the text prompt for our positive CLIPTextEncode prompt["6"]["inputs"]["text"] = "画一只大闸蟹" prompt["3"]["inputs"]["seed"] = 5 ws = websocket.WebSocket() ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id)) images = get_images(ws, prompt) ws.close() EOF

方法三:WebSocket 配合 SaveImageWebsocket(实时获取图片)

cat>/usr/local/software/ComfyUI/script_examples/test_websockets_api_example_ws_images.py<<'EOF' import websocket import uuid import json import urllib.request import urllib.parse server_address = "10.3.11.173:8188" client_id = str(uuid.uuid4()) def queue_prompt(prompt): p = {"prompt": prompt, "client_id": client_id} data = json.dumps(p).encode('utf-8') req = urllib.request.Request("http://{}/prompt".format(server_address), data=data) return json.loads(urllib.request.urlopen(req).read()) def get_image(filename, subfolder, folder_type): data = {"filename": filename, "subfolder": subfolder, "type": folder_type} url_values = urllib.parse.urlencode(data) with urllib.request.urlopen("http://{}/view?{}".format(server_address, url_values)) as response: return response.read() def get_history(prompt_id): with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response: return json.loads(response.read()) def get_images(ws, prompt): prompt_id = queue_prompt(prompt)['prompt_id'] output_images = {} current_node = "" while True: out = ws.recv() if isinstance(out, str): message = json.loads(out) if message['type'] == 'executing': data = message['data'] if data['prompt_id'] == prompt_id: if data['node'] is None: break #Execution is done else: current_node = data['node'] else: if current_node == 'save_image_websocket_node': images_output = output_images.get(current_node, []) images_output.append(out[8:]) output_images[current_node] = images_output return output_images prompt_text = """ { "3": { "class_type": "KSampler", "inputs": { "cfg": 8, "denoise": 1, "latent_image": [ "5", 0 ], "model": [ "4", 0 ], "negative": [ "7", 0 ], "positive": [ "6", 0 ], "sampler_name": "euler", "scheduler": "normal", "seed": 8566257, "steps": 20 } }, "4": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "stabilityai/stable-diffusion-3-medium/sd3_medium_incl_clips_t5xxlfp16.safetensors" } }, "5": { "class_type": "EmptyLatentImage", "inputs": { "batch_size": 1, "height": 512, "width": 512 } }, "6": { "class_type": "CLIPTextEncode", "inputs": { "clip": [ "4", 1 ], "text": "masterpiece best quality girl" } }, "7": { "class_type": "CLIPTextEncode", "inputs": { "clip": [ "4", 1 ], "text": "bad hands" } }, "8": { "class_type": "VAEDecode", "inputs": { "samples": [ "3", 0 ], "vae": [ "4", 2 ] } }, "9": { "class_type": "SaveImage", "inputs": { "filename_prefix": "ComfyUI", "images": [ "8", 0 ] } } } """ prompt = json.loads(prompt_text) prompt["6"]["inputs"]["text"] = "画一只毛毛虫" prompt["3"]["inputs"]["seed"] = 5 ws = websocket.WebSocket() ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id)) images = get_images(ws, prompt) ws.close() EOF

测试

# 本身就有的代码cd/usr/local/software/ComfyUI/script_exampleschmod0777-R*&&chown$USER:$USER-R*

方法一:提交即忘(仅 HTTP)

# 运行时候查看ComfyUI输出的日志python /usr/local/software/ComfyUI/script_examples/test_basic_api.py# 自动生成的图片在如下文件夹ls/usr/local/software/ComfyUI/output

WebSocket + History(监控执行完成)

# 运行时候查看ComfyUI输出的日志python /usr/local/software/ComfyUI/script_examples/test_websockets_api.py# 自动生成的图片在如下文件夹ls/usr/local/software/ComfyUI/output

方法三:WebSocket 配合 SaveImageWebsocket(实时获取图片)

# 运行时候查看ComfyUI输出的日志python /usr/local/software/ComfyUI/script_examples/test_websockets_api_example_ws_images.py# 自动生成的图片在如下文件夹ls/usr/local/software/ComfyUI/output
http://www.jsqmd.com/news/1151329/

相关文章:

  • VMamba VSSM 架构解析:4阶段VSS Block堆叠与SS2D模块的3步实现
  • 通过Semi Design思考前端组件AI化
  • 地月引力地震理论应用——四川高风险年份筛选
  • 测试转大模型:从排查路径看工程价值
  • DC SUPERMAN 超人美国商标维权全解析|S 盾图形 TRO 禁令应对教程
  • 一、三步搞定:在Creo/ProE任意位置自定义坐标系并导出
  • SolidWorks_装配体设计19_装配体动画与运动
  • Windows命令调用的神经反射弧:Run-Command智能启动器
  • 【单片机毕业设计】基于 51/STM32 单片机的温度监测声光报警系统设计与实现,基于 51/STM32 单片机的数码管温度采集报警装置开发(022801)
  • 杰理之旋转编码器【篇】
  • 2026智能写作工具深度测评|教育学习、文案创作、论文写作首选工具盘点
  • AGENTS.md / CLAUDE.md 到底写什么?给 AI 编程工具一份仓库说明书
  • HCIP--BGP基础实验
  • Seaborn vs Matplotlib vs Plotly:3种热力图方案性能与效果深度对比
  • JDK 1.8 已经装好,JDK 17 安装
  • 微信公众号原生Servlet开发零基础实战教程(附公众号主体变更迁移公证书办理流程及完整后端运行代码)
  • VSP One:走向统一的数据基础设施
  • 记一次使用 cloudflared tunnel 内网穿透
  • PCL 无序点云的快速三角剖分
  • 【单片机毕业设计】基于 51/STM32 单片机的超声波测距声光报警系统设计,基于 STM32/51 单片机的近距离测距预警装置开发(022901)
  • AI 眼镜不是下一台手机,而是 AI 终于长出了眼睛
  • 理解平衡树数据结构在数据库索引中的核心价值
  • 爱丁堡大学与MIT联手打造的AI科学家
  • 终极Armbian部署指南:将闲置电视盒子变身高性能Linux服务器
  • 倒装芯片封装 3 种凸块工艺对比:金/铜柱/锡凸块选型与 5 项关键参数
  • Scikit-learn 1.5实战:3行代码完成K-Means聚类与逻辑回归分类
  • 暗黑破坏神2存档编辑器完整技术指南:从入门到深度定制
  • HFSS 2024 R2 仿真分析:微带线与带状线在 20GHz 下的辐射与串扰差异
  • 数值计算优化:避免浮点数误差的算法设计
  • HarmonyKit | 鸿蒙新特性实践:UUID v4 生成器的纯 ArkTS 实现