Spaces:
Running
on
Zero
Running
on
Zero
File size: 26,645 Bytes
5a48378 b35c0f1 5a48378 b35c0f1 90e0b08 5a48378 b35c0f1 5a48378 679db62 5a48378 b35c0f1 5a48378 b35c0f1 5a48378 679db62 5a48378 679db62 5a48378 e2fd487 5a48378 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 679db62 8f09400 679db62 c6d87fc 679db62 f7ae27d 679db62 f7ae27d 679db62 f7ae27d 8f09400 679db62 3a529fc 679db62 5a48378 90e0b08 776d15b 90e0b08 776d15b 90e0b08 776d15b 90e0b08 a01c472 679db62 5a48378 679db62 5a48378 679db62 5a48378 679db62 90e0b08 b35c0f1 679db62 9390377 b35c0f1 679db62 a01c472 b35c0f1 90e0b08 679db62 90e0b08 b35c0f1 679db62 90e0b08 679db62 90e0b08 679db62 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 776d15b 90e0b08 776d15b 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 b35c0f1 90e0b08 679db62 b35c0f1 679db62 5a48378 |
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 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 |
import spaces
import os
import re
import json
import time
import torch
import tempfile
import io
import random
import string
import logging
from typing import Tuple, Optional, List, Dict, Any, Union
from PIL import Image, ImageDraw, ImageFont
from tqdm import tqdm
import gradio as gr
from safetensors.torch import save_file
from src.pipeline import FluxPipeline
from src.transformer_flux import FluxTransformer2DModel
from src.lora_helper import set_single_lora, set_multi_lora, unset_lora
# Google Gemini API ์ถ๊ฐ
from google import genai
from google.genai import types
# Initialize the image processor
base_path = "black-forest-labs/FLUX.1-dev"
lora_base_path = "./models"
# System prompt that will be hidden from users but automatically added to their input
SYSTEM_PROMPT = "Ghibli Studio style, Charming hand-drawn anime-style illustration"
# ๋ก๊น
์ค์
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Load the model
pipe = FluxPipeline.from_pretrained(base_path, torch_dtype=torch.bfloat16)
transformer = FluxTransformer2DModel.from_pretrained(base_path, subfolder="transformer", torch_dtype=torch.bfloat16)
pipe.transformer = transformer
pipe.to("cuda")
def clear_cache(transformer):
for name, attn_processor in transformer.attn_processors.items():
attn_processor.bank_kv.clear()
#######################################
# Utility Functions
#######################################
# Simple Timer Class
class timer:
def __init__(self, method_name="timed process"):
self.method = method_name
def __enter__(self):
self.start = time.time()
print(f"[TIMER] {self.method} starts")
def __exit__(self, exc_type, exc_val, exc_tb):
end = time.time()
print(f"[TIMER] {self.method} took {round(end - self.start, 2)}s")
# ๊ฐ๋จํ ๋ฒ์ญ ๊ธฐ๋ฅ (ํ๊ธ -> ์์ด)
def maybe_translate_to_english(text: str) -> str:
"""
ํ
์คํธ์ ํ๊ธ์ด ํฌํจ๋์ด ์์ผ๋ฉด ์์ด๋ก ๋ฒ์ญ, ์๋๋ฉด ๊ทธ๋๋ก ๋ฐํ
"""
if not text or not re.search("[๊ฐ-ํฃ]", text):
return text
try:
# ๊ฐ๋จํ ๋ฒ์ญ ๊ท์น (์ค์ ํ๋ก๋์
์์๋ API ์ฌ์ฉ ๊ถ์ฅ)
translations = {
"์๋
ํ์ธ์": "Hello",
"ํ์ํฉ๋๋ค": "Welcome",
"์๋ฆ๋ค์ด ๋น์ ": "Beautiful You",
"์๋
": "Hello",
"๊ณ ์์ด": "Cat",
"๋ฐฐ๋": "Banner",
"์ฌ๊ธ๋ผ์ค": "Sunglasses",
"์ฐฉ์ฉํ": "wearing",
"ํฐ์": "white"
}
# ์ ์ฒด ๋ฌธ์ฅ์ ๋ํ ๋๋ต์ ์ธ ๋ฒ์ญ
for kr, en in translations.items():
if kr in text:
text = text.replace(kr, en)
print(f"[TRANSLATE] Translated Korean text: '{text}'")
return text
except Exception as e:
print(f"[WARNING] Translation failed: {e}")
return text
def save_binary_file(file_name, data):
with open(file_name, "wb") as f:
f.write(data)
#######################################
# Gemini API Functions
#######################################
def generate_by_google_genai(text, file_name, model="gemini-2.0-flash-exp"):
"""
- ์ถ๊ฐ ์ง์์ฌํญ(AIP)์ ์ ๋ฌํด ์ด๋ฏธ์ง ๊ธฐ๋ฐ ํธ์ง์ ์ํ.
- ์๋ต์ด '์ด๋ฏธ์ง'๋ฉด ์ ์ฅ, 'ํ
์คํธ'๋ฉด ๋์ ํ์ฌ ๋ฐํ.
"""
# API ํค ๊ฐ์ ธ์ค๊ธฐ (ํ๊ฒฝ ๋ณ์ GAPI_TOKEN ์ฌ์ฉ)
api_key = os.getenv("GAPI_TOKEN", None)
if not api_key:
raise ValueError("GAPI_TOKEN is missing. Please set an API key.")
client = genai.Client(api_key=api_key)
files = [client.files.upload(file=file_name)]
contents = [
types.Content(
role="user",
parts=[
types.Part.from_uri(
file_uri=files[0].uri,
mime_type=files[0].mime_type,
),
types.Part.from_text(text=text),
],
),
]
generate_content_config = types.GenerateContentConfig(
temperature=1,
top_p=0.95,
top_k=40,
max_output_tokens=8192,
response_modalities=["image", "text"],
response_mime_type="text/plain",
)
text_response = ""
image_path = None
# ์์ ํ์ผ์ ์ด๋ฏธ์ง ์ ์ฅ ๊ฐ๋ฅํ๋๋ก ์ค๋น
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
temp_path = tmp.name
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
if not chunk.candidates or not chunk.candidates[0].content or not chunk.candidates[0].content.parts:
continue
candidate = chunk.candidates[0].content.parts[0]
# ๋ง์ฝ inline_data(์ด๋ฏธ์ง ๋ฐ์ดํฐ)๊ฐ ์๋ค๋ฉด -> ์ค์ ์ด๋ฏธ์ง ํธ์ง ๊ฒฐ๊ณผ
if candidate.inline_data:
save_binary_file(temp_path, candidate.inline_data.data)
print(f"File of mime type {candidate.inline_data.mime_type} saved to: {temp_path}")
image_path = temp_path
# ์ด๋ฏธ์ง ํ ์ฅ๋ง ํ๋ณดํ๋ฉด ์ค๋จ
break
else:
# inline_data๊ฐ ์์ผ๋ฉด ํ
์คํธ ๋ฐ์ดํฐ์ด๋ฏ๋ก ๋์
text_response += chunk.text + "\n"
del files
return image_path, text_response
def change_text_in_image_two_times(original_image, instruction):
"""
Call the text-modification API twice (Google Gemini), returning 2 final variations.
"""
if original_image is None:
raise gr.Error("์ฒ๋ฆฌํ ์ด๋ฏธ์ง๊ฐ ์์ต๋๋ค. ๋จผ์ ์ด๋ฏธ์ง๋ฅผ ์์ฑํด์ฃผ์ธ์.")
results = []
for version_tag in ["(A)", "(B)"]:
mod_instruction = f"{instruction} {version_tag}"
try:
# ์ด๋ฏธ์ง ์ ์ฅ์ฉ ์์ ํ์ผ ์์ฑ
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
original_path = tmp.name
# PIL ์ด๋ฏธ์ง ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ ์ ์ฅ
print(f"[DEBUG] Saving image of type {type(original_image)} to temporary file")
if isinstance(original_image, Image.Image):
original_image.save(original_path, format="PNG")
print(f"[DEBUG] Saved image to temporary file: {original_path}")
else:
raise gr.Error(f"์์๋ PIL Image๊ฐ ์๋ {type(original_image)} ํ์
์ด ์ ๊ณต๋์์ต๋๋ค.")
print(f"[DEBUG] Google Gemini API์ ๋ณด๋ด๋ ์ง์์ฌํญ: {mod_instruction}")
image_path, text_response = generate_by_google_genai(
text=mod_instruction,
file_name=original_path
)
if image_path:
print(f"[DEBUG] Received image from Gemini API: {image_path}")
try:
with open(image_path, "rb") as f:
image_data = f.read()
new_img = Image.open(io.BytesIO(image_data))
results.append(new_img)
except Exception as img_err:
print(f"[ERROR] Failed to process Gemini image: {img_err}")
results.append(original_image)
else:
# ๋ง์ฝ ์ด๋ฏธ์ง ์๋ต์ด ์๊ณ , ํ
์คํธ๋ง ์จ ๊ฒฝ์ฐ
print(f"[WARNING] ์ด๋ฏธ์ง๊ฐ ๋ฐํ๋์ง ์์์ต๋๋ค. ํ
์คํธ ์๋ต: {text_response}")
results.append(original_image)
except Exception as e:
logging.exception(f"Text modification error: {e}")
# ์ค๋ฅ๊ฐ ๋๋ ์๋ณธ ์ด๋ฏธ์ง๋ผ๋ ๋ฐํ
print(f"[ERROR] ํ
์คํธ ์์ ์ค ์ค๋ฅ ๋ฐ์: {e}")
results.append(original_image)
return results
#######################################
# Image Generation Functions
#######################################
@spaces.GPU()
def single_condition_generate_image(user_prompt, spatial_img, height, width, seed):
# Combine the system prompt with user prompt
full_prompt = f"{SYSTEM_PROMPT}, {user_prompt}" if user_prompt else SYSTEM_PROMPT
# Set the Ghibli LoRA
lora_path = os.path.join(lora_base_path, "Ghibli.safetensors")
set_single_lora(pipe.transformer, lora_path, lora_weights=[1], cond_size=512)
# Process the image
spatial_imgs = [spatial_img] if spatial_img else []
image = pipe(
full_prompt,
height=int(height),
width=int(width),
guidance_scale=3.5,
num_inference_steps=25,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(seed),
subject_images=[],
spatial_images=spatial_imgs,
cond_size=512,
).images[0]
clear_cache(pipe.transformer)
return image
@spaces.GPU()
def text_rendering_generate_image(user_prompt, input_text, text_color, text_size, text_position, spatial_img, height, width, seed):
"""
Generate image with Ghibli style and then send to Gemini API for multilingual text rendering
"""
try:
# Step 1: Generate the base image using FLUX
print(f"[DEBUG] Generating base image with FLUX")
full_prompt = f"{SYSTEM_PROMPT}, {user_prompt}" if user_prompt else SYSTEM_PROMPT
# Set the Ghibli LoRA
lora_path = os.path.join(lora_base_path, "Ghibli.safetensors")
set_single_lora(pipe.transformer, lora_path, lora_weights=[1], cond_size=512)
# Process the image
spatial_imgs = [spatial_img] if spatial_img else []
base_image = pipe(
full_prompt,
height=int(height),
width=int(width),
guidance_scale=3.5,
num_inference_steps=25,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(seed),
subject_images=[],
spatial_images=spatial_imgs,
cond_size=512,
).images[0]
clear_cache(pipe.transformer)
# If no text is provided, return the base image
if not input_text or not input_text.strip():
return [base_image, base_image]
# Step 2: Build the instruction for Gemini API
instruction = f"Add the text '{input_text}' to this image in {text_color} color"
# Add position information
if text_position == "top":
instruction += " at the top of the image"
elif text_position == "bottom":
instruction += " at the bottom of the image"
else: # center
instruction += " at the center of the image"
# Add size information
if text_size <= 40:
instruction += " in small size"
elif text_size <= 120:
instruction += " in medium size"
else:
instruction += " in large size"
instruction += ". Make sure the text is clearly visible and readable."
# Step 3: Call Gemini API to generate two variations
print(f"[DEBUG] Sending to Gemini API with instruction: {instruction}")
return change_text_in_image_two_times(base_image, instruction)
except Exception as e:
logging.exception(f"Text rendering error: {e}")
# Create a dummy image in case of error
dummy_img = Image.new('RGB', (width, height), color=(255, 200, 200))
draw = ImageDraw.Draw(dummy_img)
draw.text((width//2, height//2), f"Error: {str(e)}", fill="black", anchor="mm")
return [dummy_img, dummy_img]
# Load example images
def load_examples():
examples = []
test_img_dir = "./test_imgs"
example_prompts = [
" ",
"saying 'HELLO' in 'speech bubble'",
"background 'alps'"
]
for i, filename in enumerate(["00.jpg", "02.jpg", "03.jpg"]):
img_path = os.path.join(test_img_dir, filename)
if os.path.exists(img_path):
# Use dimensions from original code for each specific example
if filename == "00.jpg":
height, width = 680, 1024
elif filename == "02.jpg":
height, width = 560, 1024
elif filename == "03.jpg":
height, width = 1024, 768
else:
height, width = 768, 768
examples.append([
example_prompts[i % len(example_prompts)], # User prompt (without system prompt)
Image.open(img_path), # Reference image
height, # Height
width, # Width
i + 1 # Seed
])
return examples
# Load examples for text rendering tab
def load_text_examples():
examples = []
test_img_dir = "./test_imgs"
example_data = [
{
"prompt": "cute character with speech bubble",
"text": "Hello World!",
"color": "#ffffff",
"size": 72,
"position": "center",
"filename": "00.jpg",
"height": 680,
"width": 1024,
"seed": 123
},
{
"prompt": "landscape with message",
"text": "์๋
ํ์ธ์!",
"color": "#ffff00",
"size": 100,
"position": "top",
"filename": "03.jpg",
"height": 1024,
"width": 768,
"seed": 456
},
{
"prompt": "character with subtitles",
"text": "ใใใซใกใฏไธ็!",
"color": "#00ffff",
"size": 90,
"position": "bottom",
"filename": "02.jpg",
"height": 560,
"width": 1024,
"seed": 789
}
]
for example in example_data:
img_path = os.path.join(test_img_dir, example["filename"])
if os.path.exists(img_path):
examples.append([
example["prompt"],
example["text"],
example["color"],
example["size"],
example["position"],
Image.open(img_path),
example["height"],
example["width"],
example["seed"]
])
return examples
# Function to check API availability - modified to work directly
def check_api_status():
# Check Gemini API availability
api_key = os.getenv("GAPI_TOKEN")
gemini_available = api_key is not None
if gemini_available:
return """<div class="api-status api-connected">โ Connected to FLUX.1 and Gemini API</div>"""
else:
return """<div class="api-status api-disconnected">โ Gemini API connection issue. Please check GAPI_TOKEN environment variable.</div>"""
# CSS for improved UI
css = """
:root {
--primary-color: #4a6670;
--accent-color: #ff8a65;
--background-color: #f5f5f5;
--card-background: #ffffff;
--text-color: #333333;
--border-radius: 10px;
--shadow: 0 4px 6px rgba(0,0,0,0.1);
}
body {
background-color: var(--background-color);
color: var(--text-color);
font-family: 'Helvetica Neue', Arial, sans-serif;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.gr-header {
background: linear-gradient(135deg, #668796 0%, #4a6670 100%);
padding: 24px;
border-radius: var(--border-radius);
margin-bottom: 24px;
box-shadow: var(--shadow);
text-align: center;
}
.gr-header h1 {
color: white;
font-size: 2.5rem;
margin: 0;
font-weight: 700;
}
.gr-header p {
color: rgba(255, 255, 255, 0.9);
font-size: 1.1rem;
margin-top: 8px;
}
.gr-panel {
background-color: var(--card-background);
border-radius: var(--border-radius);
padding: 16px;
box-shadow: var(--shadow);
}
.gr-button {
background-color: var(--accent-color);
border: none;
color: white;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: transform 0.1s, background-color 0.3s;
}
.gr-button:hover {
background-color: #ff7043;
transform: translateY(-2px);
}
.gr-input, .gr-select {
border-radius: 5px;
border: 1px solid #ddd;
padding: 10px;
width: 100%;
}
.gr-form {
display: grid;
gap: 16px;
}
.gr-box {
background-color: var(--card-background);
border-radius: var(--border-radius);
padding: 20px;
box-shadow: var(--shadow);
margin-bottom: 20px;
}
.gr-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
.gr-gallery-item {
overflow: hidden;
border-radius: var(--border-radius);
box-shadow: var(--shadow);
transition: transform 0.3s;
}
.gr-gallery-item:hover {
transform: scale(1.02);
}
.gr-image {
width: 100%;
height: auto;
object-fit: cover;
}
.gr-footer {
text-align: center;
margin-top: 40px;
padding: 20px;
color: #666;
font-size: 14px;
}
.gr-examples-gallery {
margin-top: 20px;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.gr-header h1 {
font-size: 1.8rem;
}
.gr-panel {
padding: 12px;
}
}
/* Ghibli-inspired accent colors */
.gr-accent-1 {
background-color: #95ccd9;
}
.gr-accent-2 {
background-color: #74ad8c;
}
.gr-accent-3 {
background-color: #f9c06b;
}
.text-rendering-options {
background-color: #f0f8ff;
padding: 16px;
border-radius: var(--border-radius);
margin-top: 16px;
}
.api-status {
font-size: 14px;
color: #666;
text-align: center;
margin-bottom: 10px;
}
.api-connected {
color: green;
}
.api-disconnected {
color: red;
}
"""
# Create the Gradio Blocks interface
with gr.Blocks(css=css) as demo:
gr.HTML("""
<div class="gr-header">
<h1>โจ Ghibli Multilingual Text-Rendering โจ</h1>
<p>Transform your ideas into magical Ghibli-inspired artwork with multilingual text</p>
</div>
""")
# API Status - ์ง์ ํธ์ถํด์ ์ด๊ธฐ ์ํ ์ค์
api_status = gr.Markdown(check_api_status(), visible=True)
with gr.Tabs():
with gr.Tab("Create Ghibli Art"):
with gr.Row():
with gr.Column(scale=1):
gr.HTML("""
<div class="gr-box">
<h3>๐จ Your Creative Input</h3>
<p>Describe what you want to see in your Ghibli-inspired image</p>
</div>
""")
user_prompt = gr.Textbox(
label="Your description",
placeholder="Describe what you want to see (e.g., a cat sitting by the window)",
lines=2
)
spatial_img = gr.Image(
label="Reference Image (Optional)",
type="pil",
elem_classes="gr-image-upload"
)
with gr.Group():
with gr.Row():
height = gr.Slider(minimum=256, maximum=1024, step=64, label="Height", value=768)
width = gr.Slider(minimum=256, maximum=1024, step=64, label="Width", value=768)
seed = gr.Slider(minimum=1, maximum=9999, step=1, label="Seed", value=42,
info="Change for different variations")
generate_btn = gr.Button("โจ Generate Ghibli Art", variant="primary", elem_classes=["generate-btn"])
with gr.Column(scale=1):
gr.HTML("""
<div class="gr-box">
<h3>โจ Your Magical Creation</h3>
<p>Your Ghibli-inspired artwork will appear here</p>
</div>
""")
output_image = gr.Image(label="Generated Image", elem_classes="gr-output-image")
gr.HTML("""
<div class="gr-box gr-examples-gallery">
<h3>โจ Inspiration Gallery</h3>
<p>Click on any example to try it out</p>
</div>
""")
# Add examples
examples = load_examples()
gr.Examples(
examples=examples,
inputs=[user_prompt, spatial_img, height, width, seed],
outputs=output_image,
fn=single_condition_generate_image,
cache_examples=False,
examples_per_page=4
)
# Link the button to the function
generate_btn.click(
single_condition_generate_image,
inputs=[user_prompt, spatial_img, height, width, seed],
outputs=output_image
)
# Second tab for Image & Multilingual Text Rendering with Gemini API
with gr.Tab("Image & Multilingual Text Rendering"):
with gr.Row():
with gr.Column(scale=1):
gr.HTML("""
<div class="gr-box">
<h3>๐ Art with Multilingual Text</h3>
<p>Create Ghibli-style images with beautiful text in any language using Gemini AI</p>
</div>
""")
text_user_prompt = gr.Textbox(
label="Image Description",
placeholder="Describe what you want to see (e.g., a character with speech bubble)",
lines=2
)
with gr.Group(elem_classes="text-rendering-options"):
input_text = gr.Textbox(
label="Multilingual Text to Add",
placeholder="Enter text in any language (Korean, Japanese, English, etc.)",
lines=1
)
with gr.Row():
text_color = gr.ColorPicker(
label="Text Color",
value="#FFFFFF"
)
text_size = gr.Slider(
minimum=24,
maximum=200,
step=4,
label="Text Size",
value=72
)
text_position = gr.Radio(
["top", "center", "bottom"],
label="Text Position",
value="center"
)
text_spatial_img = gr.Image(
label="Reference Image (Optional)",
type="pil",
elem_classes="gr-image-upload"
)
with gr.Group():
with gr.Row():
text_height = gr.Slider(minimum=256, maximum=1024, step=64, label="Height", value=768)
text_width = gr.Slider(minimum=256, maximum=1024, step=64, label="Width", value=768)
text_seed = gr.Slider(minimum=1, maximum=9999, step=1, label="Seed", value=42,
info="Change for different variations")
text_generate_btn = gr.Button("โจ Generate Art with Multilingual Text", variant="primary", elem_classes=["generate-btn"])
with gr.Column(scale=1):
gr.HTML("""
<div class="gr-box">
<h3>โจ Your Text Creations (Two Variations)</h3>
<p>Two versions of your Ghibli-inspired artwork with text will appear here</p>
</div>
""")
with gr.Row():
text_output_image1 = gr.Image(
label="Variation A",
type="pil",
elem_classes="gr-output-image"
)
text_output_image2 = gr.Image(
label="Variation B",
type="pil",
elem_classes="gr-output-image"
)
gr.HTML("""
<div class="gr-box gr-examples-gallery">
<h3>โจ Multilingual Text Examples</h3>
<p>Click on any example to try it out</p>
</div>
""")
# Add text rendering examples
text_examples = load_text_examples()
gr.Examples(
examples=text_examples,
inputs=[text_user_prompt, input_text, text_color, text_size, text_position,
text_spatial_img, text_height, text_width, text_seed],
outputs=[text_output_image1, text_output_image2],
fn=text_rendering_generate_image,
cache_examples=False,
examples_per_page=3
)
# Link the text render button to the function
text_generate_btn.click(
text_rendering_generate_image,
inputs=[text_user_prompt, input_text, text_color, text_size, text_position,
text_spatial_img, text_height, text_width, text_seed],
outputs=[text_output_image1, text_output_image2]
)
gr.HTML("""
<div class="gr-footer">
<p>Powered by FLUX.1, Ghibli LoRA, and Google Gemini API โข Created with โค๏ธ</p>
</div>
""")
# Launch the Gradio app
demo.queue().launch() |