| import spaces |
| import gradio as gr |
| import torch |
| from diffusers import AutoencoderKL, TCDScheduler |
| from diffusers.models.model_loading_utils import load_state_dict |
| from gradio_imageslider import ImageSlider |
| from huggingface_hub import hf_hub_download |
| from controlnet_union import ControlNetModel_Union |
| from pipeline_fill_sd_xl import StableDiffusionXLFillPipeline |
| from PIL import Image, ImageFilter |
| import numpy as np |
| |
|
|
| MODELS = { |
| "RealVisXL V5.0 Lightning": "SG161222/RealVisXL_V5.0_Lightning", |
| "Lustify Lightning": "GraydientPlatformAPI/lustify-lightning", |
| "Juggernaut XL Lightning": "RunDiffusion/Juggernaut-XL-Lightning", |
| "Juggernaut-XL-V9-GE-RDPhoto2": "AiWise/Juggernaut-XL-V9-GE-RDPhoto2-Lightning_4S", |
| "SatPony-Lightning": "John6666/satpony-lightning-v2-sdxl" |
| } |
|
|
| |
| config_file = hf_hub_download( |
| "xinsir/controlnet-union-sdxl-1.0", |
| filename="config_promax.json", |
| ) |
| config = ControlNetModel_Union.load_config(config_file) |
| controlnet_model = ControlNetModel_Union.from_config(config) |
| model_file = hf_hub_download( |
| "xinsir/controlnet-union-sdxl-1.0", |
| filename="diffusion_pytorch_model_promax.safetensors", |
| ) |
| state_dict = load_state_dict(model_file) |
| model, _, _, _, _ = ControlNetModel_Union._load_pretrained_model( |
| controlnet_model, state_dict, model_file, "xinsir/controlnet-union-sdxl-1.0" |
| ) |
| model.to(device="cuda", dtype=torch.float16) |
| vae = AutoencoderKL.from_pretrained( |
| "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16 |
| ).to("cuda") |
| pipe = StableDiffusionXLFillPipeline.from_pretrained( |
| "SG161222/RealVisXL_V5.0_Lightning", |
| torch_dtype=torch.float16, |
| vae=vae, |
| controlnet=model, |
| variant="fp16", |
| ) |
| pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config) |
| pipe.to("cuda") |
| print(pipe) |
|
|
| def load_default_pipeline(): |
| """仅保留,但当前 Inpaint 逻辑未直接使用,可以删除,但保留以防将来扩展。""" |
| global pipe |
| pipe = StableDiffusionXLFillPipeline.from_pretrained( |
| "GraydientPlatformAPI/lustify-lightning", |
| torch_dtype=torch.float16, |
| vae=vae, |
| controlnet=model, |
| ).to("cuda") |
| print("Default pipeline loaded!") |
|
|
| @spaces.GPU(duration=15) |
| def fill_image(prompt, image, model_selection, paste_back): |
| """ |
| Handles the fill/repair process for inputs from ImageMask (gr. ImageMask). Applies a default 5% expansion to user-drawn masks here. |
| """ |
| global pipe |
|
|
| print(f"Received image: {image}") |
| if image is None: |
| yield None, None |
| return |
|
|
| if model_selection in MODELS: |
| current_model = pipe.config.get("_name_or_path", "") |
| target_model = MODELS[model_selection] |
| if current_model != target_model: |
| |
| del pipe |
| torch.cuda.empty_cache() |
| pipe = StableDiffusionXLFillPipeline.from_pretrained( |
| target_model, |
| torch_dtype=torch.float16, |
| vae=vae, |
| controlnet=model |
| ) |
| pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config) |
| pipe.to("cuda") |
| print(f"Loaded new SDXL model: {target_model}") |
|
|
| ( |
| prompt_embeds, |
| negative_prompt_embeds, |
| pooled_prompt_embeds, |
| negative_pooled_prompt_embeds, |
| ) = pipe.encode_prompt(prompt, "cuda", True) |
| source = image["background"] |
| |
| mask = image["layers"][0] |
| |
| alpha_channel = mask.split()[3] |
| binary_mask = alpha_channel.point(lambda p: 255 if p > 0 else 0).convert("L") |
|
|
| |
| expand_px = max(1, int(min(binary_mask.width, binary_mask.height) * 0.05)) |
| kernel_size = expand_px * 2 + 1 |
| binary_mask = binary_mask.filter(ImageFilter.MaxFilter(kernel_size)) |
| |
|
|
| cnet_image = source.copy() |
| |
| cnet_image.paste(0, (0, 0), binary_mask) |
|
|
| |
| for image_out in pipe( |
| prompt_embeds=prompt_embeds, |
| negative_prompt_embeds=negative_prompt_embeds, |
| pooled_prompt_embeds=pooled_prompt_embeds, |
| negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, |
| image=cnet_image, |
| |
| |
| |
| |
| ): |
| yield image_out, cnet_image |
|
|
| print(f"{model_selection=}") |
| print(f"{paste_back=}") |
| |
| if paste_back: |
| |
| |
| |
| |
| |
| |
| |
| final_output = source.copy() |
| image_out_rgba = image_out.convert("RGBA") |
| |
| inverted_mask = binary_mask.point(lambda p: 255 if p == 0 else 0).convert("L") |
| |
| |
| final_output.paste(image_out_rgba, (0, 0), binary_mask) |
| |
| yield cnet_image, final_output |
| else: |
| |
| yield cnet_image, image_out |
|
|
| def clear_result(): |
| return gr.update(value=None) |
|
|
| def use_output_as_input(output_image): |
| """ |
| Receives the output of ImageSlider (image_out, cnet_image) and returns cnet_image as the new input. |
| """ |
|
|
| return gr.update(value=output_image[0]) |
|
|
| css = """ |
| .nulgradio-container { |
| width: 86vw !important; |
| } |
| .nulcontain { |
| overflow-y: scroll !important; |
| padding: 10px 40px !important; |
| } |
| div#component-17 { |
| height: auto !important; |
| } |
| |
| @media screen and (max-width: 600px) { |
| .img-row{ |
| display: block !important; |
| margin-bottom: 20px !important; |
| } |
| } |
| |
| """ |
|
|
| title = """<h1 align="center">Diffusers Image Inpaint</h1> |
| <div align="center">Upload an image, draw a mask, and enter a prompt to repair/inpaint the masked area.</div> |
| <div style="display: flex; justify-content: center; align-items: center; text-align: center;"> |
| <p style="display: flex;gap: 6px;"> |
| <a href="https://huggingface.co/spaces/fffiloni/diffusers-image-outpout?duplicate=true"> |
| <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-md.svg" alt="Duplicate this Space"> |
| </a> to skip the queue and enjoy faster inference on the GPU of your choice |
| </p> |
| </div> |
| """ |
|
|
| with gr.Blocks(css=css, fill_height=True) as demo: |
| gr.Markdown(title) |
| |
| with gr.Column(): |
| with gr.Row(): |
| with gr.Column(): |
| prompt = gr.Textbox( |
| label="Prompt", |
| info="Describe what to inpaint the mask with", |
| lines=3, |
| ) |
| with gr.Column(): |
| model_selection = gr.Dropdown( |
| choices=list(MODELS.keys()), |
| value="RealVisXL V5.0 Lightning", |
| label="Model", |
| ) |
| with gr.Row(): |
| run_button = gr.Button("Generate") |
| paste_back = gr.Checkbox(True, label="Paste back original") |
| with gr.Row(equal_height=False): |
| input_image = gr.ImageMask( |
| type="pil", label="Input Image", layers=True, elem_classes="img-row" |
| ) |
| result = ImageSlider( |
| interactive=False, |
| label="Generated Image", |
| elem_classes="img-row" |
| ) |
| use_as_input_button = gr.Button("Use as Input Image", visible=False) |
| |
| |
| use_as_input_button.click( |
| fn=use_output_as_input, |
| inputs=[result], |
| outputs=[input_image], |
| queue=False |
| ) |
| |
| |
| run_button.click( |
| fn=clear_result, |
| inputs=None, |
| outputs=result, |
| queue=False, |
| ).then( |
| fn=lambda: gr.update(visible=False), |
| inputs=None, |
| outputs=use_as_input_button, |
| queue=False, |
| ).then( |
| fn=fill_image, |
| inputs=[prompt, input_image, model_selection, paste_back], |
| outputs=[result], |
| ).then( |
| fn=lambda: gr.update(visible=True), |
| inputs=None, |
| outputs=use_as_input_button, |
| queue=False, |
| ) |
| |
| |
| prompt.submit( |
| fn=clear_result, |
| inputs=None, |
| outputs=result, |
| queue=False, |
| ).then( |
| fn=lambda: gr.update(visible=False), |
| inputs=None, |
| outputs=use_as_input_button, |
| queue=False, |
| ).then( |
| fn=fill_image, |
| inputs=[prompt, input_image, model_selection, paste_back], |
| outputs=[result], |
| ).then( |
| fn=lambda: gr.update(visible=True), |
| inputs=None, |
| outputs=use_as_input_button, |
| queue=False, |
| ) |
|
|
| demo.queue(max_size=10).launch(show_error=True) |
|
|