from collections import namedtuple from copy import copy from itertools import permutations, chain import random import csv from io import StringIO from PIL import Image import numpy as np import os import modules.scripts as scripts import gradio as gr from modules import images, sd_samplers from modules.paths import models_path from modules.hypernetworks import hypernetwork from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img from modules.shared import opts, cmd_opts, state import modules.shared as shared import modules.sd_samplers import modules.sd_models import modules.generation_parameters_copypaste as parameters_copypaste def edit_prompt(p,x): img = Image.open(x) params={} params["Prompt"] = "" params["Negative prompt"] = "" params["Seed"] = "" if img.text['parameters']: params = parameters_copypaste.parse_generation_parameters(img.text['parameters']) p.prompt = params["Prompt"] p.negative_prompt = params["Negative prompt"] p.seed = params["Seed"] def apply_checkpoint(p, x, xs): info = modules.sd_models.get_closet_checkpoint_match(x) if info is None: raise RuntimeError(f"Unknown checkpoint: {x}") modules.sd_models.reload_model_weights(shared.sd_model, info) def confirm_checkpoints(p, xs): for x in xs: print(f'confirm_checkpoint {x}') if modules.sd_models.get_closet_checkpoint_match(x) is None: raise RuntimeError(f"Unknown checkpoint: {x}") def draw_xy_grid(p, input_dir, ms, cell): ps = os.listdir(input_dir) ver_texts = [[images.GridAnnotation(y)] for y in ms] hor_texts = [[images.GridAnnotation(x)] for x in ps] # Temporary list of all the images that are generated to be populated into the grid. # Will be filled with empty images for any individual step that fails to process properly image_cache = [] processed_result = None cell_mode = "P" cell_size = (1,1) state.job_count = len(ms) * len(ps) * p.n_iter for iy, y in enumerate(ms): for ix, x in enumerate(ps): state.job = f"{ix + iy * len(ps) + 1} out of {len(ps) * len(ms)}" processed:Processed = cell(os.path.join(input_dir,x), y) try: # this dereference will throw an exception if the image was not processed # (this happens in cases such as if the user stops the process from the UI) processed_image = processed.images[0] if processed_result is None: # Use our first valid processed result as a template container to hold our full results processed_result = copy(processed) cell_mode = processed_image.mode cell_size = processed_image.size processed_result.images = [Image.new(cell_mode, cell_size)] image_cache.append(processed_image) except: image_cache.append(Image.new(cell_mode, cell_size)) if not processed_result: print("Unexpected error: draw_xy_grid failed to return even a single processed image") return Processed() grid = images.image_grid(image_cache, rows=len(ms)) grid = images.draw_grid_annotations(grid, cell_size[0], cell_size[1], hor_texts, ver_texts) processed_result.images[0] = grid return processed_result class SharedSettingsStackHelper(object): def __enter__(self): self.CLIP_stop_at_last_layers = opts.CLIP_stop_at_last_layers self.vae = opts.sd_vae def __exit__(self, exc_type, exc_value, tb): opts.data["sd_vae"] = self.vae modules.sd_models.reload_model_weights() modules.sd_vae.reload_vae_weights() opts.data["CLIP_stop_at_last_layers"] = self.CLIP_stop_at_last_layers class Script(scripts.Script): def title(self): return "PNG/Model Grid" def ui(self, is_img2img): with gr.Row(): input_dir = gr.Textbox(label="PNG input dir", lines=1) with gr.Row(): models = gr.Textbox(label="Checkpoint names", lines=1) return [input_dir ,models] def run(self, p, input_dir ,models): p.batch_count = 1 p.batch_size = 1 ms = [x.strip() for x in chain.from_iterable(csv.reader(StringIO(models)))] confirm_checkpoints(p,ms) def cell(x, y): pc = copy(p) edit_prompt(pc, x) apply_checkpoint(pc, y, ms) return process_images(pc) with SharedSettingsStackHelper(): processed = draw_xy_grid( p, input_dir=input_dir, ms=ms, cell=cell ) if opts.grid_save: images.save_image(processed.images[0], p.outpath_grids, "xy_grid", prompt=p.prompt, seed=processed.seed, grid=True, p=p) return processed