|
| 1 | +# Changed from https://github.com/GaParmar/img2img-turbo/blob/main/gradio_sketch2image.py |
| 2 | +import os |
| 3 | +import random |
| 4 | +import time |
| 5 | +from datetime import datetime |
| 6 | + |
| 7 | +import torch |
| 8 | +from diffusers import FluxKontextPipeline |
| 9 | +from PIL import Image |
| 10 | +from utils import get_args |
| 11 | +from vars import EXAMPLES, MAX_SEED |
| 12 | + |
| 13 | +from nunchaku.models.transformers.transformer_flux import NunchakuFluxTransformer2dModel |
| 14 | + |
| 15 | +# import gradio last to avoid conflicts with other imports |
| 16 | +import gradio as gr # noqa: isort: skip |
| 17 | + |
| 18 | +args = get_args() |
| 19 | + |
| 20 | +if args.precision == "bf16": |
| 21 | + pipeline = FluxKontextPipeline.from_pretrained("black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16) |
| 22 | + pipeline = pipeline.to("cuda") |
| 23 | + pipeline.precision = "bf16" |
| 24 | +else: |
| 25 | + assert args.precision == "int4" |
| 26 | + pipeline_init_kwargs = {} |
| 27 | + transformer = NunchakuFluxTransformer2dModel.from_pretrained( |
| 28 | + "mit-han-lab/nunchaku-flux.1-kontext-dev/svdq-int4_r32-flux.1-kontext-dev.safetensors" |
| 29 | + ) |
| 30 | + pipeline_init_kwargs["transformer"] = transformer |
| 31 | + if args.use_qencoder: |
| 32 | + from nunchaku.models.text_encoders.t5_encoder import NunchakuT5EncoderModel |
| 33 | + |
| 34 | + text_encoder_2 = NunchakuT5EncoderModel.from_pretrained( |
| 35 | + "mit-han-lab/nunchaku-t5/awq-int4-flux.1-t5xxl.safetensors" |
| 36 | + ) |
| 37 | + pipeline_init_kwargs["text_encoder_2"] = text_encoder_2 |
| 38 | + |
| 39 | + pipeline = FluxKontextPipeline.from_pretrained( |
| 40 | + "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16, **pipeline_init_kwargs |
| 41 | + ) |
| 42 | + pipeline = pipeline.to("cuda") |
| 43 | + pipeline.precision = "int4" |
| 44 | + |
| 45 | + |
| 46 | +def run(image, prompt: str, num_inference_steps: int, guidance_scale: float, seed: int) -> tuple[Image, str]: |
| 47 | + img = image["composite"].convert("RGB") |
| 48 | + |
| 49 | + start_time = time.time() |
| 50 | + result_image = pipeline( |
| 51 | + prompt=prompt, |
| 52 | + image=img, |
| 53 | + height=img.height, |
| 54 | + width=img.width, |
| 55 | + num_inference_steps=num_inference_steps, |
| 56 | + guidance_scale=guidance_scale, |
| 57 | + generator=torch.Generator().manual_seed(seed), |
| 58 | + ).images[0] |
| 59 | + |
| 60 | + latency = time.time() - start_time |
| 61 | + if latency < 1: |
| 62 | + latency = latency * 1000 |
| 63 | + latency_str = f"{latency:.2f}ms" |
| 64 | + else: |
| 65 | + latency_str = f"{latency:.2f}s" |
| 66 | + torch.cuda.empty_cache() |
| 67 | + if args.count_use: |
| 68 | + if os.path.exists(f"{args.model}-use_count.txt"): |
| 69 | + with open(f"{args.model}-use_count.txt", "r") as f: |
| 70 | + count = int(f.read()) |
| 71 | + else: |
| 72 | + count = 0 |
| 73 | + count += 1 |
| 74 | + current_time = datetime.now() |
| 75 | + print(f"{current_time}: {count}") |
| 76 | + with open(f"{args.model}-use_count.txt", "w") as f: |
| 77 | + f.write(str(count)) |
| 78 | + with open(f"{args.model}-use_record.txt", "a") as f: |
| 79 | + f.write(f"{current_time}: {count}\n") |
| 80 | + return result_image, latency_str |
| 81 | + |
| 82 | + |
| 83 | +with gr.Blocks(css_paths="assets/style.css", title="Nunchaku FLUX.1-Kontext Demo") as demo: |
| 84 | + with open("assets/description.html", "r") as f: |
| 85 | + DESCRIPTION = f.read() |
| 86 | + # Get the GPU properties |
| 87 | + if torch.cuda.device_count() > 0: |
| 88 | + gpu_properties = torch.cuda.get_device_properties(0) |
| 89 | + gpu_memory = gpu_properties.total_memory / (1024**3) # Convert to GiB |
| 90 | + gpu_name = torch.cuda.get_device_name(0) |
| 91 | + device_info = f"Running on {gpu_name} with {gpu_memory:.0f} GiB memory." |
| 92 | + else: |
| 93 | + device_info = "Running on CPU 🥶 This demo does not work on CPU." |
| 94 | + notice = '<strong>Notice:</strong> We will replace unsafe prompts with a default prompt: "A peaceful world."' |
| 95 | + |
| 96 | + def get_header_str(): |
| 97 | + |
| 98 | + if args.count_use: |
| 99 | + if os.path.exists("use_count.txt"): |
| 100 | + with open("use_count.txt", "r") as f: |
| 101 | + count = int(f.read()) |
| 102 | + else: |
| 103 | + count = 0 |
| 104 | + count_info = ( |
| 105 | + f"<div style='display: flex; justify-content: center; align-items: center; text-align: center;'>" |
| 106 | + f"<span style='font-size: 18px; font-weight: bold;'>Total inference runs: </span>" |
| 107 | + f"<span style='font-size: 18px; color:red; font-weight: bold;'> {count}</span></div>" |
| 108 | + ) |
| 109 | + else: |
| 110 | + count_info = "" |
| 111 | + header_str = DESCRIPTION.format(device_info=device_info, notice=notice, count_info=count_info) |
| 112 | + return header_str |
| 113 | + |
| 114 | + header = gr.HTML(get_header_str()) |
| 115 | + demo.load(fn=get_header_str, outputs=header) |
| 116 | + |
| 117 | + with gr.Row(elem_id="main_row"): |
| 118 | + with gr.Column(elem_id="column_input"): |
| 119 | + gr.Markdown("## INPUT", elem_id="input_header") |
| 120 | + with gr.Group(): |
| 121 | + canvas = gr.ImageEditor( |
| 122 | + height=640, |
| 123 | + image_mode="RGB", |
| 124 | + sources=["upload", "clipboard"], |
| 125 | + type="pil", |
| 126 | + label="Input", |
| 127 | + show_label=False, |
| 128 | + show_download_button=True, |
| 129 | + interactive=True, |
| 130 | + transforms=[], |
| 131 | + canvas_size=(1024, 1024), |
| 132 | + scale=1, |
| 133 | + format="png", |
| 134 | + layers=False, |
| 135 | + ) |
| 136 | + with gr.Row(): |
| 137 | + prompt = gr.Text(label="Prompt", placeholder="Enter your prompt", scale=6) |
| 138 | + run_button = gr.Button("Run", scale=1, elem_id="run_button") |
| 139 | + |
| 140 | + with gr.Row(): |
| 141 | + seed = gr.Slider(label="Seed", show_label=True, minimum=0, maximum=MAX_SEED, value=233, step=1, scale=4) |
| 142 | + randomize_seed = gr.Button("Random Seed", scale=1, min_width=50, elem_id="random_seed") |
| 143 | + with gr.Accordion("Advanced options", open=False): |
| 144 | + with gr.Group(): |
| 145 | + num_inference_steps = gr.Slider(label="Inference Steps", minimum=10, maximum=50, step=1, value=28) |
| 146 | + guidance_scale = gr.Slider(label="Guidance Scale", minimum=1, maximum=10, step=0.1, value=2.5) |
| 147 | + |
| 148 | + with gr.Column(elem_id="column_output"): |
| 149 | + gr.Markdown("## OUTPUT", elem_id="output_header") |
| 150 | + with gr.Group(): |
| 151 | + result = gr.Image( |
| 152 | + format="png", |
| 153 | + height=640, |
| 154 | + image_mode="RGB", |
| 155 | + type="pil", |
| 156 | + label="Result", |
| 157 | + show_label=False, |
| 158 | + show_download_button=True, |
| 159 | + interactive=False, |
| 160 | + elem_id="output_image", |
| 161 | + ) |
| 162 | + latency_result = gr.Text(label="Inference Latency", show_label=True) |
| 163 | + |
| 164 | + gr.Markdown("### Instructions") |
| 165 | + gr.Markdown("**1**. Enter a text prompt") |
| 166 | + gr.Markdown("**2**. Upload an image") |
| 167 | + gr.Markdown("**3**. Try different seeds to generate different results") |
| 168 | + |
| 169 | + run_inputs = [canvas, prompt, num_inference_steps, guidance_scale, seed] |
| 170 | + run_outputs = [result, latency_result] |
| 171 | + |
| 172 | + gr.Examples(examples=EXAMPLES, inputs=run_inputs, outputs=run_outputs, fn=run) |
| 173 | + |
| 174 | + randomize_seed.click( |
| 175 | + lambda: random.randint(0, MAX_SEED), inputs=[], outputs=seed, api_name=False, queue=False |
| 176 | + ).then(run, inputs=run_inputs, outputs=run_outputs, api_name=False) |
| 177 | + |
| 178 | + gr.on( |
| 179 | + triggers=[prompt.submit, run_button.click], |
| 180 | + fn=run, |
| 181 | + inputs=run_inputs, |
| 182 | + outputs=run_outputs, |
| 183 | + api_name=False, |
| 184 | + ) |
| 185 | + |
| 186 | + gr.Markdown("MIT Accessibility: https://accessibility.mit.edu/", elem_id="accessibility") |
| 187 | + |
| 188 | + |
| 189 | +if __name__ == "__main__": |
| 190 | + demo.queue().launch(debug=True, share=True, root_path=args.gradio_root_path) |
0 commit comments