Mac电脑手动安装原版Stable Diffusion,开启本地API调用生成图片
Mac 上安装 Stable Diffusion 的方法:
安装 Homebrew(如果尚未安装)
打开终端,执行以下命令:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
安装 Python 3.10.x
brew install python@3.10
安装 Git
brew install git
安装步骤
克隆 automatic1111 仓库
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
# 如果clone不下来,直接到github去下载再解压(unzip)也可以
cd stable-diffusion-webui
创建并激活虚拟环境
python3.10 -m venv venv
source venv/bin/activate
执行webui.sh
./webui.sh
等结束后会自动跳转127.0.0.1:7860
下载model
https://civitai.com/models
model放到stable diffusion webui/models/Stable Diffusion下
开启API
# 在webui-user.sh添加
# Stable Diffusion WebUI启动脚本
export COMMANDLINE_ARGS="--lowvram --precision full --no-half --skip-torch-cuda-test --disable-nan-check --api"
再启动./webui.sh
编写本地调用api代码
import requests
import json
import base64
from PIL import Image
from io import BytesIO
import os# API地址(默认端口7860)
API_URL = "http://127.0.0.1:7860"# 1. 文本生成图像(txt2img)
def txt2img(prompt, negative_prompt="", steps=20, width=512, height=512, sampler="Euler a"):payload = {"prompt": prompt,"negative_prompt": negative_prompt,"steps": steps,"width": width,"height": height,"sampler_name": sampler,"cfg_scale": 7, # 提示词相关性,值越高越贴近提示"seed": -1, # -1表示随机种子}response = requests.post(f"{API_URL}/sdapi/v1/txt2img", json=payload)if response.status_code == 200:result = response.json()for i, img_data in enumerate(result["images"]):image = Image.open(BytesIO(base64.b64decode(img_data)))save_path = f"txt2img_result_{i}.png"image.save(save_path)print(f"图片已保存至: {save_path}")return resultelse:print(f"请求失败,状态码: {response.status_code}")print(response.text)return None# 2. 图像生成图像(img2img)
def img2img(prompt, image_path, negative_prompt="", steps=20, strength=0.7, sampler="Euler a"):# 读取图像并转换为base64with open(image_path, "rb") as f:image_data = f.read()image_base64 = base64.b64encode(image_data).decode('utf-8')payload = {"prompt": prompt,"negative_prompt": negative_prompt,"init_images": [image_base64],"steps": steps,"sampler_name": sampler,"strength": strength, # 0.1-0.9,数值越高与原图差异越大"cfg_scale": 7,"seed": -1,}response = requests.post(f"{API_URL}/sdapi/v1/img2img", json=payload)if response.status_code == 200:result = response.json()for i, img_data in enumerate(result["images"]):image = Image.open(BytesIO(base64.b64decode(img_data)))save_path = f"img2img_result_{i}.png"image.save(save_path)print(f"图片已保存至: {save_path}")return resultelse:print(f"请求失败,状态码: {response.status_code}")print(response.text)return None# 3. 获取可用模型列表
def get_models():response = requests.get(f"{API_URL}/sdapi/v1/sd-models")if response.status_code == 200:return response.json()return []# 4. 切换模型
def switch_model(model_name):payload = {"sd_model_checkpoint": model_name}response = requests.post(f"{API_URL}/sdapi/v1/options", json=payload)return response.status_code == 200# 示例调用
if __name__ == "__main__":# 示例1: 文本生成图像txt2img(prompt="a beautiful landscape, mountains, lake, detailed, realistic, 4k",negative_prompt="blurry, low quality, deformed",steps=30,width=768,height=512)# 示例2: 图像生成图像(取消注释并提供图片路径)# img2img(# prompt="make it more vibrant, add birds in the sky",# image_path="input_image.png",# strength=0.6# )# 示例3: 获取可用模型# models = get_models()# print("可用模型:", [model["title"] for model in models])# 示例4: 切换模型# switch_model("v1-5-pruned-emaonly.ckpt")
运行后
这样就可以编写本地脚本,实现自动化生图了,而无需在webui上一张张图自己生成了。