Team Ai
Apppublic

FallnAI/HyperSD15-Scribble

sourceHugging Faceopenrail++updated 2y agoView on Hugging Face
0likes
app.py102 linesDownload Raw Back to root
1import spaces2import argparse3import os4import time5from os import path6from PIL import ImageOps7 8cache_path = path.join(path.dirname(path.abspath(__file__)), "models")9os.environ["TRANSFORMERS_CACHE"] = cache_path10os.environ["HF_HUB_CACHE"] = cache_path11os.environ["HF_HOME"] = cache_path12 13import gradio as gr14import torch15from diffusers import StableDiffusionControlNetPipeline, ControlNetModel16 17from scheduling_tcd import TCDScheduler18 19torch.backends.cuda.matmul.allow_tf32 = True20 21js_func = """22function refresh() {23    const url = new URL(window.location);24 25    if (url.searchParams.get('__theme') !== 'dark') {26        url.searchParams.set('__theme', 'dark');27        window.location.href = url.href;28    }29}30"""31 32class timer:33    def __init__(self, method_name="timed process"):34        self.method = method_name35 36    def __enter__(self):37        self.start = time.time()38        print(f"{self.method} starts")39 40    def __exit__(self, exc_type, exc_val, exc_tb):41        end = time.time()42        print(f"{self.method} took {str(round(end - self.start, 2))}s")43 44if not path.exists(cache_path):45    os.makedirs(cache_path, exist_ok=True)46 47controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-scribble", torch_dtype=torch.float16, use_safetensors=True)48pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, variant="fp16")49pipe.load_lora_weights("ByteDance/Hyper-SD", weight_name="Hyper-SD15-1step-lora.safetensors", adapter_name="default")50pipe.to("cuda")51pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config, timestep_spacing ="trailing")52 53with gr.Blocks(js=js_func) as demo:54    with gr.Column():55        with gr.Row():56            with gr.Column():57                # scribble = gr.Image(source="canvas", tool="color-sketch", shape=(512, 512), height=768, width=768, type="pil")58                scribble = gr.ImageEditor(type="pil", image_mode="L", crop_size=(512, 512), sources=(), brush=gr.Brush(color_mode="fixed", colors=["#FFFFFF"]), canvas_size=(1024, 1024))59                # scribble_out = gr.Image(height=384, width=384)60                num_images = gr.Slider(label="Number of Images", minimum=1, maximum=8, step=1, value=4, interactive=True)61                steps = gr.Slider(label="Inference Steps", minimum=1, maximum=8, step=1, value=1, interactive=True)62                prompt = gr.Text(label="Prompt", value="a photo of a cat", interactive=True)63                eta = gr.Number(label="Eta (Corresponds to parameter eta (η) in the DDIM paper, i.e. 0.0 eqauls DDIM, 1.0 equals LCM)", value=1., interactive=True)64                controlnet_scale = gr.Number(label="ControlNet Conditioning Scale", value=1.0, interactive=True)65                seed = gr.Number(label="Seed", value=3413, interactive=True)66                btn = gr.Button(value="run")67 68            with gr.Column():69                output = gr.Gallery(height=768, format="png")70                # output = gr.Image()71 72        @spaces.GPU73        def process_image(steps, prompt, controlnet_scale, eta, seed, scribble, num_images):74            global pipe75            if scribble:                76                with torch.inference_mode(), torch.autocast("cuda", dtype=torch.float16), timer("inference"):77                    result = pipe(78                        prompt=[prompt]*num_images,79                        image=[ImageOps.invert(scribble['composite'])]*num_images,80                        # image=[scribble['composite']]*num_images,81                        generator=torch.Generator().manual_seed(int(seed)),82                        num_inference_steps=steps,83                        guidance_scale=0.,84                        eta=eta,85                        controlnet_conditioning_scale=float(controlnet_scale),86                    ).images87                    # result[0].save("test.jpg")88                    # print(result[0])89                    return result90            else:91                return None92 93        reactive_controls = [steps, prompt, controlnet_scale, eta, seed, scribble, num_images]94 95        for control in reactive_controls:96            if reactive_controls[-2] is not None:97                control.change(fn=process_image, inputs=reactive_controls, outputs=[output, ])98 99        btn.click(process_image, inputs=reactive_controls, outputs=[output, ])100 101if __name__ == "__main__":102    demo.launch()