import gradio as gr from huggingface_hub import login import os import torch is_shared_ui = True if "fffiloni/sdxl-control-loras" in os.environ['SPACE_ID'] else False hf_token = os.environ.get("HF_TOKEN") login(token=hf_token) device="cuda" if torch.cuda.is_available() else "cpu" from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline, AutoencoderKL from diffusers.utils import load_image from PIL import Image import torch import numpy as np import cv2 vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16) controlnet = ControlNetModel.from_pretrained( "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16 ) pipe = StableDiffusionXLControlNetPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16, variant="fp16", use_safetensors=True ) pipe.to(device) #pipe.enable_model_cpu_offload() from PIL import Image def resize_image(input_path, output_path, target_height): # Open the input image img = Image.open(input_path) # Calculate the aspect ratio of the original image original_width, original_height = img.size original_aspect_ratio = original_width / original_height # Calculate the new width while maintaining the aspect ratio and the target height new_width = int(target_height * original_aspect_ratio) # Resize the image while maintaining the aspect ratio and fixing the height img = img.resize((new_width, target_height), Image.LANCZOS) # Save the resized image img.save(output_path) return output_path def infer(use_custom_model, model_name, weight_name, custom_lora_weight, image_in, prompt, negative_prompt, preprocessor, controlnet_conditioning_scale, guidance_scale, inf_steps, seed, progress=gr.Progress(track_tqdm=True)): prompt = prompt negative_prompt = negative_prompt generator = torch.Generator(device=device).manual_seed(seed) if image_in == None: raise gr.Error("You forgot to upload a source image.") image_in = resize_image(image_in, "resized_input.jpg", 1024) if preprocessor == "canny": image = load_image(image_in) image = np.array(image) image = cv2.Canny(image, 100, 200) image = image[:, :, None] image = np.concatenate([image, image, image], axis=2) image = Image.fromarray(image) if use_custom_model: if model_name == "": raise gr.Error("you forgot to set a custom model name.") custom_model = model_name # This is where you load your trained weights pipe.load_lora_weights(custom_model, weight_name=weight_name, use_auth_token=True) lora_scale=custom_lora_weight images = pipe( prompt, negative_prompt=negative_prompt, image=image, controlnet_conditioning_scale=float(controlnet_conditioning_scale), guidance_scale = float(guidance_scale), num_inference_steps=inf_steps, generator=generator, cross_attention_kwargs={"scale": lora_scale} ).images else: images = pipe( prompt, negative_prompt=negative_prompt, image=image, controlnet_conditioning_scale=float(controlnet_conditioning_scale), guidance_scale = float(guidance_scale), num_inference_steps=inf_steps, generator=generator, ).images images[0].save(f"result.png") return f"result.png" css=""" #col-container{ margin: 0 auto; max-width: 680px; text-align: left; } div#warning-duplicate { background-color: #ebf5ff; padding: 0 10px 5px; margin: 20px 0; } div#warning-duplicate > .gr-prose > h2, div#warning-duplicate > .gr-prose > p { color: #0f4592!important; } div#warning-duplicate strong { color: #0f4592; } p.actions { display: flex; align-items: center; margin: 20px 0; } div#warning-duplicate .actions a { display: inline-block; margin-right: 10px; } """ with gr.Blocks(css=css) as demo: with gr.Column(elem_id="col-container"): if is_shared_ui: top_description = gr.HTML(f'''

Note: you might want to use a private custom LoRa model

To do so, duplicate the Space and run it on your own profile using your own access token and eventually a GPU (T4-small or A10G-small) for faster inference without waiting in the queue.

Duplicate this Space to start using private models and skip the queue

''', elem_id="warning-duplicate") gr.HTML("""

SD-XL Control LoRas

Use StableDiffusion XL with Diffusers' SDXL ControlNets

""") image_in = gr.Image(source="upload", type="filepath") with gr.Row(): with gr.Column(): prompt = gr.Textbox(label="Prompt") negative_prompt = gr.Textbox(label="Negative prompt", value="extra digit, fewer digits, cropped, worst quality, low quality, glitch, deformed, mutated, ugly, disfigured") guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=7.5) inf_steps = gr.Slider(label="Inference Steps", minimum="25", maximum="50", step=1, value=25) with gr.Column(): preprocessor = gr.Dropdown(label="Preprocessor", choices=["canny"], value="canny", interactive=False, info="For the moment, only canny is available") controlnet_conditioning_scale = gr.Slider(label="Controlnet conditioning Scale", minimum=0.1, maximum=0.9, step=0.01, value=0.5) seed = gr.Slider(label="seed", minimum=0, maximum=500000, step=1, value=42) use_custom_model = gr.Checkbox(label="Use a public custom model ?(optional)", value=False, info="To use a private model, you'll prefer to duplicate the space with your own access token.") with gr.Row(): model_name = gr.Textbox(label="Custom Model to use", placeholder="username/my_custom_public_model") weight_name = gr.Textbox(label="Specific safetensor", placeholder="specific_weight.safetensors") custom_lora_weight = gr.Slider(label="Custom model weights", minimum=0.1, maximum=0.9, step=0.1, value=0.9) submit_btn = gr.Button("Submit") result = gr.Image(label="Result") submit_btn.click( fn = infer, inputs = [use_custom_model, model_name, weight_name, custom_lora_weight, image_in, prompt, negative_prompt, preprocessor, controlnet_conditioning_scale, guidance_scale, inf_steps, seed], outputs = [result] ) demo.queue(max_size=12).launch()