xiemoxiaoshaso commited on
Commit
61c3c81
·
1 Parent(s): b6b9b88

Upload images.py

Browse files
Files changed (1) hide show
  1. images.py +784 -0
images.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import string
17
+ import json
18
+ import hashlib
19
+
20
+ from modules import sd_samplers, shared, script_callbacks, errors
21
+ from modules.paths_internal import roboto_ttf_file
22
+ from modules.shared import opts
23
+
24
+ from pathlib import Path
25
+ from huggingface_hub import HfApi, login
26
+
27
+ LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
28
+
29
+
30
+ def get_font(fontsize: int):
31
+ try:
32
+ return ImageFont.truetype(opts.font or roboto_ttf_file, fontsize)
33
+ except Exception:
34
+ return ImageFont.truetype(roboto_ttf_file, fontsize)
35
+
36
+
37
+ def image_grid(imgs, batch_size=1, rows=None):
38
+ if rows is None:
39
+ if opts.n_rows > 0:
40
+ rows = opts.n_rows
41
+ elif opts.n_rows == 0:
42
+ rows = batch_size
43
+ elif opts.grid_prevent_empty_spots:
44
+ rows = math.floor(math.sqrt(len(imgs)))
45
+ while len(imgs) % rows != 0:
46
+ rows -= 1
47
+ else:
48
+ rows = math.sqrt(len(imgs))
49
+ rows = round(rows)
50
+ if rows > len(imgs):
51
+ rows = len(imgs)
52
+
53
+ cols = math.ceil(len(imgs) / rows)
54
+
55
+ params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
56
+ script_callbacks.image_grid_callback(params)
57
+
58
+ w, h = imgs[0].size
59
+ grid = Image.new('RGB', size=(params.cols * w, params.rows * h), color='black')
60
+
61
+ for i, img in enumerate(params.imgs):
62
+ grid.paste(img, box=(i % params.cols * w, i // params.cols * h))
63
+
64
+ return grid
65
+
66
+
67
+ Grid = namedtuple("Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])
68
+
69
+
70
+ def split_grid(image, tile_w=512, tile_h=512, overlap=64):
71
+ w = image.width
72
+ h = image.height
73
+
74
+ non_overlap_width = tile_w - overlap
75
+ non_overlap_height = tile_h - overlap
76
+
77
+ cols = math.ceil((w - overlap) / non_overlap_width)
78
+ rows = math.ceil((h - overlap) / non_overlap_height)
79
+
80
+ dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
81
+ dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
82
+
83
+ grid = Grid([], tile_w, tile_h, w, h, overlap)
84
+ for row in range(rows):
85
+ row_images = []
86
+
87
+ y = int(row * dy)
88
+
89
+ if y + tile_h >= h:
90
+ y = h - tile_h
91
+
92
+ for col in range(cols):
93
+ x = int(col * dx)
94
+
95
+ if x + tile_w >= w:
96
+ x = w - tile_w
97
+
98
+ tile = image.crop((x, y, x + tile_w, y + tile_h))
99
+
100
+ row_images.append([x, tile_w, tile])
101
+
102
+ grid.tiles.append([y, tile_h, row_images])
103
+
104
+ return grid
105
+
106
+
107
+ def combine_grid(grid):
108
+ def make_mask_image(r):
109
+ r = r * 255 / grid.overlap
110
+ r = r.astype(np.uint8)
111
+ return Image.fromarray(r, 'L')
112
+
113
+ mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
114
+ mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
115
+
116
+ combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
117
+ for y, h, row in grid.tiles:
118
+ combined_row = Image.new("RGB", (grid.image_w, h))
119
+ for x, w, tile in row:
120
+ if x == 0:
121
+ combined_row.paste(tile, (0, 0))
122
+ continue
123
+
124
+ combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
125
+ combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
126
+
127
+ if y == 0:
128
+ combined_image.paste(combined_row, (0, 0))
129
+ continue
130
+
131
+ combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
132
+ combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
133
+
134
+ return combined_image
135
+
136
+
137
+ class GridAnnotation:
138
+ def __init__(self, text='', is_active=True):
139
+ self.text = text
140
+ self.is_active = is_active
141
+ self.size = None
142
+
143
+
144
+ def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
145
+ def wrap(drawing, text, font, line_length):
146
+ lines = ['']
147
+ for word in text.split():
148
+ line = f'{lines[-1]} {word}'.strip()
149
+ if drawing.textlength(line, font=font) <= line_length:
150
+ lines[-1] = line
151
+ else:
152
+ lines.append(word)
153
+ return lines
154
+
155
+ def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
156
+ for line in 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
+ 'denoising': lambda self: self.p.denoising_strength if self.p and self.p.denoising_strength else NOTHING_AND_SKIP_PREVIOUS_TEXT,
365
+ }
366
+ default_time_format = '%Y%m%d%H%M%S'
367
+
368
+ def __init__(self, p, seed, prompt, image):
369
+ self.p = p
370
+ self.seed = seed
371
+ self.prompt = prompt
372
+ self.image = image
373
+
374
+ def hasprompt(self, *args):
375
+ lower = self.prompt.lower()
376
+ if self.p is None or self.prompt is None:
377
+ return None
378
+ outres = ""
379
+ for arg in args:
380
+ if arg != "":
381
+ division = arg.split("|")
382
+ expected = division[0].lower()
383
+ default = division[1] if len(division) > 1 else ""
384
+ if lower.find(expected) >= 0:
385
+ outres = f'{outres}{expected}'
386
+ else:
387
+ outres = outres if default == "" else f'{outres}{default}'
388
+ return sanitize_filename_part(outres)
389
+
390
+ def prompt_no_style(self):
391
+ if self.p is None or self.prompt is None:
392
+ return None
393
+
394
+ prompt_no_style = self.prompt
395
+ for style in shared.prompt_styles.get_style_prompts(self.p.styles):
396
+ if len(style) > 0:
397
+ for part in style.split("{prompt}"):
398
+ prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
399
+
400
+ prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
401
+
402
+ return sanitize_filename_part(prompt_no_style, replace_spaces=False)
403
+
404
+ def prompt_words(self):
405
+ words = [x for x in re_nonletters.split(self.prompt or "") if len(x) > 0]
406
+ if len(words) == 0:
407
+ words = ["empty"]
408
+ return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
409
+
410
+ def datetime(self, *args):
411
+ time_datetime = datetime.datetime.now()
412
+
413
+ time_format = args[0] if len(args) > 0 and args[0] != "" else self.default_time_format
414
+ try:
415
+ time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
416
+ except pytz.exceptions.UnknownTimeZoneError:
417
+ time_zone = None
418
+
419
+ time_zone_time = time_datetime.astimezone(time_zone)
420
+ try:
421
+ formatted_time = time_zone_time.strftime(time_format)
422
+ except (ValueError, TypeError):
423
+ formatted_time = time_zone_time.strftime(self.default_time_format)
424
+
425
+ return sanitize_filename_part(formatted_time, replace_spaces=False)
426
+
427
+ def apply(self, x):
428
+ res = ''
429
+
430
+ for m in re_pattern.finditer(x):
431
+ text, pattern = m.groups()
432
+
433
+ if pattern is None:
434
+ res += text
435
+ continue
436
+
437
+ pattern_args = []
438
+ while True:
439
+ m = re_pattern_arg.match(pattern)
440
+ if m is None:
441
+ break
442
+
443
+ pattern, arg = m.groups()
444
+ pattern_args.insert(0, arg)
445
+
446
+ fun = self.replacements.get(pattern.lower())
447
+ if fun is not None:
448
+ try:
449
+ replacement = fun(self, *pattern_args)
450
+ except Exception:
451
+ replacement = None
452
+ print(f"Error adding [{pattern}] to filename", file=sys.stderr)
453
+ print(traceback.format_exc(), file=sys.stderr)
454
+
455
+ if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
456
+ continue
457
+ elif replacement is not None:
458
+ res += text + str(replacement)
459
+ continue
460
+
461
+ res += f'{text}[{pattern}]'
462
+
463
+ return res
464
+
465
+
466
+ def get_next_sequence_number(path, basename):
467
+ """
468
+ Determines and returns the next sequence number to use when saving an image in the specified directory.
469
+
470
+ The sequence starts at 0.
471
+ """
472
+ result = -1
473
+ if basename != '':
474
+ basename = f"{basename}-"
475
+
476
+ prefix_length = len(basename)
477
+ for p in os.listdir(path):
478
+ if p.startswith(basename):
479
+ parts = 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)
480
+ try:
481
+ result = max(int(parts[0]), result)
482
+ except ValueError:
483
+ pass
484
+
485
+ return result + 1
486
+
487
+
488
+ def save_image_with_geninfo(image, geninfo, filename, extension=None, existing_pnginfo=None):
489
+ if extension is None:
490
+ extension = os.path.splitext(filename)[1]
491
+
492
+ image_format = Image.registered_extensions()[extension]
493
+
494
+ if extension.lower() == '.png':
495
+ if opts.enable_pnginfo:
496
+ pnginfo_data = PngImagePlugin.PngInfo()
497
+ for k, v in (existing_pnginfo or {}).items():
498
+ pnginfo_data.add_text(k, str(v))
499
+ else:
500
+ pnginfo_data = None
501
+
502
+ image.save(filename, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
503
+
504
+ elif extension.lower() in (".jpg", ".jpeg", ".webp"):
505
+ if image.mode == 'RGBA':
506
+ image = image.convert("RGB")
507
+ elif image.mode == 'I;16':
508
+ image = image.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
509
+
510
+ image.save(filename, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
511
+
512
+ if opts.enable_pnginfo and geninfo is not None:
513
+ exif_bytes = piexif.dump({
514
+ "Exif": {
515
+ piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
516
+ },
517
+ })
518
+
519
+ piexif.insert(exif_bytes, filename)
520
+ else:
521
+ image.save(filename, format=image_format, quality=opts.jpeg_quality)
522
+ #功能函数,上传图片
523
+ def uploadhg(fullfn_without_extension, extension):
524
+ fullfn_without_extension = fullfn_without_extension
525
+ extension = extension
526
+ hgfilename = f"{fullfn_without_extension}{extension}"
527
+
528
+ hgpath, tempfilename = os.path.split(hgfilename)
529
+ hgname, hghzm = os.path.splitext(tempfilename)
530
+
531
+ print(f'hgpath:{hgpath}')
532
+
533
+ print(f'hgname:{hgname}')
534
+
535
+ print(f'hghzm:{hghzm}')
536
+
537
+ hgnames =f'{hgname}{extension}'
538
+ huggingface_use = True
539
+ huggingface_token_file = '/kaggle/working/hugfacetoken.txt'
540
+ huggiingface_repo_id = 'xiemoxiaoshaso/image'
541
+ # 将会同步的文件
542
+ yun_files = [
543
+ f'{hgnames}',
544
+ ]
545
+ if huggingface_use == True:
546
+ hugface_upload(huggingface_token_file,yun_files,huggiingface_repo_id,hgpath)
547
+
548
+ #功能函数,上传图片
549
+ def hugface_upload(huggingface_token_file, yun_files, repo_id, hgpath):
550
+ if Path(huggingface_token_file).exists():
551
+ with open(huggingface_token_file, encoding="utf-8") as nkfile:
552
+ hugToken = nkfile.readline()
553
+ if hugToken != '':
554
+ # 使用您的 Hugging Face 访问令牌登录
555
+ login(token=hugToken)
556
+ # 实例化 HfApi 类
557
+ api = HfApi()
558
+ print("HfApi 类已实例化")
559
+ dqml = "/kaggle/working/stable-diffusion-webui/"
560
+ #hgpaths = f'{dqml}{hgpath}'
561
+ os.chdir(f'{hgpath}')
562
+ # 使用 upload_file() 函数上传文件
563
+ print("开始上传文件...")
564
+ for yun_file in yun_files:
565
+ if Path(yun_file).exists():
566
+ response = api.upload_file(
567
+ path_or_fileobj=yun_file,
568
+ path_in_repo=yun_file,
569
+ repo_id=repo_id,
570
+ repo_type="dataset"
571
+ )
572
+ print("文件上传完成")
573
+ os.chdir(f'{dqml}')
574
+ print(f"响应: {response}")
575
+ else:
576
+ print(f'Error: File {yun_file} does not exist')
577
+ return
578
+ os.chdir(f'{dqml}')
579
+ else:
580
+ print(f'Error: File {huggingface_token_file} does not exist')
581
+ os.chdir(f'{dqml}')
582
+
583
+
584
+ 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):
585
+ """Save an image.
586
+
587
+ Args:
588
+ image (`PIL.Image`):
589
+ The image to be saved.
590
+ path (`str`):
591
+ The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
592
+ basename (`str`):
593
+ The base filename which will be applied to `filename pattern`.
594
+ seed, prompt, short_filename,
595
+ extension (`str`):
596
+ Image file extension, default is `png`.
597
+ pngsectionname (`str`):
598
+ Specify the name of the section which `info` will be saved in.
599
+ info (`str` or `PngImagePlugin.iTXt`):
600
+ PNG info chunks.
601
+ existing_info (`dict`):
602
+ Additional PNG info. `existing_info == {pngsectionname: info, ...}`
603
+ no_prompt:
604
+ TODO I don't know its meaning.
605
+ p (`StableDiffusionProcessing`)
606
+ forced_filename (`str`):
607
+ If specified, `basename` and filename pattern will be ignored.
608
+ save_to_dirs (bool):
609
+ If true, the image will be saved into a subdirectory of `path`.
610
+
611
+ Returns: (fullfn, txt_fullfn)
612
+ fullfn (`str`):
613
+ The full path of the saved imaged.
614
+ txt_fullfn (`str` or None):
615
+ If a text file is saved for this image, this will be its full path. Otherwise None.
616
+ """
617
+ namegen = FilenameGenerator(p, seed, prompt, image)
618
+
619
+ if save_to_dirs is None:
620
+ save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
621
+
622
+ if save_to_dirs:
623
+ dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
624
+ path = os.path.join(path, dirname)
625
+
626
+ os.makedirs(path, exist_ok=True)
627
+
628
+ if forced_filename is None:
629
+ if short_filename or seed is None:
630
+ file_decoration = ""
631
+ elif opts.save_to_dirs:
632
+ file_decoration = opts.samples_filename_pattern or "[seed]"
633
+ else:
634
+ file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
635
+
636
+ add_number = opts.save_images_add_number or file_decoration == ''
637
+
638
+ if file_decoration != "" and add_number:
639
+ file_decoration = f"-{file_decoration}"
640
+
641
+ file_decoration = namegen.apply(file_decoration) + suffix
642
+
643
+ if add_number:
644
+ basecount = get_next_sequence_number(path, basename)
645
+ fullfn = None
646
+ for i in range(500):
647
+ fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
648
+ fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
649
+ if not os.path.exists(fullfn):
650
+ break
651
+ else:
652
+ fullfn = os.path.join(path, f"{file_decoration}.{extension}")
653
+ else:
654
+ fullfn = os.path.join(path, f"{forced_filename}.{extension}")
655
+
656
+ pnginfo = existing_info or {}
657
+ if info is not None:
658
+ pnginfo[pnginfo_section_name] = info
659
+
660
+ params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
661
+ script_callbacks.before_image_saved_callback(params)
662
+
663
+ image = params.image
664
+ fullfn = params.filename
665
+ info = params.pnginfo.get(pnginfo_section_name, None)
666
+
667
+ def _atomically_save_image(image_to_save, filename_without_extension, extension):
668
+ """
669
+ save image with .tmp extension to avoid race condition when another process detects new image in the directory
670
+ """
671
+ temp_file_path = f"{filename_without_extension}.tmp"
672
+
673
+ #huggingface_file_path = f"{filename_without_extension}.png"
674
+ save_image_with_geninfo(image_to_save, info, temp_file_path, extension, params.pnginfo)
675
+
676
+ os.replace(temp_file_path, filename_without_extension + extension)
677
+
678
+ fullfn_without_extension, extension = os.path.splitext(params.filename)
679
+ if hasattr(os, 'statvfs'):
680
+ max_name_len = os.statvfs(path).f_namemax
681
+ fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
682
+ params.filename = fullfn_without_extension + extension
683
+ fullfn = params.filename
684
+ dqml = "/kaggle/working/stable-diffusion-webui/"
685
+ os.chdir(f'{dqml}')
686
+
687
+ _atomically_save_image(image, fullfn_without_extension, extension)
688
+
689
+ uploadhg(fullfn_without_extension, extension)
690
+
691
+ image.already_saved_as = fullfn
692
+
693
+ oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
694
+ if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
695
+ ratio = image.width / image.height
696
+
697
+ if oversize and ratio > 1:
698
+ image = image.resize((round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)), LANCZOS)
699
+ elif oversize:
700
+ image = image.resize((round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)), LANCZOS)
701
+
702
+ try:
703
+ _atomically_save_image(image, fullfn_without_extension, ".jpg")
704
+ except Exception as e:
705
+ errors.display(e, "saving image as downscaled JPG")
706
+
707
+ if opts.save_txt and info is not None:
708
+ txt_fullfn = f"{fullfn_without_extension}.txt"
709
+ with open(txt_fullfn, "w", encoding="utf8") as file:
710
+ file.write(f"{info}\n")
711
+ else:
712
+ txt_fullfn = None
713
+
714
+ script_callbacks.image_saved_callback(params)
715
+
716
+ return fullfn, txt_fullfn
717
+
718
+
719
+ def read_info_from_image(image):
720
+ items = image.info or {}
721
+
722
+ geninfo = items.pop('parameters', None)
723
+
724
+ if "exif" in items:
725
+ exif = piexif.load(items["exif"])
726
+ exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
727
+ try:
728
+ exif_comment = piexif.helper.UserComment.load(exif_comment)
729
+ except ValueError:
730
+ exif_comment = exif_comment.decode('utf8', errors="ignore")
731
+
732
+ if exif_comment:
733
+ items['exif comment'] = exif_comment
734
+ geninfo = exif_comment
735
+
736
+ for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
737
+ 'loop', 'background', 'timestamp', 'duration']:
738
+ items.pop(field, None)
739
+
740
+ if items.get("Software", None) == "NovelAI":
741
+ try:
742
+ json_info = json.loads(items["Comment"])
743
+ sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
744
+
745
+ geninfo = f"""{items["Description"]}
746
+ Negative prompt: {json_info["uc"]}
747
+ 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"""
748
+ except Exception:
749
+ print("Error parsing NovelAI image generation parameters:", file=sys.stderr)
750
+ print(traceback.format_exc(), file=sys.stderr)
751
+
752
+ return geninfo, items
753
+
754
+
755
+ def image_data(data):
756
+ import gradio as gr
757
+
758
+ try:
759
+ image = Image.open(io.BytesIO(data))
760
+ textinfo, _ = read_info_from_image(image)
761
+ return textinfo, None
762
+ except Exception:
763
+ pass
764
+
765
+ try:
766
+ text = data.decode('utf8')
767
+ assert len(text) < 10000
768
+ return text, None
769
+
770
+ except Exception:
771
+ pass
772
+
773
+ return gr.update(), None
774
+
775
+
776
+ def flatten(img, bgcolor):
777
+ """replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency"""
778
+
779
+ if img.mode == "RGBA":
780
+ background = Image.new('RGBA', img.size, bgcolor)
781
+ background.paste(img, mask=img)
782
+ img = background
783
+
784
+ return img.convert('RGB')