Path: blob/master/modules/postprocessing.py
3055 views
import os12from PIL import Image34from modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, infotext_utils5from modules.shared import opts678def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):9devices.torch_gc()1011shared.state.begin(job="extras")1213outputs = []1415def get_images(extras_mode, image, image_folder, input_dir):16if extras_mode == 1:17for img in image_folder:18if isinstance(img, Image.Image):19image = images.fix_image(img)20fn = ''21else:22image = images.read(os.path.abspath(img.name))23fn = os.path.splitext(img.orig_name)[0]24yield image, fn25elif extras_mode == 2:26assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'27assert input_dir, 'input directory not selected'2829image_list = shared.listfiles(input_dir)30for filename in image_list:31yield filename, filename32else:33assert image, 'image not selected'34yield image, None3536if extras_mode == 2 and output_dir != '':37outpath = output_dir38else:39outpath = opts.outdir_samples or opts.outdir_extras_samples4041infotext = ''4243data_to_process = list(get_images(extras_mode, image, image_folder, input_dir))44shared.state.job_count = len(data_to_process)4546for image_placeholder, name in data_to_process:47image_data: Image.Image4849shared.state.nextjob()50shared.state.textinfo = name51shared.state.skipped = False5253if shared.state.interrupted or shared.state.stopping_generation:54break5556if isinstance(image_placeholder, str):57try:58image_data = images.read(image_placeholder)59except Exception:60continue61else:62image_data = image_placeholder6364image_data = image_data if image_data.mode in ("RGBA", "RGB") else image_data.convert("RGB")6566parameters, existing_pnginfo = images.read_info_from_image(image_data)67if parameters:68existing_pnginfo["parameters"] = parameters6970initial_pp = scripts_postprocessing.PostprocessedImage(image_data)7172scripts.scripts_postproc.run(initial_pp, args)7374if shared.state.skipped:75continue7677used_suffixes = {}78for pp in [initial_pp, *initial_pp.extra_images]:79suffix = pp.get_suffix(used_suffixes)8081if opts.use_original_name_batch and name is not None:82basename = os.path.splitext(os.path.basename(name))[0]83forced_filename = basename + suffix84else:85basename = ''86forced_filename = None8788infotext = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in pp.info.items() if v is not None])8990if opts.enable_pnginfo:91pp.image.info = existing_pnginfo92pp.image.info["postprocessing"] = infotext9394shared.state.assign_current_image(pp.image)9596if save_output:97fullfn, _ = 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)9899if pp.caption:100caption_filename = os.path.splitext(fullfn)[0] + ".txt"101existing_caption = ""102try:103with open(caption_filename, encoding="utf8") as file:104existing_caption = file.read().strip()105except FileNotFoundError:106pass107108action = shared.opts.postprocessing_existing_caption_action109if action == 'Prepend' and existing_caption:110caption = f"{existing_caption} {pp.caption}"111elif action == 'Append' and existing_caption:112caption = f"{pp.caption} {existing_caption}"113elif action == 'Keep' and existing_caption:114caption = existing_caption115else:116caption = pp.caption117118caption = caption.strip()119if caption:120with open(caption_filename, "w", encoding="utf8") as file:121file.write(caption)122123if extras_mode != 2 or show_extras_results:124outputs.append(pp.image)125126devices.torch_gc()127shared.state.end()128return outputs, ui_common.plaintext_to_html(infotext), ''129130131def run_postprocessing_webui(id_task, *args, **kwargs):132return run_postprocessing(*args, **kwargs)133134135def 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, max_side_length: int = 0):136"""old handler for API"""137138args = scripts.scripts_postproc.create_args_for_run({139"Upscale": {140"upscale_enabled": True,141"upscale_mode": resize_mode,142"upscale_by": upscaling_resize,143"max_side_length": max_side_length,144"upscale_to_width": upscaling_resize_w,145"upscale_to_height": upscaling_resize_h,146"upscale_crop": upscaling_crop,147"upscaler_1_name": extras_upscaler_1,148"upscaler_2_name": extras_upscaler_2,149"upscaler_2_visibility": extras_upscaler_2_visibility,150},151"GFPGAN": {152"enable": True,153"gfpgan_visibility": gfpgan_visibility,154},155"CodeFormer": {156"enable": True,157"codeformer_visibility": codeformer_visibility,158"codeformer_weight": codeformer_weight,159},160})161162return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)163164165