stable-diffusion-webui
161 строка · 6.3 Кб
1import os2
3from PIL import Image4
5from modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, infotext_utils6from modules.shared import opts7
8
9def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):10devices.torch_gc()11
12shared.state.begin(job="extras")13
14outputs = []15
16def get_images(extras_mode, image, image_folder, input_dir):17if extras_mode == 1:18for img in image_folder:19if isinstance(img, Image.Image):20image = img21fn = ''22else:23image = Image.open(os.path.abspath(img.name))24fn = os.path.splitext(img.orig_name)[0]25yield image, fn26elif extras_mode == 2:27assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'28assert input_dir, 'input directory not selected'29
30image_list = shared.listfiles(input_dir)31for filename in image_list:32yield filename, filename33else:34assert image, 'image not selected'35yield image, None36
37if extras_mode == 2 and output_dir != '':38outpath = output_dir39else:40outpath = opts.outdir_samples or opts.outdir_extras_samples41
42infotext = ''43
44data_to_process = list(get_images(extras_mode, image, image_folder, input_dir))45shared.state.job_count = len(data_to_process)46
47for image_placeholder, name in data_to_process:48image_data: Image.Image49
50shared.state.nextjob()51shared.state.textinfo = name52shared.state.skipped = False53
54if shared.state.interrupted:55break56
57if isinstance(image_placeholder, str):58try:59image_data = Image.open(image_placeholder)60except Exception:61continue62else:63image_data = image_placeholder64
65parameters, existing_pnginfo = images.read_info_from_image(image_data)66if parameters:67existing_pnginfo["parameters"] = parameters68
69initial_pp = scripts_postprocessing.PostprocessedImage(image_data.convert("RGB"))70
71scripts.scripts_postproc.run(initial_pp, args)72
73if shared.state.skipped:74continue75
76used_suffixes = {}77for pp in [initial_pp, *initial_pp.extra_images]:78suffix = pp.get_suffix(used_suffixes)79
80if opts.use_original_name_batch and name is not None:81basename = os.path.splitext(os.path.basename(name))[0]82forced_filename = basename + suffix83else:84basename = ''85forced_filename = None86
87infotext = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in pp.info.items() if v is not None])88
89if opts.enable_pnginfo:90pp.image.info = existing_pnginfo91pp.image.info["postprocessing"] = infotext92
93shared.state.assign_current_image(pp.image)94
95if save_output:96fullfn, _ = images.save_image(pp.image, path=outpath, basename=basename, extension=opts.samples_format, info=infotext, short_filename=True, no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=existing_pnginfo, forced_filename=forced_filename, suffix=suffix)97
98if pp.caption:99caption_filename = os.path.splitext(fullfn)[0] + ".txt"100existing_caption = ""101try:102with open(caption_filename, encoding="utf8") as file:103existing_caption = file.read().strip()104except FileNotFoundError:105pass106
107action = shared.opts.postprocessing_existing_caption_action108if action == 'Prepend' and existing_caption:109caption = f"{existing_caption} {pp.caption}"110elif action == 'Append' and existing_caption:111caption = f"{pp.caption} {existing_caption}"112elif action == 'Keep' and existing_caption:113caption = existing_caption114else:115caption = pp.caption116
117caption = caption.strip()118if caption:119with open(caption_filename, "w", encoding="utf8") as file:120file.write(caption)121
122if extras_mode != 2 or show_extras_results:123outputs.append(pp.image)124
125image_data.close()126
127devices.torch_gc()128shared.state.end()129return outputs, ui_common.plaintext_to_html(infotext), ''130
131
132def run_postprocessing_webui(id_task, *args, **kwargs):133return run_postprocessing(*args, **kwargs)134
135
136def run_extras(extras_mode, resize_mode, image, image_folder, input_dir, output_dir, show_extras_results, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_first: bool, save_output: bool = True):137"""old handler for API"""138
139args = scripts.scripts_postproc.create_args_for_run({140"Upscale": {141"upscale_mode": resize_mode,142"upscale_by": upscaling_resize,143"upscale_to_width": upscaling_resize_w,144"upscale_to_height": upscaling_resize_h,145"upscale_crop": upscaling_crop,146"upscaler_1_name": extras_upscaler_1,147"upscaler_2_name": extras_upscaler_2,148"upscaler_2_visibility": extras_upscaler_2_visibility,149},150"GFPGAN": {151"enable": True,152"gfpgan_visibility": gfpgan_visibility,153},154"CodeFormer": {155"enable": True,156"codeformer_visibility": codeformer_visibility,157"codeformer_weight": codeformer_weight,158},159})160
161return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)162