Spaces:
Running
on
Zero
Running
on
Zero
File size: 8,885 Bytes
7f4c99b 9f3065c 7f4c99b 9f3065c 7f4c99b 9f3065c 7f4c99b aa0cb15 7f4c99b 9f3065c 7f4c99b 9f3065c 7f4c99b fc39399 3901f50 7f4c99b 0fb3ed4 9f3065c 0fb3ed4 9f3065c 7f4c99b 9f3065c 7f4c99b 0d71a12 9f3065c 7f4c99b 9f3065c 7f4c99b 9f3065c 7f4c99b 9f3065c 7f4c99b 9f3065c 0d71a12 9f3065c 84216fc 0d71a12 520e2e1 0d71a12 9f3065c 84216fc 9f3065c 520e2e1 9f3065c 520e2e1 9f3065c 7f4c99b 9f3065c 97f525d 9f3065c 7f4c99b 9f3065c 0bbd9e4 7f4c99b 9f3065c 7f4c99b 9f3065c 7f4c99b 52a337d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
import os
import subprocess
import sys
import io
import gradio as gr
import numpy as np
import random
import spaces
import torch
from diffusers import Flux2Pipeline, Flux2Transformer2DModel
from diffusers import BitsAndBytesConfig as DiffBitsAndBytesConfig
from optimization import optimize_pipeline_
import requests
from PIL import Image
import json
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
def remote_text_encoder(prompts):
response = requests.post(
"https://remote-text-encoder-flux-2.huggingface.co/predict",
json={"prompt": prompts},
headers={
"Authorization": f"Bearer {os.environ['HF_TOKEN']}",
"Content-Type": "application/json",
},
)
assert response.status_code == 200, f"{response.status_code=}"
prompt_embeds = torch.load(io.BytesIO(response.content))
return prompt_embeds
# Load model
repo_id = "black-forest-labs/FLUX.2-dev"
dit = Flux2Transformer2DModel.from_pretrained(
repo_id, subfolder="transformer", torch_dtype=torch.bfloat16
)
pipe = Flux2Pipeline.from_pretrained(
repo_id, text_encoder=None, transformer=dit, torch_dtype=torch.bfloat16
)
pipe.to("cuda")
pipe.transformer.set_attention_backend("_flash_3_hub")
try:
optimize_pipeline_(
pipe,
image=[Image.new("RGB", (1024, 1024))],
prompt_embeds=remote_text_encoder("prompt").to("cuda"),
guidance_scale=2.5,
width=1024,
height=1024,
num_inference_steps=1,
)
except Exception as e:
print(f"Optimization failed: {e}")
def get_duration(
prompt,
input_images=None,
seed=42,
randomize_seed=False,
width=1024,
height=1024,
num_inference_steps=50,
guidance_scale=2.5,
progress=gr.Progress(track_tqdm=True),
):
num_images = 0 if input_images is None else len(input_images)
step_duration = 1 + 0.7 * num_images
return num_inference_steps * step_duration + 10
@spaces.GPU(duration=get_duration)
def infer(
prompt,
input_images=None,
seed=42,
randomize_seed=False,
width=1024,
height=1024,
num_inference_steps=50,
guidance_scale=2.5,
progress=gr.Progress(track_tqdm=True),
):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# Get prompt embeddings from remote text encoder
progress(0.1, desc="Encoding prompt...")
try:
prompt_embeds = remote_text_encoder(prompt).to("cuda")
except Exception as e:
raise gr.Error(f"Remote text encoder failed: {e}")
# Prepare image list (convert None or empty gallery to None)
image_list = None
if input_images is not None and len(input_images) > 0:
image_list = []
for item in input_images:
image_list.append(item[0])
# Generate image
progress(0.3, desc="Generating image...")
generator = torch.Generator(device=device).manual_seed(seed)
image = pipe(
prompt_embeds=prompt_embeds,
image=image_list,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
generator=generator,
).images[0]
return image, seed
# --- UI Configuration ---
css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');
html, body, .gradio-container {
background-color: #000000 !important;
color: #ffffff !important;
font-family: 'Inter', sans-serif !important;
margin: 0;
padding: 0 !important;
overflow: hidden !important;
height: 100vh !important;
max-height: 100vh !important;
width: 100vw !important;
max-width: 100vw !important;
--color-background-primary: #000000;
--color-background-secondary: #050505;
--color-border-primary: #171717;
--color-text-primary: #ffffff;
--color-text-secondary: #a3a3a3;
}
footer {
display: none !important;
}
/* Layout */
#main-container {
position: fixed !important;
top: 0;
left: 0;
width: 100vw !important;
height: 100vh !important;
gap: 0 !important;
display: flex;
flex-wrap: nowrap;
overflow: hidden;
z-index: 10;
}
#right-sidebar {
background-color: #050505;
border-left: 1px solid #171717;
width: 320px !important;
max-width: 320px !important;
flex: none !important;
padding: 0 !important;
height: 100%;
overflow-y: auto;
}
#center-canvas {
background-color: #090909;
flex-grow: 1 !important;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 20px;
background-image: radial-gradient(#151515 1px, transparent 1px);
background-size: 20px 20px;
height: 100%;
position: relative;
}
/* Components */
#generate-btn {
background: #ffffff !important;
color: #000000 !important;
border-radius: 6px !important;
font-weight: 600 !important;
text-transform: uppercase;
font-size: 11px !important;
border: none !important;
}
#prompt-input textarea {
background-color: #000000 !important;
border: 1px solid #262626 !important;
color: white !important;
border-radius: 8px !important;
}
#prompt-input span {
display: none; /* Hide default label if needed, or style it */
}
/* Accordions */
.accordion {
background: transparent !important;
border: none !important;
border-bottom: 1px solid #171717 !important;
}
.accordion-label {
font-size: 11px !important;
font-weight: 600 !important;
text-transform: uppercase;
color: #a3a3a3 !important;
}
/* Sliders */
input[type=range] {
accent-color: white !important;
}
/* Gallery in Sidebar */
#history-gallery {
flex-grow: 1;
overflow-y: auto;
padding: 10px;
}
#history-gallery .grid-wrap {
grid-template-columns: 1fr !important; /* Force list view */
}
/* Main Image */
#main-image {
background: transparent !important;
border: 1px solid #171717;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
/* Scrollbars */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #000000;
}
::-webkit-scrollbar-thumb {
background: #333;
border-radius: 3px;
}
"""
controls_header_html = """
<div style="padding: 20px 20px 10px 20px;">
<h2 style="font-size: 11px; font-weight: 600; text-transform: uppercase; color: #666; margin: 0;">Configuration</h2>
</div>
"""
with gr.Blocks(title="FLUX.2 [dev]") as demo:
with gr.Row(elem_id="main-container", variant="compact"):
# --- Center Canvas ---
with gr.Column(elem_id="center-canvas"):
with gr.Row(elem_id="canvas-toolbar"):
gr.Markdown("Canvas", elem_id="canvas-info")
result_image = gr.Image(
elem_id="main-image", interactive=False, show_label=False
)
# --- Right Sidebar ---
with gr.Column(elem_id="right-sidebar", min_width=320):
gr.HTML(controls_header_html)
# Prompt Section
prompt = gr.Textbox(
elem_id="prompt-input",
lines=4,
placeholder="Describe your imagination...",
label="Prompt",
show_label=True,
)
run_button = gr.Button("Generate Image", elem_id="generate-btn")
# Settings
input_images = gr.Gallery(
label="Input Image(s)", type="pil", columns=3, rows=1
)
width = gr.Slider(
label="Width",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
guidance_scale = gr.Slider(
label="Guidance Scale", minimum=0.0, maximum=10.0, step=0.1, value=4
)
num_inference_steps = gr.Slider(
label="Inference Steps", minimum=1, maximum=100, step=1, value=30
)
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
# Wiring
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[
prompt,
input_images,
seed,
randomize_seed,
width,
height,
num_inference_steps,
guidance_scale,
],
outputs=[result_image, seed],
)
demo.launch(css=css)
|