Path: blob/master/modules/img2img.py
3055 views
import os1from contextlib import closing2from pathlib import Path34import numpy as np5from PIL import Image, ImageOps, ImageFilter, ImageEnhance, UnidentifiedImageError6import gradio as gr78from modules import images9from modules.infotext_utils import create_override_settings_dict, parse_generation_parameters10from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images11from modules.shared import opts, state12from modules.sd_models import get_closet_checkpoint_match13import modules.shared as shared14import modules.processing as processing15from modules.ui import plaintext_to_html16import modules.scripts171819def process_batch(p, input, output_dir, inpaint_mask_dir, args, to_scale=False, scale_by=1.0, use_png_info=False, png_info_props=None, png_info_dir=None):20output_dir = output_dir.strip()21processing.fix_seed(p)2223if isinstance(input, str):24batch_images = list(shared.walk_files(input, allowed_extensions=(".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff")))25else:26batch_images = [os.path.abspath(x.name) for x in input]2728is_inpaint_batch = False29if inpaint_mask_dir:30inpaint_masks = shared.listfiles(inpaint_mask_dir)31is_inpaint_batch = bool(inpaint_masks)3233if is_inpaint_batch:34print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")3536print(f"Will process {len(batch_images)} images, creating {p.n_iter * p.batch_size} new images for each.")3738state.job_count = len(batch_images) * p.n_iter3940# extract "default" params to use in case getting png info fails41prompt = p.prompt42negative_prompt = p.negative_prompt43seed = p.seed44cfg_scale = p.cfg_scale45sampler_name = p.sampler_name46steps = p.steps47override_settings = p.override_settings48sd_model_checkpoint_override = get_closet_checkpoint_match(override_settings.get("sd_model_checkpoint", None))49batch_results = None50discard_further_results = False51for i, image in enumerate(batch_images):52state.job = f"{i+1} out of {len(batch_images)}"53if state.skipped:54state.skipped = False5556if state.interrupted or state.stopping_generation:57break5859try:60img = images.read(image)61except UnidentifiedImageError as e:62print(e)63continue64# Use the EXIF orientation of photos taken by smartphones.65img = ImageOps.exif_transpose(img)6667if to_scale:68p.width = int(img.width * scale_by)69p.height = int(img.height * scale_by)7071p.init_images = [img] * p.batch_size7273image_path = Path(image)74if is_inpaint_batch:75# try to find corresponding mask for an image using simple filename matching76if len(inpaint_masks) == 1:77mask_image_path = inpaint_masks[0]78else:79# try to find corresponding mask for an image using simple filename matching80mask_image_dir = Path(inpaint_mask_dir)81masks_found = list(mask_image_dir.glob(f"{image_path.stem}.*"))8283if len(masks_found) == 0:84print(f"Warning: mask is not found for {image_path} in {mask_image_dir}. Skipping it.")85continue8687# it should contain only 1 matching mask88# otherwise user has many masks with the same name but different extensions89mask_image_path = masks_found[0]9091mask_image = images.read(mask_image_path)92p.image_mask = mask_image9394if use_png_info:95try:96info_img = img97if png_info_dir:98info_img_path = os.path.join(png_info_dir, os.path.basename(image))99info_img = images.read(info_img_path)100geninfo, _ = images.read_info_from_image(info_img)101parsed_parameters = parse_generation_parameters(geninfo)102parsed_parameters = {k: v for k, v in parsed_parameters.items() if k in (png_info_props or {})}103except Exception:104parsed_parameters = {}105106p.prompt = prompt + (" " + parsed_parameters["Prompt"] if "Prompt" in parsed_parameters else "")107p.negative_prompt = negative_prompt + (" " + parsed_parameters["Negative prompt"] if "Negative prompt" in parsed_parameters else "")108p.seed = int(parsed_parameters.get("Seed", seed))109p.cfg_scale = float(parsed_parameters.get("CFG scale", cfg_scale))110p.sampler_name = parsed_parameters.get("Sampler", sampler_name)111p.steps = int(parsed_parameters.get("Steps", steps))112113model_info = get_closet_checkpoint_match(parsed_parameters.get("Model hash", None))114if model_info is not None:115p.override_settings['sd_model_checkpoint'] = model_info.name116elif sd_model_checkpoint_override:117p.override_settings['sd_model_checkpoint'] = sd_model_checkpoint_override118else:119p.override_settings.pop("sd_model_checkpoint", None)120121if output_dir:122p.outpath_samples = output_dir123p.override_settings['save_to_dirs'] = False124p.override_settings['save_images_replace_action'] = "Add number suffix"125if p.n_iter > 1 or p.batch_size > 1:126p.override_settings['samples_filename_pattern'] = f'{image_path.stem}-[generation_number]'127else:128p.override_settings['samples_filename_pattern'] = f'{image_path.stem}'129130proc = modules.scripts.scripts_img2img.run(p, *args)131132if proc is None:133p.override_settings.pop('save_images_replace_action', None)134proc = process_images(p)135136if not discard_further_results and proc:137if batch_results:138batch_results.images.extend(proc.images)139batch_results.infotexts.extend(proc.infotexts)140else:141batch_results = proc142143if 0 <= shared.opts.img2img_batch_show_results_limit < len(batch_results.images):144discard_further_results = True145batch_results.images = batch_results.images[:int(shared.opts.img2img_batch_show_results_limit)]146batch_results.infotexts = batch_results.infotexts[:int(shared.opts.img2img_batch_show_results_limit)]147148return batch_results149150151def img2img(id_task: str, request: gr.Request, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint, init_mask_inpaint, mask_blur: int, mask_alpha: float, inpainting_fill: int, n_iter: int, batch_size: int, cfg_scale: float, image_cfg_scale: float, denoising_strength: float, selected_scale_tab: int, height: int, width: int, scale_by: float, resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int, inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str, img2img_batch_inpaint_mask_dir: str, override_settings_texts, img2img_batch_use_png_info: bool, img2img_batch_png_info_props: list, img2img_batch_png_info_dir: str, img2img_batch_source_type: str, img2img_batch_upload: list, *args):152override_settings = create_override_settings_dict(override_settings_texts)153154is_batch = mode == 5155156if mode == 0: # img2img157image = init_img158mask = None159elif mode == 1: # img2img sketch160image = sketch161mask = None162elif mode == 2: # inpaint163image, mask = init_img_with_mask["image"], init_img_with_mask["mask"]164mask = processing.create_binary_mask(mask)165elif mode == 3: # inpaint sketch166image = inpaint_color_sketch167orig = inpaint_color_sketch_orig or inpaint_color_sketch168pred = np.any(np.array(image) != np.array(orig), axis=-1)169mask = Image.fromarray(pred.astype(np.uint8) * 255, "L")170mask = ImageEnhance.Brightness(mask).enhance(1 - mask_alpha / 100)171blur = ImageFilter.GaussianBlur(mask_blur)172image = Image.composite(image.filter(blur), orig, mask.filter(blur))173elif mode == 4: # inpaint upload mask174image = init_img_inpaint175mask = init_mask_inpaint176else:177image = None178mask = None179180image = images.fix_image(image)181mask = images.fix_image(mask)182183if selected_scale_tab == 1 and not is_batch:184assert image, "Can't scale by because no image is selected"185186width = int(image.width * scale_by)187height = int(image.height * scale_by)188189assert 0. <= denoising_strength <= 1., 'can only work with strength in [0.0, 1.0]'190191p = StableDiffusionProcessingImg2Img(192sd_model=shared.sd_model,193outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,194outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,195prompt=prompt,196negative_prompt=negative_prompt,197styles=prompt_styles,198batch_size=batch_size,199n_iter=n_iter,200cfg_scale=cfg_scale,201width=width,202height=height,203init_images=[image],204mask=mask,205mask_blur=mask_blur,206inpainting_fill=inpainting_fill,207resize_mode=resize_mode,208denoising_strength=denoising_strength,209image_cfg_scale=image_cfg_scale,210inpaint_full_res=inpaint_full_res,211inpaint_full_res_padding=inpaint_full_res_padding,212inpainting_mask_invert=inpainting_mask_invert,213override_settings=override_settings,214)215216p.scripts = modules.scripts.scripts_img2img217p.script_args = args218219p.user = request.username220221if shared.opts.enable_console_prompts:222print(f"\nimg2img: {prompt}", file=shared.progress_print_out)223224with closing(p):225if is_batch:226if img2img_batch_source_type == "upload":227assert isinstance(img2img_batch_upload, list) and img2img_batch_upload228output_dir = ""229inpaint_mask_dir = ""230png_info_dir = img2img_batch_png_info_dir if not shared.cmd_opts.hide_ui_dir_config else ""231processed = process_batch(p, img2img_batch_upload, output_dir, inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by, use_png_info=img2img_batch_use_png_info, png_info_props=img2img_batch_png_info_props, png_info_dir=png_info_dir)232else: # "from dir"233assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"234processed = process_batch(p, img2img_batch_input_dir, img2img_batch_output_dir, img2img_batch_inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by, use_png_info=img2img_batch_use_png_info, png_info_props=img2img_batch_png_info_props, png_info_dir=img2img_batch_png_info_dir)235236if processed is None:237processed = Processed(p, [], p.seed, "")238else:239processed = modules.scripts.scripts_img2img.run(p, *args)240if processed is None:241processed = process_images(p)242243shared.total_tqdm.clear()244245generation_info_js = processed.js()246if opts.samples_log_stdout:247print(generation_info_js)248249if opts.do_not_show_images:250processed.images = []251252return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")253254255