Spaces:
Running
on
Zero
Running
on
Zero
File size: 24,404 Bytes
7f4c99b add1856 7f4c99b 803c754 7f4c99b add1856 7f4c99b add1856 989c44e 7f4c99b add1856 7f4c99b 989c44e add1856 f98eb37 add1856 f98eb37 add1856 aa0cb15 add1856 7f4c99b add1856 7f4c99b 989c44e 7f4c99b b695f49 7f4c99b 989c44e 0fb3ed4 989c44e 0fb3ed4 989c44e 02b00c0 989c44e add1856 989c44e add1856 0fb3ed4 add1856 989c44e add1856 989c44e add1856 989c44e 02b00c0 989c44e add1856 989c44e add1856 989c44e 803c754 0a3d63d d46cb20 803c754 d46cb20 803c754 d46cb20 add1856 989c44e add1856 803c754 989c44e 803c754 d46cb20 7f4c99b 75ba08b 7f4c99b e3b7665 803c754 d46cb20 803c754 1457fa8 d46cb20 803c754 d2c76bc d46cb20 803c754 d46cb20 803c754 d46cb20 1457fa8 803c754 1457fa8 803c754 d46cb20 d2c76bc 1457fa8 d46cb20 e3b7665 d46cb20 e3b7665 d46cb20 d2c76bc e3b7665 d46cb20 d2c76bc 1457fa8 d46cb20 803c754 e3b7665 d46cb20 e3b7665 d46cb20 5c03551 803c754 d46cb20 1457fa8 803c754 5c03551 d2c76bc 803c754 d2c76bc e3b7665 803c754 d2c76bc 803c754 d2c76bc 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d2c76bc 34137c3 fec0f1f 34137c3 d46cb20 34137c3 d46cb20 e3b7665 fec0f1f e3b7665 803c754 e3b7665 d46cb20 803c754 e3b7665 fec0f1f e3b7665 803c754 dd54cee e3b7665 7f4c99b 803c754 e3b7665 803c754 e3b7665 803c754 dd54cee 34137c3 d2c76bc e3b7665 803c754 d46cb20 803c754 e3b7665 803c754 e3b7665 803c754 989c44e 7f4c99b d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 d46cb20 803c754 3f05cc8 ac4f897 803c754 d2c76bc 803c754 e3b7665 803c754 fec0f1f 803c754 a7b75d1 5c03551 803c754 0a3d63d 803c754 0a3d63d 803c754 e3b7665 803c754 7f4c99b 803c754 7f4c99b d46cb20 803c754 7f4c99b 803c754 34137c3 |
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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 |
import os
import subprocess
import sys
import io
import re
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
import requests
from PIL import Image
import json
import base64
from huggingface_hub import InferenceClient
subprocess.check_call([sys.executable, "-m", "pip", "install", "spaces==0.43.0"])
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
hf_client = InferenceClient(
api_key=os.environ.get("HF_TOKEN"),
)
VLM_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"
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):
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"Text encoder failed: {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(device)
# Pull pre-compiled Flux2 Transformer blocks from HF hub
spaces.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/FLUX.2", variant="fa3")
def image_to_data_uri(img):
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return f"data:image/png;base64,{img_str}"
def upsample_prompt_logic(prompt, image_list):
try:
if image_list and len(image_list) > 0:
# Image + Text Editing Mode
system_content = SYSTEM_PROMPT_WITH_IMAGES
# Construct user message with text and images
user_content = [{"type": "text", "text": prompt}]
for img in image_list:
data_uri = image_to_data_uri(img)
user_content.append({
"type": "image_url",
"image_url": {"url": data_uri}
})
messages = [
{"role": "system", "content": system_content},
{"role": "user", "content": user_content}
]
else:
# Text Only Mode
system_content = SYSTEM_PROMPT_TEXT_ONLY
messages = [
{"role": "system", "content": system_content},
{"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):
"""Update width/height sliders based on uploaded image aspect ratio.
Keeps one side at 1024 and scales the other proportionally, with both sides as multiples of 8."""
if image_list is None or len(image_list) == 0:
return 1024, 1024 # Default dimensions
# Get the first image to determine dimensions
img = image_list[0][0] # Gallery returns list of tuples (image, caption)
img_width, img_height = img.size
aspect_ratio = img_width / img_height
if aspect_ratio >= 1: # Landscape or square
new_width = 1024
new_height = int(1024 / aspect_ratio)
else: # Portrait
new_height = 1024
new_width = int(1024 * aspect_ratio)
# Round to nearest multiple of 8
new_width = round(new_width / 8) * 8
new_height = round(new_height / 8) * 8
# Ensure within valid range (minimum 256, maximum 1024)
new_width = max(256, min(1024, new_width))
new_height = max(256, min(1024, new_height))
return new_width, new_height
# Updated duration function to match generate_image arguments (including progress)
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(65, num_inference_steps * step_duration + 10)
@spaces.GPU(duration=get_duration)
def generate_image(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
# Move embeddings to GPU only when inside the GPU decorated function
prompt_embeds = prompt_embeds.to(device)
generator = torch.Generator(device=device).manual_seed(seed)
pipe_kwargs = {
"prompt_embeds": prompt_embeds,
"image": image_list,
"num_inference_steps": num_inference_steps,
"guidance_scale": guidance_scale,
"generator": generator,
"width": width,
"height": height,
}
# Progress bar for the actual generation steps
if progress:
progress(0, desc="Starting generation...")
image = pipe(**pipe_kwargs).images[0]
return image
def parse_aspect_ratio(aspect_ratio_str):
"""Parse aspect ratio string to get width and height."""
# Extract dimensions from format like "1:1 (1024x1024)"
match = re.search(r'\((\d+)x(\d+)\)', aspect_ratio_str)
if match:
return int(match.group(1)), int(match.group(2))
return 1024, 1024 # Default
def infer(prompt, aspect_ratio="1:1 (1024x1024)", progress=gr.Progress(track_tqdm=True)):
"""Generate an image using FLUX.2 model."""
if not prompt.strip():
raise gr.Error("Please enter a prompt to generate an image.")
# Always use random seed
seed = random.randint(0, MAX_SEED)
# Parse aspect ratio to get width and height
width, height = parse_aspect_ratio(aspect_ratio)
# Fixed inference parameters
num_inference_steps = 30
guidance_scale = 4.0
# Text Encoding (Network bound - No GPU needed)
progress(0.1, desc="Encoding prompt...")
prompt_embeds = remote_text_encoder(prompt)
# Image Generation (GPU bound)
progress(0.3, desc="Generating image...")
image = generate_image(
prompt_embeds,
None, # No input images
width,
height,
num_inference_steps,
guidance_scale,
seed,
progress
)
return image
examples = [
["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"],
["Photorealistic infographic showing the complete Berlin TV Tower (Fernsehturm) from ground base to antenna tip, full vertical view with entire structure visible including concrete shaft, metallic sphere, and antenna spire. Slight upward perspective angle looking up toward the iconic sphere, perfectly centered on clean white background. Left side labels with thin horizontal connector lines: the text '368m' in extra large bold dark grey numerals (#2D3748) positioned at exactly the antenna tip with 'TOTAL HEIGHT' in small caps below. The text '207m' in extra large bold with 'TELECAFÉ' in small caps below, with connector line touching the sphere precisely at the window level. Right side label with horizontal connector line touching the sphere's equator: the text '32m' in extra large bold dark grey numerals with 'SPHERE DIAMETER' in small caps below. Bottom section arranged in three balanced columns: Left - Large text '986' in extra bold dark grey with 'STEPS' in caps below. Center - 'BERLIN TV TOWER' in bold caps with 'FERNSEHTURM' in lighter weight below. Right - 'INAUGURATED' in bold caps with 'OCTOBER 3, 1969' below. All typography in modern sans-serif font (such as Inter or Helvetica), color #2D3748, clean minimal technical diagram style. Horizontal connector lines are thin, precise, and clearly visible, touching the tower structure at exact corresponding measurement points. Professional architectural elevation drawing aesthetic with dynamic low angle perspective creating sense of height and grandeur, poster-ready infographic design with perfect visual hierarchy."],
["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."],
]
examples_images = [
# ["Replace the top of the person from image 1 with the one from image 2", ["person1.webp", "woman2.webp"]],
["The person from image 1 is petting the cat from image 2, the bird from image 3 is next to them", ["woman1.webp", "cat_window.webp", "bird.webp"]]
]
# Apple-inspired CSS styling (matching Z-Image exactly)
css = """
/* Global Styles */
.gradio-container {
max-width: 85vw !important;
margin: 0 auto !important;
padding: 16px 20px !important;
font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', 'Roboto', sans-serif !important;
}
/* Disable all transitions globally */
* {
transition: none !important;
animation: none !important;
}
/* Header */
.header-container {
text-align: left;
margin-bottom: 12px;
}
.main-title {
font-size: 28px !important;
font-weight: 600 !important;
letter-spacing: -0.02em !important;
line-height: 1.07 !important;
color: #f5f5f7 !important;
margin: 0 0 8px 0 !important;
}
/* Input Section */
.input-section {
background: #1d1d1f !important;
border-radius: 18px !important;
padding: 32px !important;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4) !important;
width: 550px !important;
min-width: 550px !important;
max-width: 550px !important;
flex: 0 0 550px !important;
flex-shrink: 0 !important;
flex-grow: 0 !important;
}
/* Textbox */
textarea {
font-size: 15px !important;
line-height: 1.47 !important;
border-radius: 12px !important;
border: 1px solid #424245 !important;
padding: 12px 16px !important;
background: #2d2d2f !important;
color: #f5f5f7 !important;
font-family: -apple-system, BlinkMacSystemFont, 'Inter', sans-serif !important;
min-height: 480px !important;
max-height: 600px !important;
height: 480px !important;
resize: vertical !important;
overflow-y: auto !important;
margin-bottom: 12px !important;
}
/* Disable label click highlight */
label {
pointer-events: none !important;
}
textarea:focus {
border-color: #0071e3 !important;
box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.15) !important;
outline: none !important;
}
textarea::placeholder {
color: #86868b !important;
}
/* Character counter */
.char-counter {
text-align: center;
font-size: 13px;
color: #86868b;
margin-top: -12px;
margin-bottom: 16px;
font-family: -apple-system, BlinkMacSystemFont, 'Inter', sans-serif;
}
.char-counter.warning {
color: #ff9500;
}
.char-counter.limit {
color: #ff3b30;
}
/* Button */
button.primary {
font-size: 17px !important;
font-weight: 400 !important;
padding: 12px 32px !important;
border-radius: 980px !important;
background: #0071e3 !important;
border: none !important;
color: #ffffff !important;
min-height: 44px !important;
letter-spacing: -0.01em !important;
cursor: pointer !important;
width: 100% !important;
}
button.primary:hover {
background: #0077ed !important;
}
button.primary:active {
opacity: 0.9 !important;
}
/* Output Section - White outer, dark inner like Z-Image */
div.output-section {
background: #ffffff !important;
border-radius: 18px !important;
padding: 32px !important;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08) !important;
overflow: hidden !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
min-height: 80vh !important;
max-height: 90vh !important;
will-change: auto !important;
position: relative !important;
flex-grow: 1 !important;
flex-shrink: 0 !important;
flex-basis: auto !important;
}
.output-section * {
transform: none !important;
transition: none !important;
animation: none !important;
}
.output-section img {
border-radius: 12px !important;
max-width: 100% !important;
max-height: 85vh !important;
width: auto !important;
height: auto !important;
object-fit: contain !important;
transform: none !important;
transition: none !important;
animation: none !important;
backface-visibility: hidden !important;
-webkit-backface-visibility: hidden !important;
}
/* Inner image area - white background matching Z-Image */
.output-section > div {
width: 100% !important;
min-height: 75vh !important;
max-height: 85vh !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
}
.output-section > div > div {
min-height: 75vh !important;
max-height: 85vh !important;
width: 100% !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
}
.output-section * {
max-width: 100% !important;
}
/* Dark mode - input section only (output stays white like Z-Image) */
.dark .input-section {
background: #1d1d1f !important;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4) !important;
}
/* Title color */
.input-section .main-title {
color: #f5f5f7 !important;
}
/* Layout - Force horizontal layout */
#main-row {
align-items: flex-start !important;
flex-direction: row !important;
display: flex !important;
flex-wrap: nowrap !important;
width: 100% !important;
gap: 24px !important;
}
.gradio-row {
align-items: flex-start !important;
flex-direction: row !important;
display: flex !important;
flex-wrap: nowrap !important;
width: 100% !important;
}
.gradio-row > .gradio-column:first-child,
.gradio-row > div:first-child {
width: 550px !important;
min-width: 550px !important;
max-width: 550px !important;
flex: 0 0 550px !important;
}
.gradio-row > .gradio-column:last-child,
.gradio-row > div:last-child {
flex: 1 1 auto !important;
min-width: 0 !important;
}
/* Hide footer */
footer {
display: none !important;
}
/* Responsive adjustments */
@media (max-width: 1200px) {
#main-row {
flex-direction: column !important;
flex-wrap: wrap !important;
}
.input-section {
width: 100% !important;
min-width: 100% !important;
max-width: 100% !important;
flex: 1 1 100% !important;
}
.output-section {
width: 100% !important;
min-height: 50vh !important;
}
}
"""
# JavaScript for layout control and character counter (matching Z-Image)
js_code = """
function() {
function setupCharCounter() {
const textbox = document.querySelector('#prompt-textbox textarea');
const counter = document.querySelector('.char-counter');
const countSpan = document.getElementById('char-count');
if (textbox && counter && countSpan) {
function updateCount() {
const len = textbox.value.length;
countSpan.textContent = len;
counter.classList.remove('warning', 'limit');
if (len >= 2000) {
counter.classList.add('limit');
} else if (len >= 1800) {
counter.classList.add('warning');
}
}
textbox.addEventListener('input', updateCount);
updateCount();
}
}
function forceHorizontalLayout() {
const container = document.querySelector('.gradio-container');
if (container) {
container.style.maxWidth = '85vw';
container.style.width = '85vw';
}
const mainRow = document.getElementById('main-row');
if (mainRow) {
mainRow.style.flexDirection = 'row';
mainRow.style.flexWrap = 'nowrap';
mainRow.style.display = 'flex';
mainRow.style.width = '100%';
}
const rows = document.querySelectorAll('.gradio-row');
rows.forEach(row => {
row.style.flexDirection = 'row';
row.style.flexWrap = 'nowrap';
row.style.display = 'flex';
});
const inputCol = document.getElementById('input-column');
if (inputCol) {
inputCol.style.width = '550px';
inputCol.style.minWidth = '550px';
inputCol.style.maxWidth = '550px';
inputCol.style.flex = '0 0 550px';
}
const outputCol = document.getElementById('output-column');
if (outputCol) {
outputCol.style.flex = '1 1 auto';
outputCol.style.minWidth = '0';
}
}
forceHorizontalLayout();
setupCharCounter();
setTimeout(forceHorizontalLayout, 100);
setTimeout(forceHorizontalLayout, 500);
setTimeout(forceHorizontalLayout, 1000);
setTimeout(forceHorizontalLayout, 2000);
setTimeout(setupCharCounter, 100);
setTimeout(setupCharCounter, 500);
const observer = new MutationObserver(forceHorizontalLayout);
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
}
"""
with gr.Blocks(
title="FLUX.2-Image",
fill_height=False,
) as demo:
# Two-column layout
with gr.Row(equal_height=False, variant="panel", elem_id="main-row"):
# LEFT COLUMN - Input Controls
with gr.Column(scale=0, min_width=550, elem_classes="input-section", elem_id="input-column"):
# Header
gr.HTML("""
<div class="header-container">
<h1 class="main-title">FLUX.2-Image</h1>
</div>
""")
# Prompt Textbox
prompt = gr.Textbox(
placeholder="Describe the image you want to create...",
value="Ultra-detailed isometric 3D diorama of a compact AI research lab inside a cutaway cube room. One person seated at a large desk placed directly against the left wall, equipped with exactly three displays, working at a keyboard, wearing large white over-ear headphones, with the mouse positioned next to the person's right hand. A large whiteboard mounted on the left wall directly in front of the desk, filled with technical diagrams and flowcharts. The room is bright, clean, and uncluttered, with a minimalist gray floor and walls.\n\nAlong the right side of the room, arranged from left to right: two tall server racks standing side by side with no gap between them, fully filled from floor to top with dense AI server units and glowing green LED indicator lights; next to the racks, a small snack bar with neatly arranged packaged snacks on shelves and a counter; and at the far right, a clear glass-front refrigerator filled with energy drinks. These are the only server racks in the room. Clean modern lighting, realistic soft shadows, no floating screens or holograms, high realism, sharp focus, professional isometric 3D style.",
lines=20,
max_lines=25,
max_length=2000,
label="Prompt",
show_label=True,
container=True,
autoscroll=False,
elem_id="prompt-textbox",
)
# Character Counter
char_counter = gr.HTML(
'<div class="char-counter"><span id="char-count">0</span> characters (max 2000)</div>'
)
# Aspect Ratio Dropdown
aspect_ratio = gr.Dropdown(
choices=[
"1:1 (1024x1024)",
"2:3 (680x1024)",
"3:2 (1024x680)",
"3:4 (768x1024)",
"4:3 (1024x768)",
"9:16 (576x1024)",
"16:9 (1024x576)",
],
value="1:1 (1024x1024)",
label="Aspect Ratio",
show_label=True,
container=True,
)
# Generate Button
generate_btn = gr.Button(
"Generate",
variant="primary",
size="lg",
elem_classes="primary"
)
# RIGHT COLUMN - Image Output
with gr.Column(scale=2, elem_classes="output-section", elem_id="output-column"):
result = gr.Image(
label="Result",
show_label=False,
type="pil",
format="png",
)
# Event handlers
gr.on(
triggers=[generate_btn.click, prompt.submit],
fn=infer,
inputs=[prompt, aspect_ratio],
outputs=[result],
show_progress="full"
)
# Load JavaScript for layout control
demo.load(None, None, None, js=js_code)
demo.launch(
share=False,
show_error=True,
theme=gr.themes.Soft(
primary_hue=gr.themes.colors.blue,
secondary_hue=gr.themes.colors.slate,
neutral_hue=gr.themes.colors.gray,
spacing_size=gr.themes.sizes.spacing_lg,
radius_size=gr.themes.sizes.radius_lg,
text_size=gr.themes.sizes.text_md,
font=[gr.themes.GoogleFont("Inter"), "SF Pro Display", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "SF Mono", "ui-monospace", "monospace"],
).set(
body_background_fill='#f5f5f7',
body_background_fill_dark='#000000',
button_primary_background_fill='#0071e3',
button_primary_background_fill_hover='#0077ed',
button_primary_text_color='#ffffff',
block_background_fill='#ffffff',
block_background_fill_dark='#1d1d1f',
block_border_width='0px',
block_shadow='0 2px 12px rgba(0, 0, 0, 0.08)',
block_shadow_dark='0 2px 12px rgba(0, 0, 0, 0.4)',
input_background_fill='#ffffff',
input_background_fill_dark='#1d1d1f',
input_border_width='1px',
input_border_color='#d2d2d7',
input_border_color_dark='#424245',
input_shadow='none',
input_shadow_focus='0 0 0 4px rgba(0, 113, 227, 0.15)',
),
css=css,
) |