Spaces:
Runtime error
Runtime error
Full code
Browse filesFiles changed (4)
- README.md+9-7
- app.py+117-4
- custom_pipeline.pyAdded+168
- requirements.txtAdded+7
123452345677899101112131214---title: Realtime FLUXemoji: 🏃colorFrom: redcolorTo: redtitle: FLUX Realtimeemoji: ⚡colorFrom: yellowcolorTo: pinksdk: gradiosdk_version: 4.44.0sdk_version: 4.36.0app_file: app.pypinned: falsepinned: truelicense: mitshort_description: High quality Images in Realtime---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-referenceCheck out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567893410111213141516671718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import gradio as grimport numpy as npimport randomimport spacesimport torchimport timefrom diffusers import DiffusionPipelinefrom custom_pipeline import FLUXPipelineWithIntermediateOutputs
def greet(name): return "Hello " + name + "!!"# ConstantsMAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 2048DEFAULT_WIDTH = 1024DEFAULT_HEIGHT = 1024DEFAULT_INFERENCE_STEPS = 1
demo = gr.Interface(fn=greet, inputs="text", outputs="text")demo.launch()# Device and model setupdtype = torch.float16pipe = FLUXPipelineWithIntermediateOutputs.from_pretrained( "black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to("cuda")torch.cuda.empty_cache()
# Inference function@spaces.GPU(duration=25)def generate_image(prompt, seed=42, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, randomize_seed=False, num_inference_steps=DEFAULT_INFERENCE_STEPS): if randomize_seed: seed = random.randint(0, MAX_SEED) generator = torch.Generator().manual_seed(seed)
start_time = time.time()
# Only generate the last image in the sequence for img in pipe.generate_images( prompt=prompt, guidance_scale=0, num_inference_steps=num_inference_steps, width=width, height=height, generator=generator ): latency = f"Latency: {(time.time()-start_time):.2f} seconds" yield img, seed, latency
# Example promptsexamples = [ "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", "a futuristic cityscape with flying cars and neon lights", "Photo of a young woman with long, wavy brown hair tied in a bun and glasses. She has a fair complexion and is wearing subtle makeup, emphasizing her eyes and lips. She is dressed in a black top. The background appears to be an urban setting with a building facade, and the sunlight casts a warm glow on her face.", "Imagine steve jobs as Star Wars movie character"]
# --- Gradio UI ---with gr.Blocks() as demo: with gr.Column(elem_id="app-container"): gr.Markdown("# 🎨 Realtime FLUX Image Generator") gr.Markdown("Generate stunning images in real-time with advanced AI technology.")
with gr.Row(): with gr.Column(scale=3): result = gr.Image(label="Generated Image", show_label=False, interactive=False) with gr.Column(scale=1): prompt = gr.Text( label="Prompt", placeholder="Describe the image you want to generate...", lines=3, show_label=False, container=False, ) enhanceBtn = gr.Button("🚀 Enhance Image")
with gr.Column("Advanced Options"): with gr.Row(): latency = gr.Text(show_label=False) with gr.Row(): seed = gr.Number(label="Seed", value=42, precision=0) randomize_seed = gr.Checkbox(label="Randomize Seed", value=False) with gr.Row(): width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=DEFAULT_WIDTH) height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=DEFAULT_HEIGHT) num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=4, step=1, value=DEFAULT_INFERENCE_STEPS)
with gr.Row(): gr.Markdown("### 🌟 Inspiration Gallery") with gr.Row(): gr.Examples( examples=examples, fn=generate_image, inputs=[prompt], outputs=[result, seed], cache_examples="lazy" )
# Event handling - Trigger image generation on button click or input change enhanceBtn.click( fn=generate_image, inputs=[prompt, seed, width, height], outputs=[result, seed, latency], show_progress="hidden", show_api=False, queue=False )
gr.on( triggers=[prompt.input, width.input, height.input, num_inference_steps.input], fn=generate_image, inputs=[prompt, seed, width, height, randomize_seed, num_inference_steps], outputs=[result, seed, latency], show_progress="hidden", show_api=False, trigger_mode="always_last", queue=False )
# Launch the appdemo.launch() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168import torchimport numpy as npfrom diffusers import FluxPipeline, FlowMatchEulerDiscreteSchedulerfrom typing import Any, Dict, List, Optional, Unionfrom PIL import Image
# Constants for shift calculationBASE_SEQ_LEN = 256MAX_SEQ_LEN = 4096BASE_SHIFT = 0.5MAX_SHIFT = 1.2
# Helper functionsdef calculate_timestep_shift(image_seq_len: int) -> float: """Calculates the timestep shift (mu) based on the image sequence length.""" m = (MAX_SHIFT - BASE_SHIFT) / (MAX_SEQ_LEN - BASE_SEQ_LEN) b = BASE_SHIFT - m * BASE_SEQ_LEN mu = image_seq_len * m + b return mu
def prepare_timesteps( scheduler: FlowMatchEulerDiscreteScheduler, num_inference_steps: Optional[int] = None, device: Optional[Union[str, torch.device]] = None, timesteps: Optional[List[int]] = None, sigmas: Optional[List[float]] = None, mu: Optional[float] = None,) -> (torch.Tensor, int): """Prepares the timesteps for the diffusion process.""" if timesteps is not None and sigmas is not None: raise ValueError("Only one of `timesteps` or `sigmas` can be passed.")
if timesteps is not None: scheduler.set_timesteps(timesteps=timesteps, device=device) elif sigmas is not None: scheduler.set_timesteps(sigmas=sigmas, device=device) else: scheduler.set_timesteps(num_inference_steps, device=device, mu=mu)
timesteps = scheduler.timesteps num_inference_steps = len(timesteps) return timesteps, num_inference_steps
# FLUX pipeline functionclass FLUXPipelineWithIntermediateOutputs(FluxPipeline): """ Extends the FluxPipeline to yield intermediate images during the denoising process with progressively increasing resolution for faster generation. """ @torch.inference_mode() def generate_images( self, prompt: Union[str, List[str]] = None, prompt_2: Optional[Union[str, List[str]]] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 4, timesteps: List[int] = None, guidance_scale: float = 3.5, num_images_per_prompt: Optional[int] = 1, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, joint_attention_kwargs: Optional[Dict[str, Any]] = None, max_sequence_length: int = 300, ): """Generates images and yields intermediate results during the denoising process.""" height = height or self.default_sample_size * self.vae_scale_factor width = width or self.default_sample_size * self.vae_scale_factor
# 1. Check inputs self.check_inputs( prompt, prompt_2, height, width, prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, max_sequence_length=max_sequence_length, )
self._guidance_scale = guidance_scale self._joint_attention_kwargs = joint_attention_kwargs self._interrupt = False
# 2. Define call parameters batch_size = 1 if isinstance(prompt, str) else len(prompt) device = self._execution_device
# 3. Encode prompt lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt( prompt=prompt, prompt_2=prompt_2, prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, device=device, num_images_per_prompt=num_images_per_prompt, max_sequence_length=max_sequence_length, lora_scale=lora_scale, ) # 4. Prepare latent variables num_channels_latents = self.transformer.config.in_channels // 4 latents, latent_image_ids = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, generator, latents, ) # 5. Prepare timesteps sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) image_seq_len = latents.shape[1] mu = calculate_timestep_shift(image_seq_len) timesteps, num_inference_steps = prepare_timesteps( self.scheduler, num_inference_steps, device, timesteps, sigmas, mu=mu, ) self._num_timesteps = len(timesteps)
# Handle guidance guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float16).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
# 6. Denoising loop for i, t in enumerate(timesteps): if self.interrupt: continue
timestep = t.expand(latents.shape[0]).to(latents.dtype)
noise_pred = self.transformer( hidden_states=latents, timestep=timestep / 1000, guidance=guidance, pooled_projections=pooled_prompt_embeds, encoder_hidden_states=prompt_embeds, txt_ids=text_ids, img_ids=latent_image_ids, joint_attention_kwargs=self.joint_attention_kwargs, return_dict=False, )[0]
# Yield intermediate result latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0] yield self._decode_latents_to_image(latents, height, width, output_type) torch.cuda.empty_cache()
# Final image self.maybe_free_model_hooks() torch.cuda.empty_cache()
def _decode_latents_to_image(self, latents, height, width, output_type, vae=None): """Decodes the given latents into an image.""" vae = vae or self.vae latents = self._unpack_latents(latents, height, width, self.vae_scale_factor) latents = (latents / vae.config.scaling_factor) + vae.config.shift_factor image = vae.decode(latents, return_dict=False)[0] return self.image_processor.postprocess(image, output_type=output_type)[0]1234567accelerategit+https://github.com/huggingface/diffusers.gittorchgradiotransformersxformerssentencepieceREADME.md+9-7
app.py+117-4
custom_pipeline.pyAdded+168
requirements.txtAdded+7