images.py 30 KB

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