当前位置:   article > 正文

Python 使用 Stable Diffusion API 生成图片示例_python调用stable diffusion的api

python调用stable diffusion的api

在这里插入图片描述
在这里插入图片描述
代码:

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://192.168.2.82: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("|", "_")
    response = submit_post(txt2img_url, data)
    save_encoded_image(response.json()['images'][0], output_path)
    save_json_file(response.json(), output_path)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79

输出:

>> python txt2img.py
请输入提示词:masterpiece, best quality, 1boy, orc, male focus, mecha, robot, science fiction, solo, black background <lora:nijiMecha:1> <lora:wzh-000022:1>
请输入反面提示词:(worst quality, low quality:1.4), greyscale, monochrome, watermark, signature

masterpiece, best quality, 1boy, orc, male focus, mecha, robot, science fiction, solo, black background <lora:nijiMecha:1> <lora:wzh-000022:1>
Negative prompt: (worst quality, low quality:1.4), greyscale, monochrome, watermark, signature
Steps: 50, Sampler: Euler, CFG scale: 7.0, Seed: 274772779, Size: 512x512, Model hash: ce67b54cf2, Model: oukaNiji5_v10, Seed resize from: -1x-1, Denoising strength: 0, Clip skip: 2

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

说明:

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

TIP:

  • 当然前提是你已经部署好 Stable Diffusion API 服务;
  • 并且安装好跟我一样的模型以及一些相关的 LoRA

print('HELLO WORLD') # http://www.skyner.cn
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/769868
推荐阅读
相关标签
  

闽ICP备14008679号