import os from collections import OrderedDict import gradio as gr import shutil import uuid import torch from pathlib import Path from lib.utils.iimage import IImage from PIL import Image from lib import models from lib.methods import rasg, sd, sr from lib.utils import poisson_blend, image_from_url_text TMP_DIR = 'gradio_tmp' if Path(TMP_DIR).exists(): shutil.rmtree(TMP_DIR) Path(TMP_DIR).mkdir(exist_ok=True, parents=True) os.environ['GRADIO_TEMP_DIR'] = TMP_DIR on_huggingspace = os.environ.get("SPACE_AUTHOR_NAME") == "PAIR" negative_prompt_str = "text, bad anatomy, bad proportions, blurry, cropped, deformed, disfigured, duplicate, error, extra limbs, gross proportions, jpeg artifacts, long neck, low quality, lowres, malformed, morbid, mutated, mutilated, out of frame, ugly, worst quality" positive_prompt_str = "Full HD, 4K, high quality, high resolution" example_inputs = [ ['assets/examples/images/a40.jpg', 'medieval castle'], ['assets/examples/images/a4.jpg', 'parrot'], ['assets/examples/images/a65.jpg', 'hoodie'], ['assets/examples/images/a54.jpg', 'salad'], ['assets/examples/images/a51.jpg', 'space helmet'], ['assets/examples/images/a46.jpg', 'stack of books'], ['assets/examples/images/a19.jpg', 'antique greek vase'], ['assets/examples/images/a2.jpg', 'sunglasses'], ] thumbnails = [ 'assets/examples/sbs/a40.png', 'assets/examples/sbs/a4.png', 'assets/examples/sbs/a65.png', 'assets/examples/sbs/a54.png', 'assets/examples/sbs/a51.png', 'assets/examples/sbs/a46.png', 'assets/examples/sbs/a19.png', 'assets/examples/sbs/a2.png' ] example_previews = [ [thumbnails[0], 'Prompt: medieval castle'], [thumbnails[1], 'Prompt: parrot'], [thumbnails[2], 'Prompt: hoodie'], [thumbnails[3], 'Prompt: salad'], [thumbnails[4], 'Prompt: space helmet'], [thumbnails[5], 'Prompt: laptop'], [thumbnails[6], 'Prompt: antique greek vase'], [thumbnails[7], 'Prompt: sunglasses'], ] # Load models inpainting_models = OrderedDict([ ("Dreamshaper Inpainting V8", models.ds_inp.load_model()), ("Stable-Inpainting 2.0", models.sd2_inp.load_model()), ("Stable-Inpainting 1.5", models.sd15_inp.load_model()) ]) sr_model = models.sd2_sr.load_model(device='cuda:1') sam_predictor = models.sam.load_model(device='cuda:0') inp_model = None cached_inp_model_name = '' def remove_cached_inpainting_model(): global inp_model global cached_inp_model_name del inp_model inp_model = None cached_inp_model_name = '' torch.cuda.empty_cache() def set_model_from_name(inp_model_name): global cached_inp_model_name global inp_model if inp_model_name == cached_inp_model_name: print (f"Activating Cached Inpaintng Model: {inp_model_name}") return print (f"Activating Inpaintng Model: {inp_model_name}") inp_model = inpainting_models[inp_model_name] cached_inp_model_name = inp_model_name def rasg_run(use_painta, prompt, input, seed, eta, negative_prompt, positive_prompt, ddim_steps, guidance_scale=7.5, batch_size=4): torch.cuda.empty_cache() seed = int(seed) batch_size = max(1, min(int(batch_size), 4)) image = IImage(input['image']).resize(512) mask = IImage(input['mask']).rgb().resize(512) method = ['rasg'] if use_painta: method.append('painta') inpainted_images = [] blended_images = [] for i in range(batch_size): inpainted_image = rasg.run( ddim = inp_model, method = '-'.join(method), prompt = prompt, image = image.padx(64), mask = mask.alpha().padx(64), seed = seed+i*1000, eta = eta, prefix = '{}', negative_prompt = negative_prompt, positive_prompt = f', {positive_prompt}', dt = 1000 // ddim_steps, guidance_scale = guidance_scale ).crop(image.size) blended_image = poisson_blend(orig_img = image.data[0], fake_img = inpainted_image.data[0], mask = mask.data[0], dilation = 12) blended_images.append(blended_image) inpainted_images.append(inpainted_image.numpy()[0]) return blended_images, inpainted_images def sd_run(use_painta, prompt, input, seed, eta, negative_prompt, positive_prompt, ddim_steps, guidance_scale=7.5, batch_size=4): torch.cuda.empty_cache() seed = int(seed) batch_size = max(1, min(int(batch_size), 4)) image = IImage(input['image']).resize(512) mask = IImage(input['mask']).rgb().resize(512) method = ['default'] if use_painta: method.append('painta') inpainted_images = [] blended_images = [] for i in range(batch_size): inpainted_image = sd.run( ddim = inp_model, method = '-'.join(method), prompt = prompt, image = image.padx(64), mask = mask.alpha().padx(64), seed = seed+i*1000, eta = eta, prefix = '{}', negative_prompt = negative_prompt, positive_prompt = f', {positive_prompt}', dt = 1000 // ddim_steps, guidance_scale = guidance_scale ).crop(image.size) blended_image = poisson_blend(orig_img = image.data[0], fake_img = inpainted_image.data[0], mask = mask.data[0], dilation = 12) blended_images.append(blended_image) inpainted_images.append(inpainted_image.numpy()[0]) return blended_images, inpainted_images def upscale_run( prompt, input, ddim_steps, seed, use_sam_mask, gallery, img_index, negative_prompt='', positive_prompt=', high resolution professional photo'): torch.cuda.empty_cache() # Load SR model and SAM predictor # sr_model = models.sd2_sr.load_model() # sam_predictor = None # if use_sam_mask: # sam_predictor = models.sam.load_model() seed = int(seed) img_index = int(img_index) img_index = 0 if img_index < 0 else img_index img_index = len(gallery) - 1 if img_index >= len(gallery) else img_index img_info = gallery[img_index if img_index >= 0 else 0] inpainted_image = image_from_url_text(img_info) lr_image = IImage(inpainted_image) hr_image = IImage(input['image']).resize(2048) hr_mask = IImage(input['mask']).resize(2048) output_image = sr.run(sr_model, sam_predictor, lr_image, hr_image, hr_mask, prompt=prompt + positive_prompt, noise_level=0, blend_trick=True, blend_output=True, negative_prompt=negative_prompt, seed=seed, use_sam_mask=use_sam_mask) return output_image.numpy()[0], output_image.numpy()[0] def switch_run(use_rasg, model_name, *args): set_model_from_name(model_name) if use_rasg: return rasg_run(*args) return sd_run(*args) with gr.Blocks(css='style.css') as demo: gr.HTML( """
For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.