前情提要
在之前嘗試使用Diffusers庫來進行stable-diffusion的接口調用以及各種插件功能實現,但發現diffusers庫中各復雜功能的添加較為麻煩,而且難以實現對采樣器的添加,safetensors格式模型的讀取。在官網上找到了webui有專門的api接口,能夠極大方便我們進行類似webui界面的api調用。
diffusers文檔
webui項目官網
webui API說明
webui項目部署
這種調用webui自帶的api的方法需要先將webui運行起來,無論是自己從官網配置的webui,還是各類啟動器一鍵啟動的都是可以的。(我使用的為一鍵啟動包,較為簡單)
一鍵啟動包教程
如果是自己配置的
使用
bash webui.sh --nowebui
或者
python launch.py --xformers --api
API接口調用
當我們把webui項目啟動之后,我們可以看到運行的端口(默認為7860)
可以進行調用
1. 文生圖(python示例):
import json
import requests
import io
import base64
from PIL import Imageurl = "http://127.0.0.1:7860"prompt = "dog"
negative_prompt = ""payload = {# 模型設置"override_settings":{"sd_model_checkpoint": "v1-5-pruned.ckpt","sd_vae": "animevae.pt","CLIP_stop_at_last_layers": 2,},# 基本參數"prompt": prompt,"negative_prompt": negative_prompt,"steps": 30,"sampler_name": "Euler a","width": 512,"height": 512,"batch_size": 1,"n_iter": 1,"seed": 1,"CLIP_stop_at_last_layers": 2,# 面部修復 face fix"restore_faces": False,#高清修復 highres fix# "enable_hr": True,# "denoising_strength": 0.4,# "hr_scale": 2,# "hr_upscaler": "Latent",}response = requests.post(url=f'{url}/sdapi/v1/txt2img', json=payload)
r = response.json()
image = Image.open(io.BytesIO(base64.b64decode(r['images'][0])))image.show()
image.save('output.png')
2. 圖生圖(python 示例)
import json
import requests
import io
import base64
from PIL import Image
import cv2url = "http://127.0.0.1:7860"prompt = "cat"
negative_prompt = ""# 此處為讀取一張圖片作為輸入圖像
img = cv2.imread('image.jpg')# 編碼圖像
retval, bytes = cv2.imencode('.png', img)
encoded_image = base64.b64encode(bytes).decode('utf-8')payload = {# # 模型設置
# "override_settings":{
# "sd_model_checkpoint": "v1-5-pruned.ckpt",
# "sd_vae": "animevae.pt",
# "CLIP_stop_at_last_layers": 2,
# },# 基本參數"prompt": prompt,"negative_prompt": negative_prompt,"steps": 30,"sampler_name": "Euler a","width": 512,"height": 512,"batch_size": 1,"n_iter": 1,"seed": 1,"cfg_scale": 7,"CLIP_stop_at_last_layers": 2,"init_images": [encoded_image],# 面部修復 face fix"restore_faces": False,#高清修復 highres fix# "enable_hr": True,# "denoising_strength": 0.4,# "hr_scale": 2,# "hr_upscaler": "Latent",}response = requests.post(url=f'{url}/sdapi/v1/img2img', json=payload)
r = response.json()
image = Image.open(io.BytesIO(base64.b64decode(r['images'][0])))image.show()
image.save('output.png')
如要修改其他參數可參照官網文檔進行修改。