当前位置:   article > 正文

comfyui api开启并显示在页面上_comfyui-api

comfyui-api

一、下载安装启动comfyui(ComfyUI_windows_portable)

双击run_nvidia_gpu.bat开启命令行

下载workflow_api.json

二、写api接口

1.get_output

  1. import json
  2. import requests
  3. import urllib.request
  4. import urllib.parse
  5. import websockets
  6. from demo.utils import image_to_base64
  7. server_address = "127.0.0.1:8188"
  8. def queue_prompt(prompt, client_id):
  9. url = f"http://{server_address}/prompt"
  10. payload = {"prompt": prompt, "client_id": client_id}
  11. response = requests.post(url, json=payload)
  12. if response.status_code == 200:
  13. return response.json()
  14. else:
  15. response.raise_for_status()
  16. def get_image_url(filename, subfolder, folder_type):
  17. data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
  18. url_values = urllib.parse.urlencode(data)
  19. image_url = "http://{}/view?{}".format(server_address, url_values)
  20. return image_url
  21. def get_history(prompt_id):
  22. with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
  23. return json.loads(response.read())
  24. async def get_outputs(client_id, prompt):
  25. prompt_id = queue_prompt(prompt, client_id)['prompt_id']
  26. output_images = []
  27. output_tags = []
  28. async with websockets.connect(f"ws://{server_address}/ws?clientId={client_id}") as websocket:
  29. while True:
  30. out = await websocket.recv()
  31. if isinstance(out, str):
  32. message = json.loads(out)
  33. if message['type'] == 'executing':
  34. data = message['data']
  35. if data['node'] is None and data['prompt_id'] == prompt_id:
  36. break
  37. history = get_history(prompt_id)[prompt_id]
  38. for node_id, node_output in history['outputs'].items():
  39. if 'images' in node_output:
  40. # images_output = []
  41. # for image in node_output['images']:
  42. # image_url = get_image_url(image['filename'], image['subfolder'], image['type'])
  43. # images_output.append(image_url)
  44. # output_images_url[node_id] = images_output
  45. for image in node_output['images']:
  46. print(image)
  47. image_base64 = image_to_base64(image['filename'])
  48. # images_output.append(f"./temp/{image['filename']}")
  49. # img_path = f"./temp/{image['filename']}"
  50. # image_name = uuid.uuid4().hex + ".png"
  51. # bucket.put_object_from_file(f"ai/image/{image_name}", img_path)
  52. # images_output.append(f"{oss_img_url}/{image_name}")
  53. output_images.append(image_base64)
  54. # output_images[node_id] = images_output
  55. if 'tags' in node_output:
  56. # tags_output = []
  57. for tag in node_output['tags']:
  58. output_tags.append(tag)
  59. # output_tags[node_id] = tags_output
  60. return {"images": output_images, "tags": output_tags}

2.utils.py

  1. import json
  2. import base64
  3. def load_json_template(file_path):
  4. with open(file_path, 'r') as file:
  5. return json.load(file)
  6. def image_to_base64(filename):
  7. image_path = f"./output/{filename}"
  8. with open(image_path, "rb") as image_file:
  9. encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
  10. return encoded_string

3.router.py

  1. import os
  2. import random
  3. import uuid
  4. import requests
  5. from demo.utils import load_json_template
  6. # from api_utils.prompt_loader import load_checkpoint, load_controlnet, load_loras, load_prompt, load_controlnet_webui
  7. from demo.get_output import get_outputs
  8. from fastapi import UploadFile, File, Form
  9. from fastapi.responses import JSONResponse
  10. async def process_generateimg(data):
  11. client_id = str(uuid.uuid4())
  12. prompt = load_json_template('demo/workflow_api.json')
  13. prompt["3"]["inputs"]["seed"] = random.randrange(10**14, 10**15)
  14. # if data.denoise:
  15. # prompt["102"]["inputs"]["denoise"] = data.denoise
  16. prompt["6"]["inputs"]["text"] = data.prompt
  17. # prompt["129"]["inputs"]["image"] = data.image
  18. images =await get_outputs(client_id,prompt)
  19. return images

