-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
305 lines (244 loc) · 7.68 KB
/
utils.py
File metadata and controls
305 lines (244 loc) · 7.68 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14186/
# Hack to fix a changed import in torchvision 0.17+, which otherwise breaks
# basicsr; see https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/13985
import sys
try:
import torchvision.transforms.functional_tensor # type: ignore
except ImportError:
try:
import torchvision.transforms.functional as functional
sys.modules["torchvision.transforms.functional_tensor"] = functional
except ImportError:
pass # shrug...
from diffusers.utils.loading_utils import load_image
from basicsr.archs.rrdbnet_arch import RRDBNet
from PIL import Image, UnidentifiedImageError
from diffusers import StableDiffusionPipeline
from torchvision.transforms import ToTensor
from pipeline import AllInOnePipeline
from realesrgan import RealESRGANer
from dataclasses import dataclass
from torch import Generator
import numpy as np
import discord
import asyncio
import torch
import os
import io
to_tensor = ToTensor()
# factors for fast latent decoding
rgb_latent_factors = torch.Tensor(
[
[0.298, 0.207, 0.208],
[0.187, 0.286, 0.173],
[-0.158, 0.189, 0.264],
[-0.184, -0.271, -0.473],
]
)
@dataclass
class BaseGenerationRequest:
interaction: discord.Interaction
model: str
prompt: str
negative_prompt: str | None
guidance_scale: float
step_count: int
seed: int
@dataclass
class Text2ImgGenerationRequest(BaseGenerationRequest):
width: int
height: int
ptype = "text2img"
@dataclass
class Img2ImgGenerationRequest(BaseGenerationRequest):
image: Image.Image
ptype = "img2img"
@dataclass
class InpaintGenerationRequest(BaseGenerationRequest):
mask: Image.Image
ptype = "inpaint"
GenerationRequest = (
BaseGenerationRequest
| Text2ImgGenerationRequest
| Img2ImgGenerationRequest
| InpaintGenerationRequest
)
def error(msg):
return f"**Error:** {msg}"
def edit(
loop: asyncio.AbstractEventLoop,
interaction: discord.Interaction,
msg: str = None,
embed: discord.Embed = None,
attachments: list[discord.File] = [],
):
asyncio.run_coroutine_threadsafe(
interaction.edit_original_response(
content=msg,
embed=embed,
attachments=attachments,
),
loop,
)
def load_model(
model_path: str,
device: str,
pipe_setup_func,
embeddings: list[str] = [],
loras: list[str] = [],
):
return AllInOnePipeline(
model_path,
device,
pipe_setup_func,
embeddings,
loras,
)
def load_models(
models: dict[str, str],
device: str,
pipe_setup_func,
embeddings: list[str] = [],
loras: list[str] = [],
) -> dict[str, AllInOnePipeline]:
return {
key: load_model(path, device, pipe_setup_func, embeddings, loras)
for key, path in models.items()
}
def load_esrgan_model(
model_path: str,
device: str,
model_name: str = None,
):
if model_name is None:
model_name = get_filename(model_path)
if model_name in [
"RealESRGAN_x4plus",
"RealESRNet_x4plus",
]: # x4 RRDBNet model
model = RRDBNet(
num_in_ch=3,
num_out_ch=3,
num_feat=64,
num_block=23,
num_grow_ch=32,
scale=4,
)
elif model_name == "RealESRGAN_x4plus_anime_6B": # x4 RRDBNet model with 6 blocks
model = RRDBNet(
num_in_ch=3,
num_out_ch=3,
num_feat=64,
num_block=6,
num_grow_ch=32,
scale=4,
)
elif model_name == "RealESRGAN_x2plus": # x2 RRDBNet model
model = RRDBNet(
num_in_ch=3,
num_out_ch=3,
num_feat=64,
num_block=23,
num_grow_ch=32,
scale=2,
)
else:
raise ValueError("Failed to determine ESRGAN model type.")
esrgan_model = RealESRGANer(
scale=model.scale,
device=device,
model_path=model_path,
model=model,
)
esrgan_model.model_name = model_name
return esrgan_model
def create_torch_generator(seed: int | None = None, device: str = "cpu") -> Generator:
gen = Generator(device=device)
if seed:
gen.manual_seed(seed)
else:
gen.seed()
return gen
def path_join(paths: list[str], sep: str = ";") -> str:
return sep.join([path.replace(",", "\\,").replace(";", "\\;") for path in paths])
def fast_decode(latent: torch.Tensor):
image = latent.permute(1, 2, 0).cpu() @ rgb_latent_factors
return Image.fromarray((255 * image).numpy().astype(np.uint8))
def check_img_nsfw(pipeline: StableDiffusionPipeline, image) -> bool | None:
if (
not hasattr(pipeline, "orig_safety_checker")
or pipeline.orig_safety_checker is None
):
return None
features = pipeline.feature_extractor([image], return_tensors="pt")
features = features.to(pipeline._execution_device)
_, has_nsfw_concept = pipeline.orig_safety_checker(
images=to_tensor(image),
clip_input=features.pixel_values.to(pipeline.text_encoder.dtype),
)
return has_nsfw_concept[0]
def add_fields(embed: discord.Embed, fields: dict) -> None:
for name, value in fields.items():
embed.add_field(name=name, value=value)
def get_embed_color(color: str | list | tuple) -> discord.Colour:
if type(color) in [list, tuple]:
return discord.Color.from_rgb(color)
elif hasattr(discord.Color, color):
return getattr(discord.Color, color)()
else:
return discord.Color.from_str(color)
def get_filename(path: str) -> str:
return os.path.basename(path).split(".")[0]
async def load_image_from_message(
message: discord.Message,
) -> tuple[Image.Image, discord.Attachment]:
attachments = message.attachments
if len(attachments) == 0:
raise ValueError(f"There are no attachments attached to the message.")
try:
attachment = next(
attachment
for attachment in attachments
if attachment.content_type.startswith("image")
)
except StopIteration:
raise ValueError(f"There are no images attached to the message.")
try:
# open file bytes as PIL image
image = Image.open(io.BytesIO(await attachment.read()))
except UnidentifiedImageError:
raise ValueError("File could not be read as an image.")
return image, attachment
async def load_image_from_args(
message_id: str = None,
url: str = None,
file: discord.Attachment = None,
channel: discord.TextChannel = None,
) -> tuple[Image.Image, None | discord.Attachment]:
attachment = None
if message_id:
try:
message = await channel.fetch_message(int(message_id))
except ValueError:
raise ValueError("Message ID is not an ID.")
except Exception:
raise ValueError(f"Could not find message {message_id}!")
image, attachment = await load_image_from_message(message)
elif url:
try:
image = load_image(url)
except UnidentifiedImageError:
raise ValueError("URL response could not be read as an image.")
except ValueError:
raise ValueError("Invalid URL.")
elif file:
if not file.content_type.startswith("image/"):
raise ValueError("File provided is not an image.")
try:
# open file bytes as PIL image
image = Image.open(io.BytesIO(await file.read()))
except UnidentifiedImageError:
raise ValueError("File could not be read as an image.")
else:
raise ValueError("No image provided.")
return image, attachment