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

简介: 本文提供了一个使用Python调用Stable Diffusion API生成图片的示例程序,包括启动API设置、发送POST请求、保存生成的图片和JSON数据,以及如何通过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、运行生图程序

程序如下

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,可以在里面查看支持修改的属性(基本全部可以奥)

相关文章
|
16天前
|
消息中间件 运维 Serverless
函数计算产品使用问题之如何部署Stable Diffusion Serverless API
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
1天前
|
JSON API 数据库
使用Python和Flask构建简单的RESTful API
使用Python和Flask构建简单的RESTful API
11 6
|
23天前
|
SQL 关系型数据库 MySQL
Python DB-API
【8月更文挑战第22天】
30 11
|
26天前
|
JSON 前端开发 API
【淘系】商品详情属性解析(属性规格详情图sku等json数据示例返回参考),淘系API接口系列
在淘宝(或天猫)平台上,商品详情属性(如属性规格、详情图、SKU等)是商家在发布商品时设置的,用于描述商品的详细信息和不同规格选项。这些信息对于消费者了解商品特性、进行购买决策至关重要。然而,直接通过前端页面获取这些信息的结构化数据(如JSON格式)并非直接暴露给普通用户或开发者,因为这涉及到平台的商业机密和数据安全。 不过,淘宝平台提供了丰富的API接口(如淘宝开放平台API),允许有资质的开发者或合作伙伴通过编程方式获取商品信息。这些API接口通常需要注册开发者账号、申请应用密钥(App Key)和秘钥(App Secret),并遵守淘宝的API使用协议。
|
14天前
|
Java 缓存 数据库连接
揭秘!Struts 2性能翻倍的秘诀:不可思议的优化技巧大公开
【8月更文挑战第31天】《Struts 2性能优化技巧》介绍了提升Struts 2 Web应用响应速度的关键策略,包括减少配置开销、优化Action处理、合理使用拦截器、精简标签库使用、改进数据访问方式、利用缓存机制以及浏览器与网络层面的优化。通过实施这些技巧,如懒加载配置、异步请求处理、高效数据库连接管理和启用GZIP压缩等,可显著提高应用性能,为用户提供更快的体验。性能优化需根据实际场景持续调整。
40 0
|
14天前
|
JSON API 数据库
探索FastAPI:不仅仅是一个Python Web框架,更是助力开发者高效构建现代化RESTful API服务的神器——从环境搭建到CRUD应用实战全面解析
【8月更文挑战第31天】FastAPI 是一个基于 Python 3.6+ 类型提示标准的现代 Web 框架,以其高性能、易用性和现代化设计而备受青睐。本文通过示例介绍了 FastAPI 的优势及其在构建高效 Web 应用中的强大功能。首先,通过安装 FastAPI 和 Uvicorn 并创建简单的“Hello, World!”应用入门;接着展示了如何处理路径参数和查询参数,并利用类型提示进行数据验证和转换。
31 0
|
17天前
|
SQL Shell API
python Django教程 之 模型(数据库)、自定义Field、数据表更改、QuerySet API
python Django教程 之 模型(数据库)、自定义Field、数据表更改、QuerySet API
|
20天前
|
API 网络架构 C++
【Azure Key Vault】使用REST API调用Azure Key Vault Secret的示例步骤
【Azure Key Vault】使用REST API调用Azure Key Vault Secret的示例步骤
|
20天前
|
API C++ Python
【Azure Function】示例运行 python durable function(model V2)
【Azure Function】示例运行 python durable function(model V2)
|
20天前
|
API 数据安全/隐私保护
【Azure Developer】使用 Microsoft Graph API 获取 AAD User 操作示例
【Azure Developer】使用 Microsoft Graph API 获取 AAD User 操作示例