4.api.py

  1. from fastapi import FastAPI, HTTPException
  2. from pydantic import BaseModel
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi.responses import HTMLResponse, JSONResponse
  5. # import random
  6. import json
  7. from demo.router import *
  8. import base64
  9. from io import BytesIO
  10. from PIL import Image
  11. app = FastAPI()
  12. class TextToImageModel(BaseModel):
  13. prompt: str
  14. @app.post("/generate_img", tags=["perfume bottle"])
  15. async def generate_img(data:TextToImageModel):
  16. return await process_generateimg(data)
  17. # 将 static 目录中的文件作为静态文件提供
  18. app.mount("/static", StaticFiles(directory="demo/static"), name="static")
  19. @app.get("/", response_class=HTMLResponse)
  20. def read_root():
  21. file_path = os.path.join("demo", "static", "index.html")
  22. try:
  23. with open(file_path, "r", encoding="utf-8") as f:
  24. return HTMLResponse(content=f.read(), status_code=200)
  25. except FileNotFoundError:
  26. return HTMLResponse(content="File not found", status_code=404)
  27. # UPLOAD_DIRECTORY = "./uploaded_videos"
  28. # if not os.path.exists(UPLOAD_DIRECTORY):
  29. # os.makedirs(UPLOAD_DIRECTORY)
  30. if __name__ == '__main__':
  31. import uvicorn
  32. uvicorn.run(app, host="0.0.0.0", port=8000)
  33. # 运行命令:uvicorn api:app --reload

5.静态页面

新建static文件夹,在该文件夹下新建index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Image Generator</title>
  5. </head>
  6. <body>
  7. <h1>Image Generator</h1>
  8. <form id="generateForm">
  9. <label for="prompt">Prompt:</label>
  10. <input type="text" id="prompt" name="prompt" required>
  11. <button type="submit">Generate Image</button>
  12. </form>
  13. <div id="images"></div>
  14. <script>
  15. document.getElementById('generateForm').addEventListener('submit', async function(event) {
  16. event.preventDefault();
  17. const prompt = document.getElementById('prompt').value;
  18. console.log(prompt);
  19. try {
  20. const response = await fetch('/generate_img', {
  21. method: 'POST',
  22. headers: {
  23. 'Content-Type': 'application/json'
  24. },
  25. body: JSON.stringify({ prompt: prompt })
  26. });
  27. if (!response.ok) {
  28. throw new Error('Network response was not ok');
  29. }
  30. const data = await response.json();
  31. console.log(data);
  32. const imagesDiv = document.getElementById('images');
  33. imagesDiv.innerHTML = '';
  34. data.images.forEach(imageBase64 => {
  35. const img = document.createElement('img');
  36. img.onload = function() {
  37. imagesDiv.appendChild(img);
  38. };
  39. img.src = 'data:image/png;base64,' + imageBase64;
  40. });
  41. } catch (error) {
  42. console.error('Error:', error);
  43. }
  44. });
  45. </script>
  46. </body>
  47. </html>

6.补充COMFYUI安装教程

 官网下载地址:

确保将稳定扩散检查点/模型(巨大的 ckpt/safetensors 文件)放入文件中:ComfyUI\models\checkpoints

加载模型 有条件(魔法)的同学可前往C站下载 跳转

此处大模型由 B站UP主秋葉aaaki提供,留下了没用SVIP的

大模型:https://pan.baidu.com/s/1TbA04C3TcOSKUh1Y_9trOg 提取码:aaki

大模型:https://pan.baidu.com/s/1v_RKaBTWkhFYabOvlao7pQ 提取码:aaki

下载完成后将模型放在如下目录 checkpoints 文件夹下

另一个UI如何跟ComfyUI之间共享模型 笔者之前用的是 stable-diffusion-webui ,以此举例将extra_model_paths.yaml.example 文件复制一份,然后通过文本编辑器打开副本文件。

修改配置文件,笔者的controlnet插件是通过Civitai-Helper下载的所有也需要修改,退出保存。

删除extra_model_paths.yaml- 副本.example yaml文件后字符串(副本.example)后的得到extra_model_paths.yaml 文件。

启动comfyUI如下图根据具体需求选择对应的脚本。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/944810
推荐阅读
相关标签
  

闽ICP备14008679号