Spaces:
Runtime error
Runtime error
File size: 7,802 Bytes
cc579f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
#!/usr/bin/env python
import cv2
import numpy as np
import torch
import random
import base64
import json
import threading
import uuid
import math
import io
from PIL import Image
from diffusers import AutoencoderKL, StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler,StableDiffusionControlNetImg2ImgPipeline,StableDiffusionXLControlNetPipeline,DiffusionPipeline
from diffusers.utils import load_image
from transformers import pipeline
import gradio as gr
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
canny_controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_canny", torch_dtype=torch.float16)
canny_pipe = StableDiffusionControlNetPipeline.from_pretrained(
"SG161222/Realistic_Vision_V3.0_VAE", controlnet=canny_controlnet, torch_dtype=torch.float16, use_safetensors=True
)
canny_controlnet_tile = ControlNetModel.from_pretrained("lllyasviel/control_v11f1e_sd15_tile", torch_dtype=torch.float16)
canny_pipe_img2img = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
"SG161222/Realistic_Vision_V3.0_VAE", controlnet=canny_controlnet_tile, torch_dtype=torch.float16, use_safetensors=True
)
canny_pipe_img2img.enable_model_cpu_offload()
canny_pipe_img2img.enable_xformers_memory_efficient_attention()
canny_pipe.scheduler = UniPCMultistepScheduler.from_config(canny_pipe.scheduler.config)
canny_pipe.enable_model_cpu_offload()
canny_pipe.enable_xformers_memory_efficient_attention()
controlnet_xl = ControlNetModel.from_pretrained(
"diffusers/controlnet-canny-sdxl-1.0",
torch_dtype=torch.float16
)
vae_xl = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe_xl = StableDiffusionXLControlNetPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
controlnet=controlnet_xl,
vae=vae_xl,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
pipe_xl.scheduler = UniPCMultistepScheduler.from_config(pipe_xl.scheduler.config)
pipe_xl.enable_xformers_memory_efficient_attention()
pipe_xl.enable_model_cpu_offload()
refiner = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-refiner-1.0",
text_encoder_2=pipe_xl.text_encoder_2,
vae=pipe_xl.vae,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
refiner.enable_xformers_memory_efficient_attention()
refiner.enable_model_cpu_offload()
def resize_image_output(im, width, height):
im = np.array(im)
newSize = (width,height)
img = cv2.resize(im, newSize, interpolation=cv2.INTER_CUBIC)
img = Image.fromarray(img)
return img
def resize_image(im, max_size = 590000):
[x,y,z] = im.shape
new_size = [0,0]
min_size = 262144
if x*y > max_size:
scale_ratio = math.sqrt((x*y)/max_size)
new_size[0] = int(x / scale_ratio)
new_size[1] = int(y / scale_ratio)
elif x*y <= min_size:
scale_ratio = math.sqrt((x*y)/min_size)
new_size[0] = int(x / scale_ratio)
new_size[1] = int(y / scale_ratio)
else:
new_size[0] = int(x)
new_size[1] = int(y)
height = (new_size[0] // 8) * 8
width = (new_size[1] // 8) * 8
newSize = (width,height)
img = cv2.resize(im, newSize, interpolation=cv2.INTER_CUBIC)
return img
def process_canny_tile(input_image,control_image, x ,y, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength_conditioning, scale, seed, eta, low_threshold, high_threshold):
image = input_image
return canny_pipe_img2img(
prompt = '',
image=image,
control_image = image,
num_inference_steps=20,
guidance_scale=4,
strength = 0.3,
guess_mode = True,
negative_prompt=n_prompt,
num_images_per_prompt=1,
eta=eta,
generator=torch.Generator(device="cpu").manual_seed(seed)
)
def process_canny(input_image,x ,y, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold):
image = input_image
print(strength)
return canny_pipe(
prompt=','.join([prompt,a_prompt]),
image=image,
height=x,
width=y,
num_inference_steps=ddim_steps,
guidance_scale=scale,
negative_prompt=n_prompt,
num_images_per_prompt=num_samples,
eta=eta,
controlnet_conditioning_scale=strength,
generator=torch.Generator(device="cpu").manual_seed(seed)
)
def process_canny_sdxl(input_image,x ,y, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold):
image = input_image
image = pipe_xl(
prompt=','.join([prompt,a_prompt]),
image=image,
height=x,
width=y,
num_inference_steps=ddim_steps,
guidance_scale=scale,
negative_prompt=n_prompt,
num_images_per_prompt=num_samples,
eta=eta,
controlnet_conditioning_scale=strength,
generator=torch.Generator(device="cpu").manual_seed(seed),
output_type="latent"
).images
return refiner(
prompt=prompt,
num_inference_steps=ddim_steps,
num_images_per_prompt=num_samples,
denoising_start=0.8,
image=image,
)
def process(image, prompt, a_prompt, n_prompt, ddim_steps, strength, scale, seed, eta, low_threshold, high_threshold):
image = load_image(image)
image = np.array(image)
[x_orig,y_orig,z_orig] = image.shape
image = resize_image(image)
[x,y,z] = image.shape
image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
image = Image.fromarray(image)
return process_canny(image,x,y, prompt, a_prompt, n_prompt, 1, None, ddim_steps, False, float(strength), scale, seed, eta, low_threshold, high_threshold)
demo = gr.Blocks().queue()
with demo:
with gr.Row():
gr.Markdown("## Control Stable Diffusion with Canny Edge Maps")
with gr.Row():
with gr.Column():
input_image = gr.Image(type="pil", label="Input Image")
input_prompt = gr.Textbox()
run_button = gr.Button(label="Run")
with gr.Accordion("Advanced Options"):
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
low_threshold = gr.Slider(label="Canny low threshold", minimum=1, maximum=255, value=100, step=1)
high_threshold = gr.Slider(label="Canny high threshold", minimum=1, maximum=255, value=200, step=1)
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=7.5, step=0.1) # default value was 9.0
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
eta = gr.Number(label="eta (DDIM)", value=0.0)
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
n_prompt = gr.Textbox(label="Negative Prompt",
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
with gr.Column():
result = gr.outputs.Image(label='Output', type="pil")
ips = [input_image, input_prompt, a_prompt, n_prompt, ddim_steps, strength, scale, seed, eta, low_threshold, high_threshold]
run_button.click(fn=process, inputs=ips, outputs=[result])
demo.launch()
|