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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import sys
|
3 |
+
import traceback
|
4 |
+
|
5 |
+
import pytz
|
6 |
+
import io
|
7 |
+
import math
|
8 |
+
import os
|
9 |
+
from collections import namedtuple
|
10 |
+
import re
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import piexif
|
14 |
+
import piexif.helper
|
15 |
+
from PIL import Image, ImageFont, ImageDraw, PngImagePlugin
|
16 |
+
from fonts.ttf import Roboto
|
17 |
+
import string
|
18 |
+
import json
|
19 |
+
import hashlib
|
20 |
+
|
21 |
+
from modules import sd_samplers, shared, script_callbacks, errors
|
22 |
+
from modules.shared import opts, cmd_opts
|
23 |
+
|
24 |
+
|
25 |
+
from pathlib import Path
|
26 |
+
from huggingface_hub import HfApi, login
|
27 |
+
|
28 |
+
LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
|
29 |
+
|
30 |
+
|
31 |
+
def image_grid(imgs, batch_size=1, rows=None):
|
32 |
+
if rows is None:
|
33 |
+
if opts.n_rows > 0:
|
34 |
+
rows = opts.n_rows
|
35 |
+
elif opts.n_rows == 0:
|
36 |
+
rows = batch_size
|
37 |
+
elif opts.grid_prevent_empty_spots:
|
38 |
+
rows = math.floor(math.sqrt(len(imgs)))
|
39 |
+
while len(imgs) % rows != 0:
|
40 |
+
rows -= 1
|
41 |
+
else:
|
42 |
+
rows = math.sqrt(len(imgs))
|
43 |
+
rows = round(rows)
|
44 |
+
if rows > len(imgs):
|
45 |
+
rows = len(imgs)
|
46 |
+
|
47 |
+
cols = math.ceil(len(imgs) / rows)
|
48 |
+
|
49 |
+
params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
|
50 |
+
script_callbacks.image_grid_callback(params)
|
51 |
+
|
52 |
+
w, h = imgs[0].size
|
53 |
+
grid = Image.new('RGB', size=(params.cols * w, params.rows * h), color='black')
|
54 |
+
|
55 |
+
for i, img in enumerate(params.imgs):
|
56 |
+
grid.paste(img, box=(i % params.cols * w, i // params.cols * h))
|
57 |
+
|
58 |
+
return grid
|
59 |
+
|
60 |
+
|
61 |
+
Grid = namedtuple("Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])
|
62 |
+
|
63 |
+
|
64 |
+
def split_grid(image, tile_w=512, tile_h=512, overlap=64):
|
65 |
+
w = image.width
|
66 |
+
h = image.height
|
67 |
+
|
68 |
+
non_overlap_width = tile_w - overlap
|
69 |
+
non_overlap_height = tile_h - overlap
|
70 |
+
|
71 |
+
cols = math.ceil((w - overlap) / non_overlap_width)
|
72 |
+
rows = math.ceil((h - overlap) / non_overlap_height)
|
73 |
+
|
74 |
+
dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
|
75 |
+
dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
|
76 |
+
|
77 |
+
grid = Grid([], tile_w, tile_h, w, h, overlap)
|
78 |
+
for row in range(rows):
|
79 |
+
row_images = []
|
80 |
+
|
81 |
+
y = int(row * dy)
|
82 |
+
|
83 |
+
if y + tile_h >= h:
|
84 |
+
y = h - tile_h
|
85 |
+
|
86 |
+
for col in range(cols):
|
87 |
+
x = int(col * dx)
|
88 |
+
|
89 |
+
if x + tile_w >= w:
|
90 |
+
x = w - tile_w
|
91 |
+
|
92 |
+
tile = image.crop((x, y, x + tile_w, y + tile_h))
|
93 |
+
|
94 |
+
row_images.append([x, tile_w, tile])
|
95 |
+
|
96 |
+
grid.tiles.append([y, tile_h, row_images])
|
97 |
+
|
98 |
+
return grid
|
99 |
+
|
100 |
+
|
101 |
+
def combine_grid(grid):
|
102 |
+
def make_mask_image(r):
|
103 |
+
r = r * 255 / grid.overlap
|
104 |
+
r = r.astype(np.uint8)
|
105 |
+
return Image.fromarray(r, 'L')
|
106 |
+
|
107 |
+
mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
|
108 |
+
mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
|
109 |
+
|
110 |
+
combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
|
111 |
+
for y, h, row in grid.tiles:
|
112 |
+
combined_row = Image.new("RGB", (grid.image_w, h))
|
113 |
+
for x, w, tile in row:
|
114 |
+
if x == 0:
|
115 |
+
combined_row.paste(tile, (0, 0))
|
116 |
+
continue
|
117 |
+
|
118 |
+
combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
|
119 |
+
combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
|
120 |
+
|
121 |
+
if y == 0:
|
122 |
+
combined_image.paste(combined_row, (0, 0))
|
123 |
+
continue
|
124 |
+
|
125 |
+
combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
|
126 |
+
combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
|
127 |
+
|
128 |
+
return combined_image
|
129 |
+
|
130 |
+
|
131 |
+
class GridAnnotation:
|
132 |
+
def __init__(self, text='', is_active=True):
|
133 |
+
self.text = text
|
134 |
+
self.is_active = is_active
|
135 |
+
self.size = None
|
136 |
+
|
137 |
+
|
138 |
+
def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
|
139 |
+
def wrap(drawing, text, font, line_length):
|
140 |
+
lines = ['']
|
141 |
+
for word in text.split():
|
142 |
+
line = f'{lines[-1]} {word}'.strip()
|
143 |
+
if drawing.textlength(line, font=font) <= line_length:
|
144 |
+
lines[-1] = line
|
145 |
+
else:
|
146 |
+
lines.append(word)
|
147 |
+
return lines
|
148 |
+
|
149 |
+
def get_font(fontsize):
|
150 |
+
try:
|
151 |
+
return ImageFont.truetype(opts.font or Roboto, fontsize)
|
152 |
+
except Exception:
|
153 |
+
return ImageFont.truetype(Roboto, fontsize)
|
154 |
+
|
155 |
+
def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
|
156 |
+
for i, line in enumerate(lines):
|
157 |
+
fnt = initial_fnt
|
158 |
+
fontsize = initial_fontsize
|
159 |
+
while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0:
|
160 |
+
fontsize -= 1
|
161 |
+
fnt = get_font(fontsize)
|
162 |
+
drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center")
|
163 |
+
|
164 |
+
if not line.is_active:
|
165 |
+
drawing.line((draw_x - line.size[0] // 2, draw_y + line.size[1] // 2, draw_x + line.size[0] // 2, draw_y + line.size[1] // 2), fill=color_inactive, width=4)
|
166 |
+
|
167 |
+
draw_y += line.size[1] + line_spacing
|
168 |
+
|
169 |
+
fontsize = (width + height) // 25
|
170 |
+
line_spacing = fontsize // 2
|
171 |
+
|
172 |
+
fnt = get_font(fontsize)
|
173 |
+
|
174 |
+
color_active = (0, 0, 0)
|
175 |
+
color_inactive = (153, 153, 153)
|
176 |
+
|
177 |
+
pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
|
178 |
+
|
179 |
+
cols = im.width // width
|
180 |
+
rows = im.height // height
|
181 |
+
|
182 |
+
assert cols == len(hor_texts), f'bad number of horizontal texts: {len(hor_texts)}; must be {cols}'
|
183 |
+
assert rows == len(ver_texts), f'bad number of vertical texts: {len(ver_texts)}; must be {rows}'
|
184 |
+
|
185 |
+
calc_img = Image.new("RGB", (1, 1), "white")
|
186 |
+
calc_d = ImageDraw.Draw(calc_img)
|
187 |
+
|
188 |
+
for texts, allowed_width in zip(hor_texts + ver_texts, [width] * len(hor_texts) + [pad_left] * len(ver_texts)):
|
189 |
+
items = [] + texts
|
190 |
+
texts.clear()
|
191 |
+
|
192 |
+
for line in items:
|
193 |
+
wrapped = wrap(calc_d, line.text, fnt, allowed_width)
|
194 |
+
texts += [GridAnnotation(x, line.is_active) for x in wrapped]
|
195 |
+
|
196 |
+
for line in texts:
|
197 |
+
bbox = calc_d.multiline_textbbox((0, 0), line.text, font=fnt)
|
198 |
+
line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
|
199 |
+
line.allowed_width = allowed_width
|
200 |
+
|
201 |
+
hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
|
202 |
+
ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
|
203 |
+
|
204 |
+
pad_top = 0 if sum(hor_text_heights) == 0 else max(hor_text_heights) + line_spacing * 2
|
205 |
+
|
206 |
+
result = Image.new("RGB", (im.width + pad_left + margin * (cols-1), im.height + pad_top + margin * (rows-1)), "white")
|
207 |
+
|
208 |
+
for row in range(rows):
|
209 |
+
for col in range(cols):
|
210 |
+
cell = im.crop((width * col, height * row, width * (col+1), height * (row+1)))
|
211 |
+
result.paste(cell, (pad_left + (width + margin) * col, pad_top + (height + margin) * row))
|
212 |
+
|
213 |
+
d = ImageDraw.Draw(result)
|
214 |
+
|
215 |
+
for col in range(cols):
|
216 |
+
x = pad_left + (width + margin) * col + width / 2
|
217 |
+
y = pad_top / 2 - hor_text_heights[col] / 2
|
218 |
+
|
219 |
+
draw_texts(d, x, y, hor_texts[col], fnt, fontsize)
|
220 |
+
|
221 |
+
for row in range(rows):
|
222 |
+
x = pad_left / 2
|
223 |
+
y = pad_top + (height + margin) * row + height / 2 - ver_text_heights[row] / 2
|
224 |
+
|
225 |
+
draw_texts(d, x, y, ver_texts[row], fnt, fontsize)
|
226 |
+
|
227 |
+
return result
|
228 |
+
|
229 |
+
|
230 |
+
def draw_prompt_matrix(im, width, height, all_prompts, margin=0):
|
231 |
+
prompts = all_prompts[1:]
|
232 |
+
boundary = math.ceil(len(prompts) / 2)
|
233 |
+
|
234 |
+
prompts_horiz = prompts[:boundary]
|
235 |
+
prompts_vert = prompts[boundary:]
|
236 |
+
|
237 |
+
hor_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_horiz)] for pos in range(1 << len(prompts_horiz))]
|
238 |
+
ver_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_vert)] for pos in range(1 << len(prompts_vert))]
|
239 |
+
|
240 |
+
return draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin)
|
241 |
+
|
242 |
+
|
243 |
+
def resize_image(resize_mode, im, width, height, upscaler_name=None):
|
244 |
+
"""
|
245 |
+
Resizes an image with the specified resize_mode, width, and height.
|
246 |
+
|
247 |
+
Args:
|
248 |
+
resize_mode: The mode to use when resizing the image.
|
249 |
+
0: Resize the image to the specified width and height.
|
250 |
+
1: Resize the image to fill the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess.
|
251 |
+
2: Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image.
|
252 |
+
im: The image to resize.
|
253 |
+
width: The width to resize the image to.
|
254 |
+
height: The height to resize the image to.
|
255 |
+
upscaler_name: The name of the upscaler to use. If not provided, defaults to opts.upscaler_for_img2img.
|
256 |
+
"""
|
257 |
+
|
258 |
+
upscaler_name = upscaler_name or opts.upscaler_for_img2img
|
259 |
+
|
260 |
+
def resize(im, w, h):
|
261 |
+
if upscaler_name is None or upscaler_name == "None" or im.mode == 'L':
|
262 |
+
return im.resize((w, h), resample=LANCZOS)
|
263 |
+
|
264 |
+
scale = max(w / im.width, h / im.height)
|
265 |
+
|
266 |
+
if scale > 1.0:
|
267 |
+
upscalers = [x for x in shared.sd_upscalers if x.name == upscaler_name]
|
268 |
+
if len(upscalers) == 0:
|
269 |
+
upscaler = shared.sd_upscalers[0]
|
270 |
+
print(f"could not find upscaler named {upscaler_name or '<empty string>'}, using {upscaler.name} as a fallback")
|
271 |
+
else:
|
272 |
+
upscaler = upscalers[0]
|
273 |
+
|
274 |
+
im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
|
275 |
+
|
276 |
+
if im.width != w or im.height != h:
|
277 |
+
im = im.resize((w, h), resample=LANCZOS)
|
278 |
+
|
279 |
+
return im
|
280 |
+
|
281 |
+
if resize_mode == 0:
|
282 |
+
res = resize(im, width, height)
|
283 |
+
|
284 |
+
elif resize_mode == 1:
|
285 |
+
ratio = width / height
|
286 |
+
src_ratio = im.width / im.height
|
287 |
+
|
288 |
+
src_w = width if ratio > src_ratio else im.width * height // im.height
|
289 |
+
src_h = height if ratio <= src_ratio else im.height * width // im.width
|
290 |
+
|
291 |
+
resized = resize(im, src_w, src_h)
|
292 |
+
res = Image.new("RGB", (width, height))
|
293 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
294 |
+
|
295 |
+
else:
|
296 |
+
ratio = width / height
|
297 |
+
src_ratio = im.width / im.height
|
298 |
+
|
299 |
+
src_w = width if ratio < src_ratio else im.width * height // im.height
|
300 |
+
src_h = height if ratio >= src_ratio else im.height * width // im.width
|
301 |
+
|
302 |
+
resized = resize(im, src_w, src_h)
|
303 |
+
res = Image.new("RGB", (width, height))
|
304 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
305 |
+
|
306 |
+
if ratio < src_ratio:
|
307 |
+
fill_height = height // 2 - src_h // 2
|
308 |
+
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
|
309 |
+
res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h))
|
310 |
+
elif ratio > src_ratio:
|
311 |
+
fill_width = width // 2 - src_w // 2
|
312 |
+
res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
|
313 |
+
res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0))
|
314 |
+
|
315 |
+
return res
|
316 |
+
|
317 |
+
|
318 |
+
invalid_filename_chars = '<>:"/\\|?*\n'
|
319 |
+
invalid_filename_prefix = ' '
|
320 |
+
invalid_filename_postfix = ' .'
|
321 |
+
re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
|
322 |
+
re_pattern = re.compile(r"(.*?)(?:\[([^\[\]]+)\]|$)")
|
323 |
+
re_pattern_arg = re.compile(r"(.*)<([^>]*)>$")
|
324 |
+
max_filename_part_length = 128
|
325 |
+
NOTHING_AND_SKIP_PREVIOUS_TEXT = object()
|
326 |
+
|
327 |
+
|
328 |
+
def sanitize_filename_part(text, replace_spaces=True):
|
329 |
+
if text is None:
|
330 |
+
return None
|
331 |
+
|
332 |
+
if replace_spaces:
|
333 |
+
text = text.replace(' ', '_')
|
334 |
+
|
335 |
+
text = text.translate({ord(x): '_' for x in invalid_filename_chars})
|
336 |
+
text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
|
337 |
+
text = text.rstrip(invalid_filename_postfix)
|
338 |
+
return text
|
339 |
+
|
340 |
+
|
341 |
+
class FilenameGenerator:
|
342 |
+
replacements = {
|
343 |
+
'seed': lambda self: self.seed if self.seed is not None else '',
|
344 |
+
'steps': lambda self: self.p and self.p.steps,
|
345 |
+
'cfg': lambda self: self.p and self.p.cfg_scale,
|
346 |
+
'width': lambda self: self.image.width,
|
347 |
+
'height': lambda self: self.image.height,
|
348 |
+
'styles': lambda self: self.p and sanitize_filename_part(", ".join([style for style in self.p.styles if not style == "None"]) or "None", replace_spaces=False),
|
349 |
+
'sampler': lambda self: self.p and sanitize_filename_part(self.p.sampler_name, replace_spaces=False),
|
350 |
+
'model_hash': lambda self: getattr(self.p, "sd_model_hash", shared.sd_model.sd_model_hash),
|
351 |
+
'model_name': lambda self: sanitize_filename_part(shared.sd_model.sd_checkpoint_info.model_name, replace_spaces=False),
|
352 |
+
'date': lambda self: datetime.datetime.now().strftime('%Y-%m-%d'),
|
353 |
+
'datetime': lambda self, *args: self.datetime(*args), # accepts formats: [datetime], [datetime<Format>], [datetime<Format><Time Zone>]
|
354 |
+
'job_timestamp': lambda self: getattr(self.p, "job_timestamp", shared.state.job_timestamp),
|
355 |
+
'prompt_hash': lambda self: hashlib.sha256(self.prompt.encode()).hexdigest()[0:8],
|
356 |
+
'prompt': lambda self: sanitize_filename_part(self.prompt),
|
357 |
+
'prompt_no_styles': lambda self: self.prompt_no_style(),
|
358 |
+
'prompt_spaces': lambda self: sanitize_filename_part(self.prompt, replace_spaces=False),
|
359 |
+
'prompt_words': lambda self: self.prompt_words(),
|
360 |
+
'batch_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 else self.p.batch_index + 1,
|
361 |
+
'generation_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.n_iter == 1 and self.p.batch_size == 1 else self.p.iteration * self.p.batch_size + self.p.batch_index + 1,
|
362 |
+
'hasprompt': lambda self, *args: self.hasprompt(*args), # accepts formats:[hasprompt<prompt1|default><prompt2>..]
|
363 |
+
'clip_skip': lambda self: opts.data["CLIP_stop_at_last_layers"],
|
364 |
+
}
|
365 |
+
default_time_format = '%Y%m%d%H%M%S'
|
366 |
+
|
367 |
+
def __init__(self, p, seed, prompt, image):
|
368 |
+
self.p = p
|
369 |
+
self.seed = seed
|
370 |
+
self.prompt = prompt
|
371 |
+
self.image = image
|
372 |
+
|
373 |
+
def hasprompt(self, *args):
|
374 |
+
lower = self.prompt.lower()
|
375 |
+
if self.p is None or self.prompt is None:
|
376 |
+
return None
|
377 |
+
outres = ""
|
378 |
+
for arg in args:
|
379 |
+
if arg != "":
|
380 |
+
division = arg.split("|")
|
381 |
+
expected = division[0].lower()
|
382 |
+
default = division[1] if len(division) > 1 else ""
|
383 |
+
if lower.find(expected) >= 0:
|
384 |
+
outres = f'{outres}{expected}'
|
385 |
+
else:
|
386 |
+
outres = outres if default == "" else f'{outres}{default}'
|
387 |
+
return sanitize_filename_part(outres)
|
388 |
+
|
389 |
+
def prompt_no_style(self):
|
390 |
+
if self.p is None or self.prompt is None:
|
391 |
+
return None
|
392 |
+
|
393 |
+
prompt_no_style = self.prompt
|
394 |
+
for style in shared.prompt_styles.get_style_prompts(self.p.styles):
|
395 |
+
if len(style) > 0:
|
396 |
+
for part in style.split("{prompt}"):
|
397 |
+
prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
|
398 |
+
|
399 |
+
prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
|
400 |
+
|
401 |
+
return sanitize_filename_part(prompt_no_style, replace_spaces=False)
|
402 |
+
|
403 |
+
def prompt_words(self):
|
404 |
+
words = [x for x in re_nonletters.split(self.prompt or "") if len(x) > 0]
|
405 |
+
if len(words) == 0:
|
406 |
+
words = ["empty"]
|
407 |
+
return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
|
408 |
+
|
409 |
+
def datetime(self, *args):
|
410 |
+
time_datetime = datetime.datetime.now()
|
411 |
+
|
412 |
+
time_format = args[0] if len(args) > 0 and args[0] != "" else self.default_time_format
|
413 |
+
try:
|
414 |
+
time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
|
415 |
+
except pytz.exceptions.UnknownTimeZoneError as _:
|
416 |
+
time_zone = None
|
417 |
+
|
418 |
+
time_zone_time = time_datetime.astimezone(time_zone)
|
419 |
+
try:
|
420 |
+
formatted_time = time_zone_time.strftime(time_format)
|
421 |
+
except (ValueError, TypeError) as _:
|
422 |
+
formatted_time = time_zone_time.strftime(self.default_time_format)
|
423 |
+
|
424 |
+
return sanitize_filename_part(formatted_time, replace_spaces=False)
|
425 |
+
|
426 |
+
def apply(self, x):
|
427 |
+
res = ''
|
428 |
+
|
429 |
+
for m in re_pattern.finditer(x):
|
430 |
+
text, pattern = m.groups()
|
431 |
+
|
432 |
+
if pattern is None:
|
433 |
+
res += text
|
434 |
+
continue
|
435 |
+
|
436 |
+
pattern_args = []
|
437 |
+
while True:
|
438 |
+
m = re_pattern_arg.match(pattern)
|
439 |
+
if m is None:
|
440 |
+
break
|
441 |
+
|
442 |
+
pattern, arg = m.groups()
|
443 |
+
pattern_args.insert(0, arg)
|
444 |
+
|
445 |
+
fun = self.replacements.get(pattern.lower())
|
446 |
+
if fun is not None:
|
447 |
+
try:
|
448 |
+
replacement = fun(self, *pattern_args)
|
449 |
+
except Exception:
|
450 |
+
replacement = None
|
451 |
+
print(f"Error adding [{pattern}] to filename", file=sys.stderr)
|
452 |
+
print(traceback.format_exc(), file=sys.stderr)
|
453 |
+
|
454 |
+
if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
|
455 |
+
continue
|
456 |
+
elif replacement is not None:
|
457 |
+
res += text + str(replacement)
|
458 |
+
continue
|
459 |
+
|
460 |
+
res += f'{text}[{pattern}]'
|
461 |
+
|
462 |
+
return res
|
463 |
+
|
464 |
+
|
465 |
+
def get_next_sequence_number(path, basename):
|
466 |
+
"""
|
467 |
+
Determines and returns the next sequence number to use when saving an image in the specified directory.
|
468 |
+
|
469 |
+
The sequence starts at 0.
|
470 |
+
"""
|
471 |
+
result = -1
|
472 |
+
if basename != '':
|
473 |
+
basename = basename + "-"
|
474 |
+
|
475 |
+
prefix_length = len(basename)
|
476 |
+
for p in os.listdir(path):
|
477 |
+
if p.startswith(basename):
|
478 |
+
l = os.path.splitext(p[prefix_length:])[0].split('-') # splits the filename (removing the basename first if one is defined, so the sequence number is always the first element)
|
479 |
+
try:
|
480 |
+
result = max(int(l[0]), result)
|
481 |
+
except ValueError:
|
482 |
+
pass
|
483 |
+
|
484 |
+
return result + 1
|
485 |
+
#功能函数,删除图片
|
486 |
+
def delsdimg(fullfn_without_extension, extension):
|
487 |
+
fullfn_without_extension = fullfn_without_extension
|
488 |
+
extension = extension
|
489 |
+
hgfilename = f"{fullfn_without_extension}{extension}"
|
490 |
+
hgpath, tempfilename = os.path.split(hgfilename)
|
491 |
+
hgname, hghzm = os.path.splitext(tempfilename)
|
492 |
+
hgnames =f'{hgname}{extension}'
|
493 |
+
os.chdir(f'{hgpath}')
|
494 |
+
os.remove(hgnames)
|
495 |
+
print(f'成功删除图片:{hgnames}')
|
496 |
+
|
497 |
+
#功能函数,上传图片
|
498 |
+
def uploadhg(fullfn_without_extension, extension):
|
499 |
+
fullfn_without_extension = fullfn_without_extension
|
500 |
+
extension = extension
|
501 |
+
hgfilename = f"{fullfn_without_extension}{extension}"
|
502 |
+
|
503 |
+
hgpath, tempfilename = os.path.split(hgfilename)
|
504 |
+
hgname, hghzm = os.path.splitext(tempfilename)
|
505 |
+
|
506 |
+
print(f'hgpath:{hgpath}')
|
507 |
+
|
508 |
+
print(f'hgname:{hgname}')
|
509 |
+
|
510 |
+
print(f'hghzm:{hghzm}')
|
511 |
+
|
512 |
+
hgnames =f'{hgname}{extension}'
|
513 |
+
huggingface_use = True
|
514 |
+
huggingface_token_file = '/kaggle/working/hugfacetoken.txt'
|
515 |
+
huggiingface_repo_id = 'xiemoxiaoshaso/image'
|
516 |
+
# 将会同步的文件
|
517 |
+
yun_files = [
|
518 |
+
f'{hgnames}',
|
519 |
+
]
|
520 |
+
if huggingface_use == True:
|
521 |
+
hgurl = hugface_upload(huggingface_token_file,yun_files,huggiingface_repo_id,hgpath)
|
522 |
+
return hgurl
|
523 |
+
|
524 |
+
#功能函数,上传图片
|
525 |
+
def hugface_upload(huggingface_token_file, yun_files, repo_id, hgpath):
|
526 |
+
if Path(huggingface_token_file).exists():
|
527 |
+
with open(huggingface_token_file, encoding="utf-8") as nkfile:
|
528 |
+
hugToken = nkfile.readline()
|
529 |
+
if hugToken != '':
|
530 |
+
# 使用您的 Hugging Face 访问令牌登录
|
531 |
+
login(token=hugToken)
|
532 |
+
# 实例化 HfApi 类
|
533 |
+
api = HfApi()
|
534 |
+
print("HfApi 类已实例化")
|
535 |
+
dqml = "/kaggle/working/stable-diffusion-webui/"
|
536 |
+
#hgpaths = f'{dqml}{hgpath}'
|
537 |
+
os.chdir(f'{hgpath}')
|
538 |
+
# 使用 upload_file() 函数上传文件
|
539 |
+
print("开始上传文件...")
|
540 |
+
for yun_file in yun_files:
|
541 |
+
if Path(yun_file).exists():
|
542 |
+
response = api.upload_file(
|
543 |
+
path_or_fileobj=yun_file,
|
544 |
+
path_in_repo=yun_file,
|
545 |
+
repo_id=repo_id,
|
546 |
+
repo_type="dataset"
|
547 |
+
)
|
548 |
+
print(f"文件上传完成{response}")
|
549 |
+
os.chdir(f'{dqml}')
|
550 |
+
return response
|
551 |
+
else:
|
552 |
+
print(f'Error: File {yun_file} does not exist')
|
553 |
+
return
|
554 |
+
os.chdir(f'{dqml}')
|
555 |
+
else:
|
556 |
+
print(f'Error: File {huggingface_token_file} does not exist')
|
557 |
+
os.chdir(f'{dqml}')
|
558 |
+
|
559 |
+
|
560 |
+
|
561 |
+
def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name='parameters', p=None, existing_info=None, forced_filename=None, suffix="", save_to_dirs=None):
|
562 |
+
"""Save an image.
|
563 |
+
|
564 |
+
Args:
|
565 |
+
image (`PIL.Image`):
|
566 |
+
The image to be saved.
|
567 |
+
path (`str`):
|
568 |
+
The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
|
569 |
+
basename (`str`):
|
570 |
+
The base filename which will be applied to `filename pattern`.
|
571 |
+
seed, prompt, short_filename,
|
572 |
+
extension (`str`):
|
573 |
+
Image file extension, default is `png`.
|
574 |
+
pngsectionname (`str`):
|
575 |
+
Specify the name of the section which `info` will be saved in.
|
576 |
+
info (`str` or `PngImagePlugin.iTXt`):
|
577 |
+
PNG info chunks.
|
578 |
+
existing_info (`dict`):
|
579 |
+
Additional PNG info. `existing_info == {pngsectionname: info, ...}`
|
580 |
+
no_prompt:
|
581 |
+
TODO I don't know its meaning.
|
582 |
+
p (`StableDiffusionProcessing`)
|
583 |
+
forced_filename (`str`):
|
584 |
+
If specified, `basename` and filename pattern will be ignored.
|
585 |
+
save_to_dirs (bool):
|
586 |
+
If true, the image will be saved into a subdirectory of `path`.
|
587 |
+
|
588 |
+
Returns: (fullfn, txt_fullfn)
|
589 |
+
fullfn (`str`):
|
590 |
+
The full path of the saved imaged.
|
591 |
+
txt_fullfn (`str` or None):
|
592 |
+
If a text file is saved for this image, this will be its full path. Otherwise None.
|
593 |
+
"""
|
594 |
+
namegen = FilenameGenerator(p, seed, prompt, image)
|
595 |
+
|
596 |
+
if save_to_dirs is None:
|
597 |
+
save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
|
598 |
+
|
599 |
+
if save_to_dirs:
|
600 |
+
dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
|
601 |
+
path = os.path.join(path, dirname)
|
602 |
+
|
603 |
+
os.makedirs(path, exist_ok=True)
|
604 |
+
|
605 |
+
if forced_filename is None:
|
606 |
+
if short_filename or seed is None:
|
607 |
+
file_decoration = ""
|
608 |
+
elif opts.save_to_dirs:
|
609 |
+
file_decoration = opts.samples_filename_pattern or "[seed]"
|
610 |
+
else:
|
611 |
+
file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
|
612 |
+
|
613 |
+
add_number = opts.save_images_add_number or file_decoration == ''
|
614 |
+
|
615 |
+
if file_decoration != "" and add_number:
|
616 |
+
file_decoration = "-" + file_decoration
|
617 |
+
|
618 |
+
file_decoration = namegen.apply(file_decoration) + suffix
|
619 |
+
|
620 |
+
if add_number:
|
621 |
+
basecount = get_next_sequence_number(path, basename)
|
622 |
+
fullfn = None
|
623 |
+
for i in range(500):
|
624 |
+
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
|
625 |
+
fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
|
626 |
+
if not os.path.exists(fullfn):
|
627 |
+
break
|
628 |
+
else:
|
629 |
+
fullfn = os.path.join(path, f"{file_decoration}.{extension}")
|
630 |
+
else:
|
631 |
+
fullfn = os.path.join(path, f"{forced_filename}.{extension}")
|
632 |
+
|
633 |
+
pnginfo = existing_info or {}
|
634 |
+
if info is not None:
|
635 |
+
pnginfo[pnginfo_section_name] = info
|
636 |
+
|
637 |
+
params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
|
638 |
+
script_callbacks.before_image_saved_callback(params)
|
639 |
+
|
640 |
+
image = params.image
|
641 |
+
fullfn = params.filename
|
642 |
+
info = params.pnginfo.get(pnginfo_section_name, None)
|
643 |
+
|
644 |
+
def _atomically_save_image(image_to_save, filename_without_extension, extension):
|
645 |
+
# save image with .tmp extension to avoid race condition when another process detects new image in the directory
|
646 |
+
temp_file_path = filename_without_extension + ".tmp"
|
647 |
+
image_format = Image.registered_extensions()[extension]
|
648 |
+
|
649 |
+
if extension.lower() == '.png':
|
650 |
+
pnginfo_data = PngImagePlugin.PngInfo()
|
651 |
+
if opts.enable_pnginfo:
|
652 |
+
for k, v in params.pnginfo.items():
|
653 |
+
pnginfo_data.add_text(k, str(v))
|
654 |
+
|
655 |
+
image_to_save.save(temp_file_path, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
|
656 |
+
|
657 |
+
elif extension.lower() in (".jpg", ".jpeg", ".webp"):
|
658 |
+
if image_to_save.mode == 'RGBA':
|
659 |
+
image_to_save = image_to_save.convert("RGB")
|
660 |
+
elif image_to_save.mode == 'I;16':
|
661 |
+
image_to_save = image_to_save.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
|
662 |
+
|
663 |
+
image_to_save.save(temp_file_path, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
|
664 |
+
|
665 |
+
if opts.enable_pnginfo and info is not None:
|
666 |
+
exif_bytes = piexif.dump({
|
667 |
+
"Exif": {
|
668 |
+
piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(info or "", encoding="unicode")
|
669 |
+
},
|
670 |
+
})
|
671 |
+
|
672 |
+
piexif.insert(exif_bytes, temp_file_path)
|
673 |
+
else:
|
674 |
+
image_to_save.save(temp_file_path, format=image_format, quality=opts.jpeg_quality)
|
675 |
+
|
676 |
+
# atomically rename the file with correct extension
|
677 |
+
os.replace(temp_file_path, filename_without_extension + extension)
|
678 |
+
|
679 |
+
fullfn_without_extension, extension = os.path.splitext(params.filename)
|
680 |
+
if hasattr(os, 'statvfs'):
|
681 |
+
max_name_len = os.statvfs(path).f_namemax
|
682 |
+
fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
|
683 |
+
params.filename = fullfn_without_extension + extension
|
684 |
+
fullfn = params.filename
|
685 |
+
|
686 |
+
dqml = "/kaggle/working/stable-diffusion-webui/"
|
687 |
+
os.chdir(f'{dqml}')
|
688 |
+
|
689 |
+
_atomically_save_image(image, fullfn_without_extension, extension)
|
690 |
+
#上传图片至抱脸
|
691 |
+
hgurl = uploadhg(fullfn_without_extension, extension)
|
692 |
+
|
693 |
+
|
694 |
+
image.already_saved_as = fullfn
|
695 |
+
|
696 |
+
oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
|
697 |
+
if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
|
698 |
+
ratio = image.width / image.height
|
699 |
+
|
700 |
+
if oversize and ratio > 1:
|
701 |
+
image = image.resize((round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)), LANCZOS)
|
702 |
+
elif oversize:
|
703 |
+
image = image.resize((round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)), LANCZOS)
|
704 |
+
|
705 |
+
try:
|
706 |
+
_atomically_save_image(image, fullfn_without_extension, ".jpg")
|
707 |
+
except Exception as e:
|
708 |
+
errors.display(e, "saving image as downscaled JPG")
|
709 |
+
|
710 |
+
if opts.save_txt and info is not None:
|
711 |
+
txt_fullfn = f"{fullfn_without_extension}.txt"
|
712 |
+
with open(txt_fullfn, "w", encoding="utf8") as file:
|
713 |
+
file.write(info + "\n")
|
714 |
+
else:
|
715 |
+
txt_fullfn = None
|
716 |
+
|
717 |
+
script_callbacks.image_saved_callback(params)
|
718 |
+
|
719 |
+
#上传成功后删除本地图片
|
720 |
+
#delsdimg(fullfn_without_extension, extension)
|
721 |
+
print(f'fullfn:{fullfn}')
|
722 |
+
print(f'hgurl:{hgurl}')
|
723 |
+
print(f'txt_fullfn:{txt_fullfn}')
|
724 |
+
fullfn = hgurl
|
725 |
+
return fullfn, txt_fullfn
|
726 |
+
|
727 |
+
|
728 |
+
def read_info_from_image(image):
|
729 |
+
items = image.info or {}
|
730 |
+
|
731 |
+
geninfo = items.pop('parameters', None)
|
732 |
+
|
733 |
+
if "exif" in items:
|
734 |
+
exif = piexif.load(items["exif"])
|
735 |
+
exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
|
736 |
+
try:
|
737 |
+
exif_comment = piexif.helper.UserComment.load(exif_comment)
|
738 |
+
except ValueError:
|
739 |
+
exif_comment = exif_comment.decode('utf8', errors="ignore")
|
740 |
+
|
741 |
+
if exif_comment:
|
742 |
+
items['exif comment'] = exif_comment
|
743 |
+
geninfo = exif_comment
|
744 |
+
|
745 |
+
for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
|
746 |
+
'loop', 'background', 'timestamp', 'duration']:
|
747 |
+
items.pop(field, None)
|
748 |
+
|
749 |
+
if items.get("Software", None) == "NovelAI":
|
750 |
+
try:
|
751 |
+
json_info = json.loads(items["Comment"])
|
752 |
+
sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
|
753 |
+
|
754 |
+
geninfo = f"""{items["Description"]}
|
755 |
+
Negative prompt: {json_info["uc"]}
|
756 |
+
Steps: {json_info["steps"]}, Sampler: {sampler}, CFG scale: {json_info["scale"]}, Seed: {json_info["seed"]}, Size: {image.width}x{image.height}, Clip skip: 2, ENSD: 31337"""
|
757 |
+
except Exception:
|
758 |
+
print("Error parsing NovelAI image generation parameters:", file=sys.stderr)
|
759 |
+
print(traceback.format_exc(), file=sys.stderr)
|
760 |
+
|
761 |
+
return geninfo, items
|
762 |
+
|
763 |
+
|
764 |
+
def image_data(data):
|
765 |
+
import gradio as gr
|
766 |
+
|
767 |
+
try:
|
768 |
+
image = Image.open(io.BytesIO(data))
|
769 |
+
textinfo, _ = read_info_from_image(image)
|
770 |
+
return textinfo, None
|
771 |
+
except Exception:
|
772 |
+
pass
|
773 |
+
|
774 |
+
try:
|
775 |
+
text = data.decode('utf8')
|
776 |
+
assert len(text) < 10000
|
777 |
+
return text, None
|
778 |
+
|
779 |
+
except Exception:
|
780 |
+
pass
|
781 |
+
|
782 |
+
return gr.update(), None
|
783 |
+
|
784 |
+
|
785 |
+
def flatten(img, bgcolor):
|
786 |
+
"""replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency"""
|
787 |
+
|
788 |
+
if img.mode == "RGBA":
|
789 |
+
background = Image.new('RGBA', img.size, bgcolor)
|
790 |
+
background.paste(img, mask=img)
|
791 |
+
img = background
|
792 |
+
|
793 |
+
return img.convert('RGB')
|