python 使用 Stable Diffusion API 生成图片示例

python 使用 Stable Diffusion API 生成图片示例

一、前言

在无聊的时候,想瞅一下sd生图遂做了一下

二、具体步骤

1、启动SD的api设置

注意,运行后的api相关功能可以在:http://127.0.0.1:7860/docs 查看

比如这一次我们要的生图的地址就是/sdapi/v1/txt2img 是POST

所以可以通过requests 向 "http://127.0.0.1:7860/sdapi/v1/txt2img"发送POST请求并拿到数据

注意将69行的: txt2img_url = "http://127.0.0.1:7860/sdapi/v1/txt2img" # 服务器地址 ,里面的地址和端口改成你的

2、运行生图程序

程序如下

python 复制代码
import base64
import datetime
import json
import os

import requests


def submit_post(url: str, data: dict):
    """
    Submit a POST request to the given URL with the given data.
    :param url:  url
    :param data: data
    :return:  response
    """
    return requests.post(url, data=json.dumps(data))


def save_encoded_image(b64_image: str, output_path: str):
    """
    Save the given image to the given output path.
    :param b64_image:  base64 encoded image
    :param output_path:  output path
    :return:  None
    """
    # 判断当前目录下是否存在 output 文件夹,如果不存在则创建
    if not os.path.exists("output"):
        os.mkdir("output")
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    output_path = f"{output_path}_{timestamp}" + ".png"
    # 将文件放入当前目录下的 output 文件夹中
    output_path = f"output/{output_path}"
    with open(output_path, "wb") as f:
        f.write(base64.b64decode(b64_image))


def save_json_file(data: dict, output_path: str):
    """
    Save the given data to the given output path.
    :param data:  data
    :param output_path:  output path
    :return:  None
    """
    # 忽略 data 中的 images 字段
    data.pop('images')
    # 将 data 中的 info 字段转为 json 字符串,info 当前数据需要转义
    data['info'] = json.loads(data['info'])

    # 输出 data.info.infotexts
    info_texts = data['info']['infotexts']
    for info_text in info_texts:
        print(info_text)

    # 判断当前目录下是否存在 output 文件夹,如果不存在则创建
    if not os.path.exists("output"):
        os.mkdir("output")
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    output_path = f"{output_path}_{timestamp}" + ".json"
    # 将文件放入当前目录下的 output 文件夹中
    output_path = f"output/{output_path}"
    with open(output_path, "w") as f:
        json.dump(data, f, indent=4, ensure_ascii=False)


if __name__ == '__main__':
    """
    Example usage: python3 txt2img.py
    """
    txt2img_url = "http://127.0.0.1:7860/sdapi/v1/txt2img" # 服务器地址
    prompt = input("请输入提示词:")
    negative_prompt = input("请输入反面提示词:")
    data = {'prompt': prompt, 'negative_prompt': negative_prompt}
    # 将 data.prompt 中的文本,删除文件名非法字符,已下划线分隔,作为文件名
    output_path = data['prompt'].replace(" ", "_").replace("/", "_").replace("\\", "_").replace(":", "_").replace("\"",
                                                                                                                  "_").replace(
        "<", "_").replace(">", "_").replace("|", "_")[:40]
    response = submit_post(txt2img_url, data)
    save_encoded_image(response.json()['images'][0], output_path)
    save_json_file(response.json(), output_path)

运行结果:

说明:

  • 运行后,图片以及 JSON 将会输出到当前目录下 output 中;

TIP:

  • 如果要调用特定模型请在body中加入额外的参数如
    *

    复制代码
      data = {'prompt': prompt, 'negative_prompt': negative_prompt,"sd_model_name":"animePastelDream_softBakedVae"}
    • 要使用更多参数请查看上面提到的docs,可以在里面查看支持修改的属性(基本全部可以奥)
相关推荐
愚润求学2 分钟前
【专题刷题】二分查找(一):深度解刨二分思想和二分模板
开发语言·c++·笔记·leetcode·刷题
EnigmaCoder3 分钟前
java面向对象编程【基础篇】之基础语法
java·开发语言
tanyongxi664 分钟前
手撕C++STL list:深入理解双向链表的实现
开发语言·c++·链表
啊阿狸不会拉杆7 分钟前
数据结构-图
java·c语言·数据结构·c++·python·算法·图论
沙尘暴炒饭19 分钟前
vuex持久化vuex-persistedstate,存储的数据刷新页面后导致数据丢失
开发语言·前端·javascript
Msshu12322 分钟前
诱骗协议芯片支持PD2.0/3.0/3.1/PPS协议,支持使用一个Type-C与电脑传输数据和快充取电功能
c语言·开发语言·电脑
萧鼎22 分钟前
RAGFlow:构建高效检索增强生成流程的技术解析
人工智能·python
cooljser31 分钟前
告别手动操作!用脚本搞定小程序签到的全过程
python
凌叁儿1 小时前
从零开始搭建Django博客①--正式开始前的准备工作
python·django·sqlite
景天科技苑1 小时前
【Rust结构体】Rust结构体详解:从基础到高级应用
开发语言·后端·rust·结构体·关联函数·rust结构体·结构体方法