import gradio as gr import numpy as np import random import torch from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL from live_preview_helpers import flux_pipe_call_that_returns_an_iterable_of_images dtype = torch.float32 # CPU-friendly device = "cpu" # Load models on CPU taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device) good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype).to(device) pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype, vae=taef1).to(device) MAX_SEED = np.iinfo(np.int32).max MAX_IMAGE_SIZE = 1024 # reduce max size for CPU # Bind the custom flux method pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe) def infer(prompt, seed=42, randomize_seed=False, width=512, height=512, guidance_scale=3.5, num_inference_steps=15, progress=gr.Progress(track_tqdm=True)): if randomize_seed: seed = random.randint(0, MAX_SEED) generator = torch.Generator(device=device).manual_seed(seed) for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images( prompt=prompt, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, width=width, height=height, generator=generator, output_type="pil", good_vae=good_vae, ): yield img, seed examples = [ "a tiny astronaut hatching from an egg on the moon", "a cat holding a sign that says hello world", "an anime illustration of a wiener schnitzel", ] css=""" #col-container { margin: 0 auto; max-width: 520px; } """ with gr.Blocks(css=css) as demo: with gr.Column(elem_id="col-container"): gr.Markdown(""" # FLUX.1 [dev] 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/) [[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] """) with gr.Row(): prompt = gr.Textbox( label="Prompt", placeholder="Enter your prompt", lines=1 ) run_button = gr.Button("Run") result = gr.Image(label="Result") with gr.Accordion("Advanced Settings", open=False): seed = gr.Slider(0, MAX_SEED, step=1, label="Seed", value=0) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) width = gr.Slider(256, MAX_IMAGE_SIZE, step=32, label="Width", value=512) height = gr.Slider(256, MAX_IMAGE_SIZE, step=32, label="Height", value=512) guidance_scale = gr.Slider(1.0, 15.0, step=0.1, label="Guidance Scale", value=3.5) num_inference_steps = gr.Slider(1, 30, step=1, label="Inference Steps", value=15) gr.Examples( examples=examples, fn=infer, inputs=[prompt], outputs=[result, seed], cache_examples=False ) run_button.click( fn=infer, inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps], outputs=[result, seed] ) prompt.submit( fn=infer, inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps], outputs=[result, seed] ) demo.launch()