-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
sd3api.py
183 lines (159 loc) · 6.28 KB
/
sd3api.py
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import os
import io
import json
import requests
import torch
import requests
from io import BytesIO
from PIL import Image
import sys
import torch
import numpy as np
import base64
p = os.path.dirname(os.path.realpath(__file__))
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def get_sai_api_key():
try:
config_path = os.path.join(p, 'config.json')
with open(config_path, 'r') as f:
config = json.load(f)
api_key = config["STABILITY_KEY"]
except:
print("出错啦 Error: API key is required")
return ""
return api_key
class SD3_Zho:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"positive": ("STRING", {"default": "cat", "multiline": True}),
"negative": ("STRING", {"default": "worst quality, low quality", "multiline": True}),
"aspect_ratio": (["21:9", "16:9", "5:4", "3:2", "1:1", "2:3", "4:5", "9:16", "9:21"],),
"mode": (["text-to-image", "image-to-image"],),
"model": (["sd3", "sd3-turbo"],),
"seed": ("INT", {"default": 66, "min": 0, "max": 1000000}),
},
"optional": {
"image": ("IMAGE",),
"strength": ("FLOAT", {"default": 0.7, "min": 0, "max": 1.0, "step": 0.01}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "generate_image"
CATEGORY = "🔥SD3"
def generate_image(self, positive, negative, aspect_ratio, mode, model, seed, image=None, strength=None):
apikey = get_sai_api_key()
if model == 'sd3-turbo':
if mode == 'text-to-image':
response = requests.post(
f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
headers={
"authorization": apikey,
"accept": "application/json"
},
files={"none": ''},
data={
"prompt": positive,
"aspect_ratio": aspect_ratio,
"mode": mode,
"model": model,
"seed": seed,
"output_format": "png",
},
)
elif mode == 'image-to-image':
pil_image = tensor2pil(image)
img_byte_arr = BytesIO()
pil_image.save(img_byte_arr, format='PNG')
#img_byte_arr = img_byte_arr.getvalue()
img_byte_arr.seek(0)
response = requests.post(
f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
headers={
"authorization": apikey,
"accept": "application/json"
},
files={
"image": ("image.png", img_byte_arr, 'image/png'),
},
data={
"prompt": positive,
"mode": mode,
"model": model,
"seed": seed,
"strength": strength,
"output_format": "png",
},
)
elif model == 'sd3':
if mode == 'text-to-image':
response = requests.post(
f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
headers={
"authorization": apikey,
"accept": "application/json"
},
files={"none": ''},
data={
"prompt": positive,
"negative_prompt": negative,
"aspect_ratio": aspect_ratio,
"mode": mode,
"model": model,
"seed": seed,
"output_format": "png",
},
)
elif mode == 'image-to-image':
pil_image = tensor2pil(image)
img_byte_arr = BytesIO()
pil_image.save(img_byte_arr, format='PNG')
#img_byte_arr = img_byte_arr.getvalue()
img_byte_arr.seek(0)
response = requests.post(
f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
headers={
"authorization": apikey,
"accept": "application/json"
},
files={
"image": ("image.png", img_byte_arr, 'image/png'),
},
data={
"prompt": positive,
"negative_prompt": negative,
"mode": mode,
"model": model,
"seed": seed,
"strength": strength,
"output_format": "png",
},
)
if response.status_code == 200:
json_data = response.json()
image_base64 = json_data['image']
image_bytes = base64.b64decode(image_base64)
image_data = Image.open(io.BytesIO(image_bytes))
output_t = pil2tensor(image_data)
print(output_t.shape)
return (output_t,)
else:
# 错误处理
if response.headers['Content-Type'] == 'application/json':
error_info = response.json()
print("Error name:", error_info.get('name', 'No name provided'))
print("Error details:", error_info.get('errors', ['No details provided']))
print("Response Text:", response.text)
raise Exception(f"Failed to fetch image: {response.status_code}")
NODE_CLASS_MAPPINGS = {
"SD3_Zho": SD3_Zho,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"SD3_Zho": "🔥Stable Diffusion 3",
}