Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import numpy as np | |
| import random | |
| from typing import Optional | |
| # import spaces #[uncomment to use ZeroGPU] | |
| from diffusers import StableDiffusionPipeline, StableDiffusionControlNetPipeline | |
| from diffusers import ControlNetModel | |
| from peft import PeftModel, LoraConfig | |
| from rembg import new_session, remove | |
| from PIL import Image as PILImage | |
| import cv2 | |
| import torch | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| if torch.cuda.is_available(): | |
| torch_dtype = torch.float16 | |
| else: | |
| torch_dtype = torch.float32 | |
| import os | |
| # import torch | |
| MAX_SEED = np.iinfo(np.int32).max | |
| MAX_IMAGE_SIZE = 1024 | |
| CONTROL_MODE_MODEL = { | |
| "Canny Ege Detection" : "lllyasviel/control_v11p_sd15_canny", | |
| "Pixel to Pixel": "lllyasviel/control_v11e_sd15_ip2p", | |
| "M-LSD Line detection" : "lllyasviel/control_v11p_sd15_mlsd", | |
| "HED edge detection (soft edge)" : "lllyasviel/control_sd15_hed", | |
| "Midas depth estimationn" : "lllyasviel/control_v11f1p_sd15_depth", | |
| "Surface Normal Estimation" : "lllyasviel/control_v11p_sd15_normalbae", | |
| "Scribble-Based Generation" : "lllyasviel/control_v11p_sd15_scribble", | |
| "Semantic segmentation" : "lllyasviel/control_v11p_sd15_seg", | |
| "OpenPose pose detection" : "lllyasviel/control_v11p_sd15_openpose", | |
| "Line Art Generation": "lllyasviel/control_v11p_sd15_lineart", | |
| } | |
| # @spaces.GPU #[uncomment to use ZeroGPU] | |
| def infer( | |
| prompt: str, | |
| negative_prompt : str, | |
| width, | |
| height, | |
| lscale=0.0, | |
| remove_background=False, | |
| controlnet_enabled=False, | |
| controlnet_strength=0.0, | |
| controlnet_mode=None, | |
| controlnet_image=None, | |
| ip_adapter_enabled=False, | |
| ip_adapter_scale=0.0, | |
| ip_adapter_image=None, | |
| model_id: Optional[str] = "CompVis/stable-diffusion-v1-4", | |
| seed: Optional[int] = 42, | |
| guidance_scale : Optional[int] = 7, | |
| num_inference_steps : Optional[int] = 20, | |
| progress=gr.Progress(track_tqdm=True), | |
| ): | |
| generator = torch.Generator().manual_seed(seed) | |
| if controlnet_enabled: | |
| if not controlnet_image : | |
| raise ValueError("controlnet_enabled set to True, but controlnet_image not given") | |
| else: | |
| controlnet_model = ControlNetModel.from_pretrained(CONTROL_MODE_MODEL.get(controlnet_mode),torch_dtype=torch_dtype) | |
| if model_id == "SD-v1-5 + Lora" : | |
| pipe=StableDiffusionControlNetPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5",controlnet=controlnet_model, torch_dtype=torch_dtype) | |
| pipe.unet = PeftModel.from_pretrained(pipe.unet , "Emilichcka/diffusion_lora_funny_cat", subfolder="unet", torch_dtype=torch_dtype) | |
| pipe.text_encoder = PeftModel.from_pretrained(pipe.text_encoder,"Emilichcka/diffusion_lora_funny_cat", subfolder="text_encoder", torch_dtype=torch_dtype) | |
| else: | |
| pipe=StableDiffusionControlNetPipeline.from_pretrained(model_id, controlnet=controlnet_model, torch_dtype=torch_dtype) | |
| else: | |
| if model_id == "SD-v1-5 + Lora" : | |
| pipe=StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5",torch_dtype=torch_dtype) | |
| pipe.unet = PeftModel.from_pretrained(pipe.unet , "Emilichcka/diffusion_lora_funny_cat", subfolder="unet", torch_dtype=torch_dtype) | |
| pipe.text_encoder = PeftModel.from_pretrained(pipe.text_encoder,"Emilichcka/diffusion_lora_funny_cat", subfolder="text_encoder", torch_dtype=torch_dtype) | |
| else: | |
| pipe=StableDiffusionPipeline.from_pretrained(model_id) | |
| if ip_adapter_enabled: | |
| ip_adapter_scale = float(ip_adapter_scale) | |
| pipe.load_ip_adapter("h94/IP-Adapter",subfolder="models", weight_name="ip-adapter-plus_sd15.bin", torch_dtype=torch_dtype) | |
| pipe.set_ip_adapter_scale(ip_adapter_scale) | |
| if controlnet_image!= None: | |
| controlnet_image = np.array(controlnet_image) | |
| low_threshold = 100 | |
| high_threshold = 200 | |
| controlnet_image = cv2.Canny(controlnet_image, low_threshold, high_threshold) | |
| controlnet_image = controlnet_image[:, :, None] | |
| controlnet_image = np.concatenate([controlnet_image, controlnet_image, controlnet_image], axis=2) | |
| controlnet_image = PILImage.fromarray(controlnet_image) | |
| pipe = pipe.to(device) | |
| image = pipe( | |
| prompt=prompt, | |
| image=controlnet_image, | |
| negative_prompt=negative_prompt, | |
| guidance_scale=guidance_scale, | |
| num_inference_steps=num_inference_steps, | |
| width=width, | |
| height=height, | |
| generator=generator, | |
| cross_attention_kwargs={"scale": lscale}, | |
| controlnet_conditioning_scale=controlnet_strength, | |
| ip_adapter_image=ip_adapter_image, | |
| ).images[0] | |
| if remove_background: | |
| image = remove(image) | |
| return image, seed | |
| examples = [ | |
| "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", | |
| "An astronaut riding a green horse", | |
| "A delicious ceviche cheesecake slice", | |
| ] | |
| css = """ | |
| #col-container { | |
| margin: 0 auto; | |
| max-width: 880px; | |
| } | |
| """ | |
| default_model_id_choice = [ | |
| "stable-diffusion-v1-5/stable-diffusion-v1-5", | |
| "CompVis/stable-diffusion-v1-4", | |
| "SD-v1-5 + Lora", | |
| "nota-ai/bk-sdm-small", | |
| ] | |
| def update_controlnet_visibility(controlnet_enabled): | |
| return gr.update(visible=controlnet_enabled), gr.update(visible=controlnet_enabled), gr.update(visible=controlnet_enabled) | |
| def update_ip_adapter_visibility(ip_adapter_enabled): | |
| return gr.update(visible=ip_adapter_enabled), gr.update(visible=ip_adapter_enabled) | |
| with gr.Blocks(css=css) as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown(" # Text-to-Image Gradio Template") | |
| with gr.Row(): | |
| model_id = gr.Dropdown( | |
| label="Model Selection", | |
| choices=default_model_id_choice, | |
| value="SD-v1-5 + Lora", | |
| ) | |
| seed = gr.Slider( | |
| label="Seed", | |
| minimum=0, | |
| maximum=MAX_SEED, | |
| step=1, | |
| value=42, | |
| ) | |
| with gr.Row(): | |
| prompt = gr.Text( | |
| label="Prompt", | |
| show_label=False, | |
| max_lines=1, | |
| placeholder="Enter your prompt", | |
| container=False, | |
| ) | |
| run_button = gr.Button("Run", scale=0, variant="primary") | |
| result = gr.Image(label="Result", show_label=False) | |
| with gr.Row(): | |
| remove_background = gr.Checkbox(label="Remove Background", value=False) | |
| controlnet_enabled = gr.Checkbox(label="Enable ControlNet", value=False) | |
| ip_adapter_enabled = gr.Checkbox(label="Enable IP-Adapter", value=False) | |
| with gr.Accordion("ControlNet Settings", open=False): | |
| gr.Markdown("Enable ControlNet to use settings", visible=True) | |
| with gr.Row(): | |
| controlNet_strength = gr.Slider( | |
| label="ControlNet scale", | |
| minimum=0.0, maximum=1.0, step=0.05, value=0.75, | |
| visible=False, | |
| interactive=True, | |
| ) | |
| controlNet_mode = gr.Dropdown( | |
| label="ControlNet Mode", | |
| choices=list(CONTROL_MODE_MODEL.keys()), | |
| visible=False, | |
| interactive=True, | |
| ) | |
| controlNet_image = gr.Image(label="ControlNet Image", type="pil", | |
| interactive=True, visible=False) | |
| with gr.Accordion("IP-Adapter Settings", open=False): | |
| gr.Markdown("Enable IP-Adapter to use settings", visible=True) | |
| with gr.Row(): | |
| ip_adapter_scale = gr.Slider( | |
| label="IP-Adapter Scale", | |
| minimum=0.0, maximum=2.0, step=0.05, value=1.0, | |
| visible=False, | |
| interactive=True, | |
| ) | |
| ip_adapter_image = gr.Image(label="IP-Adapter Image", type="pil",interactive=True, visible=False) | |
| with gr.Accordion("Advanced Settings", open=False): | |
| negative_prompt = gr.Text( | |
| label="Negative prompt", | |
| max_lines=1, | |
| placeholder="Enter a negative prompt", | |
| ) | |
| lora_scale = gr.Slider( | |
| label="LoRA Scale", | |
| minimum=0.0, | |
| maximum=2.0, | |
| step=0.1, | |
| value=1.0, | |
| info="Adjust the influence of the LoRA weights", | |
| interactive=True, | |
| ) | |
| with gr.Row(): | |
| width = gr.Slider( | |
| label="Width", | |
| minimum=256, | |
| maximum=MAX_IMAGE_SIZE, | |
| step=32, | |
| value=512, # Replace with defaults that work for your model | |
| ) | |
| height = gr.Slider( | |
| label="Height", | |
| minimum=256, | |
| maximum=MAX_IMAGE_SIZE, | |
| step=32, | |
| value=512, # Replace with defaults that work for your model | |
| ) | |
| with gr.Row(): | |
| guidance_scale = gr.Slider( | |
| label="Guidance scale", | |
| minimum=0.0, | |
| maximum=10.0, | |
| step=0.1, | |
| value=10.0, # Replace with defaults that work for your model | |
| ) | |
| num_inference_steps = gr.Slider( | |
| label="Number of inference steps", | |
| minimum=1, | |
| maximum=50, | |
| step=1, | |
| value=30, # Replace with defaults that work for your model | |
| ) | |
| gr.Examples(examples=examples, inputs=[prompt]) | |
| gr.on( | |
| triggers=[run_button.click, prompt.submit], | |
| fn=infer, | |
| inputs=[ | |
| prompt, | |
| negative_prompt, | |
| width, | |
| height, | |
| lora_scale, | |
| remove_background, | |
| controlnet_enabled, | |
| controlNet_strength, | |
| controlNet_mode, | |
| controlNet_image, | |
| ip_adapter_enabled, | |
| ip_adapter_scale, | |
| ip_adapter_image, | |
| model_id, | |
| seed, | |
| guidance_scale, | |
| num_inference_steps, | |
| ], | |
| outputs=[result, seed], | |
| ) | |
| controlnet_enabled.change( | |
| fn=update_controlnet_visibility, | |
| inputs=[controlnet_enabled], | |
| outputs=[controlNet_strength, controlNet_mode, controlNet_image], | |
| ) | |
| ip_adapter_enabled.change( | |
| fn=update_ip_adapter_visibility, | |
| inputs=[ip_adapter_enabled], | |
| outputs=[ip_adapter_scale, ip_adapter_image], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(share=True) |