python调用sd绘画接口

bvipc的接口:

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
import requests
from base64 import b64encode, b64decode
import json

# 设置API的URL
url = "https://qwq.bvipc.com/sdapi/v1/txt2img"

# 账号和密码用于Basic Auth认证
account_id = "xxxxx"
account_password = "xxxxxxxxxxxx"

# 准备Basic Auth的头部
credentials = f"{account_id}:{account_password}"
encoded_credentials = b64encode(credentials.encode("utf-8")).decode("utf-8")
auth_header = {
"Authorization": f"Basic {encoded_credentials}",
"Content-Type": "application/json",
}

# 根据API的要求调整请求数据
data = {
"prompt": "draw a lovely girly",
"steps": 10,
"width": 512,
"height": 512,
"cfg_scale": 7.5,
"seed": -1,
"sampler_index": "Euler a",
}

# 发送POST请求,包含Basic Auth头部和JSON数据
response = requests.post(url, data=json.dumps(data), headers=auth_header)

# 检查响应
if response.status_code == 200:
response_data = response.json()
images = response_data.get('images', [])
for i, image_base64 in enumerate(images, start=1):
# 解码Base64编码的图像数据
image_data = b64decode(image_base64)
# 为每个图像创建一个文件名
image_filename = f"image_{i}.png"
# 将图像数据写入文件
with open(image_filename, "wb") as image_file:
image_file.write(image_data)
print(f"图像已保存为:{image_filename}")
else:
print("Error:", response.status_code, response.text)

阿里云sd绘画api接口代码:

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
import requests
import base64

endpoint = "http://sd.xxxxxxx.cn-hangzhou.fc.devsapp.net"
username = ""
password = ""

resp = requests.post(
"%s/sdapi/v1/txt2img" % endpoint,
headers={
"Authorization": "Basic %s" % (
base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("utf-8")), # 如果未开启 API 鉴权,可忽略该部分
},
json={
"prompt": "a lovely girly,avatar",#提示词
"step": 10,
"height": 512,
"width": 1024,

"override_settings": {
"sd_model_checkpoint": "mixProV4.Cqhm.safetensors",
# "sd_model_checkpoint": "majicMIX realistic_v6.safetensors",
},
}
)

if resp.status_code == 200:
data = resp.json()
for i, img in enumerate(data["images"]):
with open("%s.png" % (i), "wb") as f:
b = base64.b64decode(img)
f.write(b)

data["images"] = ""
print(data)
else:
print(resp.status_code, resp.text)