images.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. import datetime
  2. import pytz
  3. import io
  4. import math
  5. import os
  6. from collections import namedtuple
  7. import re
  8. import numpy as np
  9. import piexif
  10. import piexif.helper
  11. from PIL import Image, ImageFont, ImageDraw, PngImagePlugin
  12. import string
  13. import json
  14. import hashlib
  15. from modules import sd_samplers, shared, script_callbacks, errors
  16. from modules.paths_internal import roboto_ttf_file
  17. from modules.shared import opts
  18. import modules.sd_vae as sd_vae
  19. LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
  20. def get_font(fontsize: int):
  21. try:
  22. return ImageFont.truetype(opts.font or roboto_ttf_file, fontsize)
  23. except Exception:
  24. return ImageFont.truetype(roboto_ttf_file, fontsize)
  25. def image_grid(imgs, batch_size=1, rows=None):
  26. if rows is None:
  27. if opts.n_rows > 0:
  28. rows = opts.n_rows
  29. elif opts.n_rows == 0:
  30. rows = batch_size
  31. elif opts.grid_prevent_empty_spots:
  32. rows = math.floor(math.sqrt(len(imgs)))
  33. while len(imgs) % rows != 0:
  34. rows -= 1
  35. else:
  36. rows = math.sqrt(len(imgs))
  37. rows = round(rows)
  38. if rows > len(imgs):
  39. rows = len(imgs)
  40. cols = math.ceil(len(imgs) / rows)
  41. params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
  42. script_callbacks.image_grid_callback(params)
  43. w, h = imgs[0].size
  44. grid = Image.new('RGB', size=(params.cols * w, params.rows * h), color='black')
  45. for i, img in enumerate(params.imgs):
  46. grid.paste(img, box=(i % params.cols * w, i // params.cols * h))
  47. return grid
  48. Grid = namedtuple("Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])
  49. def split_grid(image, tile_w=512, tile_h=512, overlap=64):
  50. w = image.width
  51. h = image.height
  52. non_overlap_width = tile_w - overlap
  53. non_overlap_height = tile_h - overlap
  54. cols = math.ceil((w - overlap) / non_overlap_width)
  55. rows = math.ceil((h - overlap) / non_overlap_height)
  56. dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
  57. dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
  58. grid = Grid([], tile_w, tile_h, w, h, overlap)
  59. for row in range(rows):
  60. row_images = []
  61. y = int(row * dy)
  62. if y + tile_h >= h:
  63. y = h - tile_h
  64. for col in range(cols):
  65. x = int(col * dx)
  66. if x + tile_w >= w:
  67. x = w - tile_w
  68. tile = image.crop((x, y, x + tile_w, y + tile_h))
  69. row_images.append([x, tile_w, tile])
  70. grid.tiles.append([y, tile_h, row_images])
  71. return grid
  72. def combine_grid(grid):
  73. def make_mask_image(r):
  74. r = r * 255 / grid.overlap
  75. r = r.astype(np.uint8)
  76. return Image.fromarray(r, 'L')
  77. mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
  78. mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
  79. combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
  80. for y, h, row in grid.tiles:
  81. combined_row = Image.new("RGB", (grid.image_w, h))
  82. for x, w, tile in row:
  83. if x == 0:
  84. combined_row.paste(tile, (0, 0))
  85. continue
  86. combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
  87. combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
  88. if y == 0:
  89. combined_image.paste(combined_row, (0, 0))
  90. continue
  91. combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
  92. combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
  93. return combined_image
  94. class GridAnnotation:
  95. def __init__(self, text='', is_active=True):
  96. self.text = text
  97. self.is_active = is_active
  98. self.size = None
  99. def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
  100. def wrap(drawing, text, font, line_length):
  101. lines = ['']
  102. for word in text.split():
  103. line = f'{lines[-1]} {word}'.strip()
  104. if drawing.textlength(line, font=font) <= line_length:
  105. lines[-1] = line
  106. else:
  107. lines.append(word)
  108. return lines
  109. def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
  110. for line in lines:
  111. fnt = initial_fnt
  112. fontsize = initial_fontsize
  113. while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0:
  114. fontsize -= 1
  115. fnt = get_font(fontsize)
  116. 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")
  117. if not line.is_active:
  118. 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)
  119. draw_y += line.size[1] + line_spacing
  120. fontsize = (width + height) // 25
  121. line_spacing = fontsize // 2
  122. fnt = get_font(fontsize)
  123. color_active = (0, 0, 0)
  124. color_inactive = (153, 153, 153)
  125. pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
  126. cols = im.width // width
  127. rows = im.height // height
  128. assert cols == len(hor_texts), f'bad number of horizontal texts: {len(hor_texts)}; must be {cols}'
  129. assert rows == len(ver_texts), f'bad number of vertical texts: {len(ver_texts)}; must be {rows}'
  130. calc_img = Image.new("RGB", (1, 1), "white")
  131. calc_d = ImageDraw.Draw(calc_img)
  132. for texts, allowed_width in zip(hor_texts + ver_texts, [width] * len(hor_texts) + [pad_left] * len(ver_texts)):
  133. items = [] + texts
  134. texts.clear()
  135. for line in items:
  136. wrapped = wrap(calc_d, line.text, fnt, allowed_width)
  137. texts += [GridAnnotation(x, line.is_active) for x in wrapped]
  138. for line in texts:
  139. bbox = calc_d.multiline_textbbox((0, 0), line.text, font=fnt)
  140. line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
  141. line.allowed_width = allowed_width
  142. hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
  143. ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
  144. pad_top = 0 if sum(hor_text_heights) == 0 else max(hor_text_heights) + line_spacing * 2
  145. result = Image.new("RGB", (im.width + pad_left + margin * (cols-1), im.height + pad_top + margin * (rows-1)), "white")
  146. for row in range(rows):
  147. for col in range(cols):
  148. cell = im.crop((width * col, height * row, width * (col+1), height * (row+1)))
  149. result.paste(cell, (pad_left + (width + margin) * col, pad_top + (height + margin) * row))
  150. d = ImageDraw.Draw(result)
  151. for col in range(cols):
  152. x = pad_left + (width + margin) * col + width / 2
  153. y = pad_top / 2 - hor_text_heights[col] / 2
  154. draw_texts(d, x, y, hor_texts[col], fnt, fontsize)
  155. for row in range(rows):
  156. x = pad_left / 2
  157. y = pad_top + (height + margin) * row + height / 2 - ver_text_heights[row] / 2
  158. draw_texts(d, x, y, ver_texts[row], fnt, fontsize)
  159. return result
  160. def draw_prompt_matrix(im, width, height, all_prompts, margin=0):
  161. prompts = all_prompts[1:]
  162. boundary = math.ceil(len(prompts) / 2)
  163. prompts_horiz = prompts[:boundary]
  164. prompts_vert = prompts[boundary:]
  165. 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))]
  166. 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))]
  167. return draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin)
  168. def resize_image(resize_mode, im, width, height, upscaler_name=None):
  169. """
  170. Resizes an image with the specified resize_mode, width, and height.
  171. Args:
  172. resize_mode: The mode to use when resizing the image.
  173. 0: Resize the image to the specified width and height.
  174. 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.
  175. 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.
  176. im: The image to resize.
  177. width: The width to resize the image to.
  178. height: The height to resize the image to.
  179. upscaler_name: The name of the upscaler to use. If not provided, defaults to opts.upscaler_for_img2img.
  180. """
  181. upscaler_name = upscaler_name or opts.upscaler_for_img2img
  182. def resize(im, w, h):
  183. if upscaler_name is None or upscaler_name == "None" or im.mode == 'L':
  184. return im.resize((w, h), resample=LANCZOS)
  185. scale = max(w / im.width, h / im.height)
  186. if scale > 1.0:
  187. upscalers = [x for x in shared.sd_upscalers if x.name == upscaler_name]
  188. if len(upscalers) == 0:
  189. upscaler = shared.sd_upscalers[0]
  190. print(f"could not find upscaler named {upscaler_name or '<empty string>'}, using {upscaler.name} as a fallback")
  191. else:
  192. upscaler = upscalers[0]
  193. im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
  194. if im.width != w or im.height != h:
  195. im = im.resize((w, h), resample=LANCZOS)
  196. return im
  197. if resize_mode == 0:
  198. res = resize(im, width, height)
  199. elif resize_mode == 1:
  200. ratio = width / height
  201. src_ratio = im.width / im.height
  202. src_w = width if ratio > src_ratio else im.width * height // im.height
  203. src_h = height if ratio <= src_ratio else im.height * width // im.width
  204. resized = resize(im, src_w, src_h)
  205. res = Image.new("RGB", (width, height))
  206. res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
  207. else:
  208. ratio = width / height
  209. src_ratio = im.width / im.height
  210. src_w = width if ratio < src_ratio else im.width * height // im.height
  211. src_h = height if ratio >= src_ratio else im.height * width // im.width
  212. resized = resize(im, src_w, src_h)
  213. res = Image.new("RGB", (width, height))
  214. res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
  215. if ratio < src_ratio:
  216. fill_height = height // 2 - src_h // 2
  217. res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
  218. res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h))
  219. elif ratio > src_ratio:
  220. fill_width = width // 2 - src_w // 2
  221. res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
  222. res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0))
  223. return res
  224. invalid_filename_chars = '<>:"/\\|?*\n'
  225. invalid_filename_prefix = ' '
  226. invalid_filename_postfix = ' .'
  227. re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
  228. re_pattern = re.compile(r"(.*?)(?:\[([^\[\]]+)\]|$)")
  229. re_pattern_arg = re.compile(r"(.*)<([^>]*)>$")
  230. max_filename_part_length = 128
  231. NOTHING_AND_SKIP_PREVIOUS_TEXT = object()
  232. def sanitize_filename_part(text, replace_spaces=True):
  233. if text is None:
  234. return None
  235. if replace_spaces:
  236. text = text.replace(' ', '_')
  237. text = text.translate({ord(x): '_' for x in invalid_filename_chars})
  238. text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
  239. text = text.rstrip(invalid_filename_postfix)
  240. return text
  241. class FilenameGenerator:
  242. def get_vae_filename(self): #get the name of the VAE file.
  243. if sd_vae.loaded_vae_file is None:
  244. return "NoneType"
  245. file_name = os.path.basename(sd_vae.loaded_vae_file)
  246. split_file_name = file_name.split('.')
  247. if len(split_file_name) > 1 and split_file_name[0] == '':
  248. return split_file_name[1] # if the first character of the filename is "." then [1] is obtained.
  249. else:
  250. return split_file_name[0]
  251. replacements = {
  252. 'seed': lambda self: self.seed if self.seed is not None else '',
  253. 'seed_first': lambda self: self.seed if self.p.batch_size == 1 else self.p.all_seeds[0],
  254. 'seed_last': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 else self.p.all_seeds[-1],
  255. 'steps': lambda self: self.p and self.p.steps,
  256. 'cfg': lambda self: self.p and self.p.cfg_scale,
  257. 'width': lambda self: self.image.width,
  258. 'height': lambda self: self.image.height,
  259. '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),
  260. 'sampler': lambda self: self.p and sanitize_filename_part(self.p.sampler_name, replace_spaces=False),
  261. 'model_hash': lambda self: getattr(self.p, "sd_model_hash", shared.sd_model.sd_model_hash),
  262. 'model_name': lambda self: sanitize_filename_part(shared.sd_model.sd_checkpoint_info.model_name, replace_spaces=False),
  263. 'date': lambda self: datetime.datetime.now().strftime('%Y-%m-%d'),
  264. 'datetime': lambda self, *args: self.datetime(*args), # accepts formats: [datetime], [datetime<Format>], [datetime<Format><Time Zone>]
  265. 'job_timestamp': lambda self: getattr(self.p, "job_timestamp", shared.state.job_timestamp),
  266. 'prompt_hash': lambda self: hashlib.sha256(self.prompt.encode()).hexdigest()[0:8],
  267. 'prompt': lambda self: sanitize_filename_part(self.prompt),
  268. 'prompt_no_styles': lambda self: self.prompt_no_style(),
  269. 'prompt_spaces': lambda self: sanitize_filename_part(self.prompt, replace_spaces=False),
  270. 'prompt_words': lambda self: self.prompt_words(),
  271. 'batch_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 or self.zip else self.p.batch_index + 1,
  272. 'batch_size': lambda self: self.p.batch_size,
  273. 'generation_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if (self.p.n_iter == 1 and self.p.batch_size == 1) or self.zip else self.p.iteration * self.p.batch_size + self.p.batch_index + 1,
  274. 'hasprompt': lambda self, *args: self.hasprompt(*args), # accepts formats:[hasprompt<prompt1|default><prompt2>..]
  275. 'clip_skip': lambda self: opts.data["CLIP_stop_at_last_layers"],
  276. 'denoising': lambda self: self.p.denoising_strength if self.p and self.p.denoising_strength else NOTHING_AND_SKIP_PREVIOUS_TEXT,
  277. 'vae_filename': lambda self: self.get_vae_filename(),
  278. }
  279. default_time_format = '%Y%m%d%H%M%S'
  280. def __init__(self, p, seed, prompt, image, zip=False):
  281. self.p = p
  282. self.seed = seed
  283. self.prompt = prompt
  284. self.image = image
  285. self.zip = zip
  286. def hasprompt(self, *args):
  287. lower = self.prompt.lower()
  288. if self.p is None or self.prompt is None:
  289. return None
  290. outres = ""
  291. for arg in args:
  292. if arg != "":
  293. division = arg.split("|")
  294. expected = division[0].lower()
  295. default = division[1] if len(division) > 1 else ""
  296. if lower.find(expected) >= 0:
  297. outres = f'{outres}{expected}'
  298. else:
  299. outres = outres if default == "" else f'{outres}{default}'
  300. return sanitize_filename_part(outres)
  301. def prompt_no_style(self):
  302. if self.p is None or self.prompt is None:
  303. return None
  304. prompt_no_style = self.prompt
  305. for style in shared.prompt_styles.get_style_prompts(self.p.styles):
  306. if style:
  307. for part in style.split("{prompt}"):
  308. prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
  309. prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
  310. return sanitize_filename_part(prompt_no_style, replace_spaces=False)
  311. def prompt_words(self):
  312. words = [x for x in re_nonletters.split(self.prompt or "") if x]
  313. if len(words) == 0:
  314. words = ["empty"]
  315. return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
  316. def datetime(self, *args):
  317. time_datetime = datetime.datetime.now()
  318. time_format = args[0] if (args and args[0] != "") else self.default_time_format
  319. try:
  320. time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
  321. except pytz.exceptions.UnknownTimeZoneError:
  322. time_zone = None
  323. time_zone_time = time_datetime.astimezone(time_zone)
  324. try:
  325. formatted_time = time_zone_time.strftime(time_format)
  326. except (ValueError, TypeError):
  327. formatted_time = time_zone_time.strftime(self.default_time_format)
  328. return sanitize_filename_part(formatted_time, replace_spaces=False)
  329. def apply(self, x):
  330. res = ''
  331. for m in re_pattern.finditer(x):
  332. text, pattern = m.groups()
  333. if pattern is None:
  334. res += text
  335. continue
  336. pattern_args = []
  337. while True:
  338. m = re_pattern_arg.match(pattern)
  339. if m is None:
  340. break
  341. pattern, arg = m.groups()
  342. pattern_args.insert(0, arg)
  343. fun = self.replacements.get(pattern.lower())
  344. if fun is not None:
  345. try:
  346. replacement = fun(self, *pattern_args)
  347. except Exception:
  348. replacement = None
  349. errors.report(f"Error adding [{pattern}] to filename", exc_info=True)
  350. if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
  351. continue
  352. elif replacement is not None:
  353. res += text + str(replacement)
  354. continue
  355. res += f'{text}[{pattern}]'
  356. return res
  357. def get_next_sequence_number(path, basename):
  358. """
  359. Determines and returns the next sequence number to use when saving an image in the specified directory.
  360. The sequence starts at 0.
  361. """
  362. result = -1
  363. if basename != '':
  364. basename = f"{basename}-"
  365. prefix_length = len(basename)
  366. for p in os.listdir(path):
  367. if p.startswith(basename):
  368. 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)
  369. try:
  370. result = max(int(parts[0]), result)
  371. except ValueError:
  372. pass
  373. return result + 1
  374. def save_image_with_geninfo(image, geninfo, filename, extension=None, existing_pnginfo=None):
  375. if extension is None:
  376. extension = os.path.splitext(filename)[1]
  377. image_format = Image.registered_extensions()[extension]
  378. if extension.lower() == '.png':
  379. if opts.enable_pnginfo:
  380. pnginfo_data = PngImagePlugin.PngInfo()
  381. for k, v in (existing_pnginfo or {}).items():
  382. pnginfo_data.add_text(k, str(v))
  383. else:
  384. pnginfo_data = None
  385. image.save(filename, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
  386. elif extension.lower() in (".jpg", ".jpeg", ".webp"):
  387. if image.mode == 'RGBA':
  388. image = image.convert("RGB")
  389. elif image.mode == 'I;16':
  390. image = image.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
  391. image.save(filename, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
  392. if opts.enable_pnginfo and geninfo is not None:
  393. exif_bytes = piexif.dump({
  394. "Exif": {
  395. piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
  396. },
  397. })
  398. piexif.insert(exif_bytes, filename)
  399. else:
  400. image.save(filename, format=image_format, quality=opts.jpeg_quality)
  401. 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):
  402. """Save an image.
  403. Args:
  404. image (`PIL.Image`):
  405. The image to be saved.
  406. path (`str`):
  407. The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
  408. basename (`str`):
  409. The base filename which will be applied to `filename pattern`.
  410. seed, prompt, short_filename,
  411. extension (`str`):
  412. Image file extension, default is `png`.
  413. pngsectionname (`str`):
  414. Specify the name of the section which `info` will be saved in.
  415. info (`str` or `PngImagePlugin.iTXt`):
  416. PNG info chunks.
  417. existing_info (`dict`):
  418. Additional PNG info. `existing_info == {pngsectionname: info, ...}`
  419. no_prompt:
  420. TODO I don't know its meaning.
  421. p (`StableDiffusionProcessing`)
  422. forced_filename (`str`):
  423. If specified, `basename` and filename pattern will be ignored.
  424. save_to_dirs (bool):
  425. If true, the image will be saved into a subdirectory of `path`.
  426. Returns: (fullfn, txt_fullfn)
  427. fullfn (`str`):
  428. The full path of the saved imaged.
  429. txt_fullfn (`str` or None):
  430. If a text file is saved for this image, this will be its full path. Otherwise None.
  431. """
  432. namegen = FilenameGenerator(p, seed, prompt, image)
  433. if save_to_dirs is None:
  434. save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
  435. if save_to_dirs:
  436. dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
  437. path = os.path.join(path, dirname)
  438. os.makedirs(path, exist_ok=True)
  439. if forced_filename is None:
  440. if short_filename or seed is None:
  441. file_decoration = ""
  442. elif opts.save_to_dirs:
  443. file_decoration = opts.samples_filename_pattern or "[seed]"
  444. else:
  445. file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
  446. add_number = opts.save_images_add_number or file_decoration == ''
  447. if file_decoration != "" and add_number:
  448. file_decoration = f"-{file_decoration}"
  449. file_decoration = namegen.apply(file_decoration) + suffix
  450. if add_number:
  451. basecount = get_next_sequence_number(path, basename)
  452. fullfn = None
  453. for i in range(500):
  454. fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
  455. fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
  456. if not os.path.exists(fullfn):
  457. break
  458. else:
  459. fullfn = os.path.join(path, f"{file_decoration}.{extension}")
  460. else:
  461. fullfn = os.path.join(path, f"{forced_filename}.{extension}")
  462. pnginfo = existing_info or {}
  463. if info is not None:
  464. pnginfo[pnginfo_section_name] = info
  465. params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
  466. script_callbacks.before_image_saved_callback(params)
  467. image = params.image
  468. fullfn = params.filename
  469. info = params.pnginfo.get(pnginfo_section_name, None)
  470. def _atomically_save_image(image_to_save, filename_without_extension, extension):
  471. """
  472. save image with .tmp extension to avoid race condition when another process detects new image in the directory
  473. """
  474. temp_file_path = f"{filename_without_extension}.tmp"
  475. save_image_with_geninfo(image_to_save, info, temp_file_path, extension, params.pnginfo)
  476. os.replace(temp_file_path, filename_without_extension + extension)
  477. fullfn_without_extension, extension = os.path.splitext(params.filename)
  478. if hasattr(os, 'statvfs'):
  479. max_name_len = os.statvfs(path).f_namemax
  480. fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
  481. params.filename = fullfn_without_extension + extension
  482. fullfn = params.filename
  483. _atomically_save_image(image, fullfn_without_extension, extension)
  484. image.already_saved_as = fullfn
  485. oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
  486. if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
  487. ratio = image.width / image.height
  488. if oversize and ratio > 1:
  489. image = image.resize((round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)), LANCZOS)
  490. elif oversize:
  491. image = image.resize((round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)), LANCZOS)
  492. try:
  493. _atomically_save_image(image, fullfn_without_extension, ".jpg")
  494. except Exception as e:
  495. errors.display(e, "saving image as downscaled JPG")
  496. if opts.save_txt and info is not None:
  497. txt_fullfn = f"{fullfn_without_extension}.txt"
  498. with open(txt_fullfn, "w", encoding="utf8") as file:
  499. file.write(f"{info}\n")
  500. else:
  501. txt_fullfn = None
  502. script_callbacks.image_saved_callback(params)
  503. return fullfn, txt_fullfn
  504. def read_info_from_image(image):
  505. items = image.info or {}
  506. geninfo = items.pop('parameters', None)
  507. if "exif" in items:
  508. exif = piexif.load(items["exif"])
  509. exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
  510. try:
  511. exif_comment = piexif.helper.UserComment.load(exif_comment)
  512. except ValueError:
  513. exif_comment = exif_comment.decode('utf8', errors="ignore")
  514. if exif_comment:
  515. items['exif comment'] = exif_comment
  516. geninfo = exif_comment
  517. for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
  518. 'loop', 'background', 'timestamp', 'duration', 'progressive', 'progression',
  519. 'icc_profile', 'chromaticity']:
  520. items.pop(field, None)
  521. if items.get("Software", None) == "NovelAI":
  522. try:
  523. json_info = json.loads(items["Comment"])
  524. sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
  525. geninfo = f"""{items["Description"]}
  526. Negative prompt: {json_info["uc"]}
  527. 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"""
  528. except Exception:
  529. errors.report("Error parsing NovelAI image generation parameters", exc_info=True)
  530. return geninfo, items
  531. def image_data(data):
  532. import gradio as gr
  533. try:
  534. image = Image.open(io.BytesIO(data))
  535. textinfo, _ = read_info_from_image(image)
  536. return textinfo, None
  537. except Exception:
  538. pass
  539. try:
  540. text = data.decode('utf8')
  541. assert len(text) < 10000
  542. return text, None
  543. except Exception:
  544. pass
  545. return gr.update(), None
  546. def flatten(img, bgcolor):
  547. """replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency"""
  548. if img.mode == "RGBA":
  549. background = Image.new('RGBA', img.size, bgcolor)
  550. background.paste(img, mask=img)
  551. img = background
  552. return img.convert('RGB')