FLUX.2-dev-demo / app.py
danieljan1983's picture
Upload folder using huggingface_hub
9555c11 verified
Raw History Blame Contribute Delete
9.8 kB
import spaces # must be imported before torch / diffusers
import os
import io
import random
import base64
import gradio as gr
import numpy as np
import torch
from diffusers import Flux2Pipeline, Flux2Transformer2DModel
from huggingface_hub import InferenceClient
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
REPO_ID = "black-forest-labs/FLUX.2-dev"
VLM_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"
TEXT_ENCODER_SPACE = "multimodalart/mistral-text-encoder"
hf_client = InferenceClient(api_key=os.environ.get("HF_TOKEN"))
SYSTEM_PROMPT_TEXT_ONLY = """You are an expert prompt engineer for FLUX.2 by Black Forest Labs. Rewrite user prompts to be more descriptive while strictly preserving their core subject and intent.
Guidelines:
1. Structure: Keep structured inputs structured (enhance within fields). Convert natural language to detailed paragraphs.
2. Details: Add concrete visual specifics - form, scale, textures, materials, lighting (quality, direction, color), shadows, spatial relationships, and environmental context.
3. Text in Images: Put ALL text in quotation marks, matching the prompt's language. Always provide explicit quoted text for objects that would contain text in reality (signs, labels, screens, etc.) - without it, the model generates gibberish.
Output only the revised prompt and nothing else."""
SYSTEM_PROMPT_WITH_IMAGES = """You are FLUX.2 by Black Forest Labs, an image-editing expert. You convert editing requests into one concise instruction (50-80 words, ~30 for brief requests).
Rules:
- Single instruction only, no commentary
- Use clear, analytical language (avoid "whimsical," "cascading," etc.)
- Specify what changes AND what stays the same (face, lighting, composition)
- Reference actual image elements
- Turn negatives into positives ("don't change X" -> "keep X")
- Make abstractions concrete ("futuristic" -> "glowing cyan neon, metallic panels")
- Keep content PG-13
Output only the final instruction in plain text and nothing else."""
def remote_text_encoder(prompts):
"""Encode the prompt with Mistral on a separate Space (the 24B encoder does not fit next to the DiT)."""
from gradio_client import Client
client = Client(TEXT_ENCODER_SPACE, token=os.environ.get("HF_TOKEN"))
result = client.predict(prompt=prompts, api_name="/encode_text")
return torch.load(result[0], weights_only=True)
# Load model: transformer on the ZeroGPU device, text encoder is remote.
dit = Flux2Transformer2DModel.from_pretrained(REPO_ID, subfolder="transformer", torch_dtype=dtype)
pipe = Flux2Pipeline.from_pretrained(REPO_ID, text_encoder=None, transformer=dit, torch_dtype=dtype)
pipe.to(device)
# Pre-compiled (AoT) transformer blocks for FLUX.2 on ZeroGPU
spaces.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/FLUX.2")
def image_to_data_uri(img):
buffered = io.BytesIO()
img.save(buffered, format="PNG")
return "data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode("utf-8")
def upsample_prompt_logic(prompt, image_list):
try:
if image_list:
system_content = SYSTEM_PROMPT_WITH_IMAGES
user_content = [{"type": "text", "text": prompt}]
for img in image_list:
user_content.append({"type": "image_url", "image_url": {"url": image_to_data_uri(img)}})
messages = [
{"role": "system", "content": system_content},
{"role": "user", "content": user_content},
]
else:
messages = [
{"role": "system", "content": SYSTEM_PROMPT_TEXT_ONLY},
{"role": "user", "content": prompt},
]
completion = hf_client.chat.completions.create(model=VLM_MODEL, messages=messages, max_tokens=1024)
return completion.choices[0].message.content
except Exception as e:
print(f"Upsampling failed: {e}")
return prompt
def update_dimensions_from_image(image_list):
"""Keep the longer side at 1024 and scale the other, both multiples of 8."""
if not image_list:
return 1024, 1024
img_width, img_height = image_list[0][0].size
aspect_ratio = img_width / img_height
if aspect_ratio >= 1:
new_width, new_height = 1024, int(1024 / aspect_ratio)
else:
new_height, new_width = 1024, int(1024 * aspect_ratio)
new_width = max(256, min(1024, round(new_width / 8) * 8))
new_height = max(256, min(1024, round(new_height / 8) * 8))
return new_width, new_height
def get_duration(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
num_images = 0 if image_list is None else len(image_list)
step_duration = 1 + 0.8 * num_images
return max(75, num_inference_steps * step_duration + 20)
@spaces.GPU(duration=get_duration, size="xlarge")
def generate_image(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
prompt_embeds = prompt_embeds.to(device)
generator = torch.Generator(device=device).manual_seed(seed)
if progress:
progress(0, desc="Starting generation...")
return pipe(
prompt_embeds=prompt_embeds,
image=image_list,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
generator=generator,
width=width,
height=height,
).images[0]
def infer(prompt, input_images=None, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=30, guidance_scale=4.0, prompt_upsampling=False, progress=gr.Progress(track_tqdm=True)):
"""Generate an image from a text prompt, or edit/combine up to several reference images with a text instruction using FLUX.2 [dev]."""
if randomize_seed:
seed = random.randint(0, MAX_SEED)
image_list = [item[0] for item in input_images] if input_images else None
final_prompt = prompt
if prompt_upsampling:
progress(0.05, desc="Upsampling prompt...")
final_prompt = upsample_prompt_logic(prompt, image_list)
print(f"Original Prompt: {prompt}\nUpsampled Prompt: {final_prompt}")
progress(0.1, desc="Encoding prompt...")
prompt_embeds = remote_text_encoder(final_prompt)
progress(0.3, desc="Waiting for GPU...")
image = generate_image(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress)
return image, seed
examples = [
["Soaking wet capybara taking shelter under a banana leaf in the rainy jungle, close up photo"],
["A kawaii die-cut sticker of a chubby orange cat, featuring big sparkly eyes and a happy smile with paws raised in greeting and a heart-shaped pink nose. The design should have smooth rounded lines with black outlines and soft gradient shading with pink cheeks."],
["Create a vase on a table in living room, the color of the vase is a gradient of color, starting with #02eb3c color and finishing with #edfa3c. The flowers inside the vase have the color #ff0088"],
]
css = """
#col-container { margin: 0 auto; max-width: 1200px; }
.gallery-container img { object-fit: contain; }
"""
with gr.Blocks() as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# FLUX.2 [dev]\n"
"32B rectified-flow model for generating, editing and combining images from text instructions "
"[[model](https://huggingface.co/black-forest-labs/FLUX.2-dev)] [[blog](https://bfl.ai/blog/flux-2)]. "
"Licence: FLUX [dev] Non-Commercial."
)
with gr.Row():
with gr.Column():
with gr.Row():
prompt = gr.Text(label="Prompt", show_label=False, max_lines=2, placeholder="Enter your prompt", container=False, scale=3)
run_button = gr.Button("Run", scale=1)
with gr.Accordion("Input image(s) (optional, for editing)", open=True):
input_images = gr.Gallery(label="Input Image(s)", type="pil", columns=3, rows=1)
with gr.Accordion("Advanced Settings", open=False):
prompt_upsampling = gr.Checkbox(label="Prompt Upsampling", value=False, info="Enhance the prompt with a VLM via Inference Providers (falls back to the original prompt on error)")
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=8, value=1024)
height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=8, value=1024)
with gr.Row():
num_inference_steps = gr.Slider(label="Number of inference steps", minimum=1, maximum=100, step=1, value=30)
guidance_scale = gr.Slider(label="Guidance scale", minimum=0.0, maximum=10.0, step=0.1, value=4)
with gr.Column():
result = gr.Image(label="Result", show_label=False)
gr.Examples(examples=examples, fn=infer, inputs=[prompt], outputs=[result, seed], cache_examples=False)
input_images.upload(fn=update_dimensions_from_image, inputs=[input_images], outputs=[width, height])
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[prompt, input_images, seed, randomize_seed, width, height, num_inference_steps, guidance_scale, prompt_upsampling],
outputs=[result, seed],
)
if __name__ == "__main__":
demo.queue().launch(css=css, mcp_server=False)