File size: 27,217 Bytes
395173a 42d38fe fd41e09 ad645a2 f9d2a46 ad645a2 42d38fe 649e6f6 42d38fe 649e6f6 ad645a2 42d38fe 395173a ad645a2 7bb926b fd41e09 f9d2a46 ad645a2 f9d2a46 7bb926b f9d2a46 7bb926b f9d2a46 ad645a2 f9d2a46 ad645a2 f9d2a46 ad645a2 f9d2a46 395173a f9d2a46 395173a ad645a2 42d38fe ad645a2 42d38fe ad645a2 42d38fe f9d2a46 42d38fe f9d2a46 ad645a2 f9d2a46 ad645a2 f9d2a46 42d38fe f9d2a46 42d38fe f9d2a46 42d38fe ad645a2 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe ad645a2 42d38fe ad645a2 f9d2a46 ad645a2 f9d2a46 ad645a2 |
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 |
import os
import tempfile
import logging
import re
import time
import json
from PIL import Image
import gradio as gr
from google import genai
from google.genai import types
import google.generativeai as genai_generative
from dotenv import load_dotenv
load_dotenv()
# ------------------- λ‘κΉ
μ€μ -------------------
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# ------------------- κΈ°λ³Έ μ΄λ―Έμ§ μμ± κ΄λ ¨ ν¨μ (κΈ°λ³Έμ½λ) -------------------
def save_binary_file(file_name, data):
with open(file_name, "wb") as f:
f.write(data)
def translate_prompt_to_english(prompt):
if not re.search("[κ°-ν£]", prompt):
return prompt
prompt = prompt.replace("#1", "IMAGE_TAG_ONE")
try:
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
logger.error("Gemini API ν€κ° μ€μ λμ§ μμμ΅λλ€.")
prompt = prompt.replace("IMAGE_TAG_ONE", "#1")
return prompt
client = genai.Client(api_key=api_key)
translation_prompt = f"""
Translate the following Korean text to English:
{prompt}
IMPORTANT: The token IMAGE_TAG_ONE is a special tag
and must be preserved exactly as is in your translation. Do not translate this token.
"""
logger.info(f"Translation prompt: {translation_prompt}")
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=[translation_prompt],
config=types.GenerateContentConfig(
response_modalities=['Text'],
temperature=0.2,
top_p=0.95,
top_k=40,
max_output_tokens=512
)
)
translated_text = ""
for part in response.candidates[0].content.parts:
if hasattr(part, 'text') and part.text:
translated_text += part.text
if translated_text.strip():
translated_text = translated_text.replace("IMAGE_TAG_ONE", "#1")
logger.info(f"Translated text: {translated_text.strip()}")
return translated_text.strip()
else:
logger.warning("λ²μ κ²°κ³Όκ° μμ΅λλ€. μλ³Έ ν둬ννΈ μ¬μ©")
prompt = prompt.replace("IMAGE_TAG_ONE", "#1")
return prompt
except Exception as e:
logger.exception("λ²μ μ€ μ€λ₯ λ°μ:")
prompt = prompt.replace("IMAGE_TAG_ONE", "#1")
return prompt
def preprocess_prompt(prompt, image1):
has_img1 = image1 is not None
if "#1" in prompt and not has_img1:
prompt = prompt.replace("#1", "첫 λ²μ§Έ μ΄λ―Έμ§(μμ)")
else:
prompt = prompt.replace("#1", "첫 λ²μ§Έ μ΄λ―Έμ§")
prompt += " μ΄λ―Έμ§λ₯Ό μμ±ν΄μ£ΌμΈμ. μ΄λ―Έμ§μ ν
μ€νΈλ κΈμλ₯Ό ν¬ν¨νμ§ λ§μΈμ."
return prompt
def generate_with_images(prompt, images, variation_index=0):
try:
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
return None, "API ν€κ° μ€μ λμ§ μμμ΅λλ€. νκ²½λ³μλ₯Ό νμΈν΄μ£ΌμΈμ."
client = genai.Client(api_key=api_key)
logger.info(f"Gemini API μμ² μμ - ν둬ννΈ: {prompt}, λ³ν μΈλ±μ€: {variation_index}")
variation_suffixes = [
" Create this as the first variation. Do not add any text, watermarks, or labels to the image.",
" Create this as the second variation with more vivid colors. Do not add any text, watermarks, or labels to the image.",
" Create this as the third variation with a more creative style. Do not add any text, watermarks, or labels to the image.",
" Create this as the fourth variation with enhanced details. Do not add any text, watermarks, or labels to the image."
]
if variation_index < len(variation_suffixes):
prompt = prompt + variation_suffixes[variation_index]
else:
prompt = prompt + " Do not add any text, watermarks, or labels to the image."
contents = [prompt]
for idx, img in enumerate(images, 1):
if img is not None:
contents.append(img)
logger.info(f"μ΄λ―Έμ§ #{idx} μΆκ°λ¨")
response = client.models.generate_content(
model="gemini-2.0-flash-exp-image-generation",
contents=contents,
config=types.GenerateContentConfig(
response_modalities=['Text', 'Image'],
temperature=1,
top_p=0.95,
top_k=40,
max_output_tokens=8192
)
)
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
temp_path = tmp.name
result_text = ""
image_found = False
for part in response.candidates[0].content.parts:
if hasattr(part, 'text') and part.text:
result_text += part.text
logger.info(f"μλ΅ ν
μ€νΈ: {part.text}")
elif hasattr(part, 'inline_data') and part.inline_data:
save_binary_file(temp_path, part.inline_data.data)
image_found = True
logger.info("μλ΅μμ μ΄λ―Έμ§ μΆμΆ μ±κ³΅")
if not image_found:
return None, f"APIμμ μ΄λ―Έμ§λ₯Ό μμ±νμ§ λͺ»νμ΅λλ€. μλ΅ ν
μ€νΈ: {result_text}"
result_img = Image.open(temp_path)
if result_img.mode == "RGBA":
result_img = result_img.convert("RGB")
result_img.save(temp_path, format="JPEG", quality=95)
return temp_path, f"μ΄λ―Έμ§κ° μ±κ³΅μ μΌλ‘ μμ±λμμ΅λλ€. {result_text}"
except Exception as e:
logger.exception("μ΄λ―Έμ§ μμ± μ€ μ€λ₯ λ°μ:")
return None, f"μ€λ₯ λ°μ: {str(e)}"
def process_images_with_prompt(image1, prompt, variation_index=0, max_retries=3):
retry_count = 0
last_error = None
while retry_count < max_retries:
try:
images = [image1]
valid_images = [img for img in images if img is not None]
if not valid_images:
return None, "μ΄λ―Έμ§λ₯Ό μ
λ‘λν΄μ£ΌμΈμ.", ""
if prompt and prompt.strip():
processed_prompt = preprocess_prompt(prompt, image1)
if re.search("[κ°-ν£]", processed_prompt):
final_prompt = translate_prompt_to_english(processed_prompt)
else:
final_prompt = processed_prompt
else:
final_prompt = "Please creatively transform this image into a more vivid and artistic version. Do not include any text or watermarks in the generated image."
logger.info("Default prompt generated for single image")
result_img, status = generate_with_images(final_prompt, valid_images, variation_index)
if result_img is not None:
return result_img, status, final_prompt
else:
last_error = status
retry_count += 1
logger.warning(f"μ΄λ―Έμ§ μμ± μ€ν¨, μ¬μλ {retry_count}/{max_retries}: {status}")
time.sleep(1)
except Exception as e:
last_error = str(e)
retry_count += 1
logger.exception(f"μ΄λ―Έμ§ μ²λ¦¬ μ€ μ€λ₯ λ°μ, μ¬μλ {retry_count}/{max_retries}:")
time.sleep(1)
return None, f"μ΅λ μ¬μλ νμ({max_retries}ν) μ΄κ³Ό ν μ€ν¨: {last_error}", prompt
def generate_multiple_images(image1, prompt, progress=gr.Progress()):
results = []
statuses = []
prompts = []
num_images = 4
max_retries = 3
progress(0, desc="μ΄λ―Έμ§ μμ± μ€λΉ μ€...")
for i in range(num_images):
progress((i / num_images), desc=f"{i+1}/{num_images} μ΄λ―Έμ§ μμ± μ€...")
result_img, status, final_prompt = process_images_with_prompt(image1, prompt, i, max_retries)
if result_img is not None:
results.append(result_img)
statuses.append(f"μ΄λ―Έμ§ #{i+1}: {status}")
prompts.append(f"μ΄λ―Έμ§ #{i+1}: {final_prompt}")
else:
results.append(None)
statuses.append(f"μ΄λ―Έμ§ #{i+1} μμ± μ€ν¨: {status}")
prompts.append(f"μ΄λ―Έμ§ #{i+1}: {final_prompt}")
time.sleep(1)
progress(1.0, desc="μ΄λ―Έμ§ μμ± μλ£!")
while len(results) < 4:
results.append(None)
combined_status = "\n".join(statuses)
combined_prompts = "\n".join(prompts)
return results[0], results[1], results[2], results[3], combined_status, combined_prompts
# ------------------- μν ν둬ννΈ μμ± κ΄λ ¨ ν¨μ (μ°Έμ‘°μ½λ) -------------------
# λ°°κ²½ JSON νμΌ κ²½λ‘ μ€μ
BACKGROUNDS_DIR = "./background"
if not os.path.exists(BACKGROUNDS_DIR):
os.makedirs(BACKGROUNDS_DIR)
logger.info(f"λ°°κ²½ λλ ν 리λ₯Ό μμ±νμ΅λλ€: {BACKGROUNDS_DIR}")
else:
logger.info(f"λ°°κ²½ λλ ν λ¦¬κ° μ΄λ―Έ μ‘΄μ¬ν©λλ€: {BACKGROUNDS_DIR}")
def load_background_json(filename):
file_path = os.path.join(BACKGROUNDS_DIR, filename)
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
logger.info(f"{filename} νμΌμ μ±κ³΅μ μΌλ‘ λ‘λνμ΅λλ€. {len(data)} νλͺ© ν¬ν¨.")
return data
except Exception as e:
logger.warning(f"{filename} νμΌ λ‘λ μ€ μ€λ₯ λ°μ: {str(e)}. κΈ°λ³Έκ°μ μ¬μ©ν©λλ€.")
return {}
SIMPLE_BACKGROUNDS = load_background_json("simple_backgrounds.json")
STUDIO_BACKGROUNDS = load_background_json("studio_backgrounds.json")
NATURE_BACKGROUNDS = load_background_json("nature_backgrounds.json")
INDOOR_BACKGROUNDS = load_background_json("indoor_backgrounds.json")
ABSTRACT_BACKGROUNDS = load_background_json("abstract_backgrounds.json")
# λ°°κ²½μ΄ λ‘λλμ§ μμ κ²½μ° κΈ°λ³Έκ° μ€μ
if not SIMPLE_BACKGROUNDS:
SIMPLE_BACKGROUNDS = {"νμ΄νΈ λ°°κ²½": "white background"}
if not STUDIO_BACKGROUNDS:
STUDIO_BACKGROUNDS = {"μ ν μ¬μ§ μ€νλμ€": "product photography studio"}
if not NATURE_BACKGROUNDS:
NATURE_BACKGROUNDS = {"μ΄λ ν΄λ³": "tropical beach"}
if not INDOOR_BACKGROUNDS:
INDOOR_BACKGROUNDS = {"λͺ¨λ 리λΉλ£Έ": "modern living room"}
if not ABSTRACT_BACKGROUNDS:
ABSTRACT_BACKGROUNDS = {"λ€μ¨ μ‘°λͺ
": "neon lights"}
def generate_system_instruction():
return """λΉμ μ μν μ΄λ―Έμ§μ λ°°κ²½μ λ³κ²½νκΈ° μν κ³ νμ§ ν둬ννΈλ₯Ό μμ±νλ μ λ¬Έκ°μ
λλ€.
μ¬μ©μκ° μ 곡νλ μνλͺ
, λ°°κ²½ μ ν, μΆκ° μμ²μ¬νμ λ°νμΌλ‘ λ―Έλμ λ(Midjourney)μ μ¬μ©ν μ μλ
μμΈνκ³ μ λ¬Έμ μΈ ν둬ννΈλ₯Ό μμ΄λ‘ μμ±ν΄μ£ΌμΈμ.
λ€μ κ°μ΄λλΌμΈμ λ°λμ λ°λΌμΌ ν©λλ€:
1. μνμ "#1"λ‘ μ§μ νμ¬ μ°Έμ‘°ν©λλ€. (μ: "skincare tube (#1)")
2. *** λ§€μ° μ€μ: μνμ μλ νΉμ±(λμμΈ, μμ, νν, λ‘κ³ , ν¨ν€μ§ λ±)μ μ΄λ€ μν©μμλ μ λ λ³κ²½νμ§ μμ΅λλ€. ***
3. *** μνμ λ³Έμ§μ νΉμ±μ μ μ§νλ, μμ°μ€λ¬μ΄ νκ²½ ν΅ν©μ μν μ‘°λͺ
κ³Ό κ·Έλ¦Όμλ νμ©ν©λλ€: ***
- μν μ체μ μμ, λμμΈ, νν, ν
μ€μ²λ μ λ μμ νμ§ μμ΅λλ€.
- νκ²½κ³Ό μμ°μ€λ½κ² μ΄μΈλ¦¬λ κ·Έλ¦Όμ, μ£Όλ³ μ‘°λͺ
ν¨κ³Όλ νμ©λ©λλ€.
- μνμ λ¬Όλ°©μΈ, μμΆ, κΈ, μκ³Ό κ°μ μΆκ° μμλ 물리μ ν¨κ³Όλ μ μ©νμ§ μμ΅λλ€.
- νκ²½μ μ΄μΈλ¦¬λ μμ°μ€λ¬μ΄ λΉ λ°μ¬, μ£Όλ³ μ‘°λͺ
, κ·Έλ¦Όμλ μ¬μ€μ ν΅ν©κ°μ μν΄ μ μ©ν μ μμ΅λλ€.
4. μ΄λ―Έμ§ λΉμ¨μ μ νν 1:1(μ μ¬κ°ν) νμμΌλ‘ μ§μ ν©λλ€. ν둬ννΈμ "square format", "1:1 ratio" λλ "aspect ratio 1:1"μ λͺ
μμ μΌλ‘ ν¬ν¨ν©λλ€.
5. μνμ λ°λμ μ μ¬κ°ν ꡬλμ μ μ€μμ λ°°μΉλμ΄μΌ ν©λλ€.
6. μνμ μ΄λ―Έμ§μ μ£Όμ μ΄μ μΌλ‘ λΆκ°μν€κ³ , μνμ λΉμ¨μ΄ μ 체 μ΄λ―Έμ§μμ ν¬κ² μ°¨μ§νλλ‘ ν©λλ€.
7. μν μ΄λ―Έμ§ μ»·μμ(#1)μ κΈ°λ³Έ ννμ μμμ μ μ§νλ©΄μ, μ νν νκ²½μ μμ°μ€λ½κ² ν΅ν©λλλ‘ ν©λλ€.
8. κ³ κΈμ€λ¬μ΄ μμ
μ μ΄λ―Έμ§λ₯Ό μν λ€μ νκ²½ μμλ€μ ν¬ν¨νμΈμ:
- μνκ³Ό μ΄μΈλ¦¬λ μ£Όλ³ νκ²½/λ°°κ²½ μμλ₯Ό μΆκ°ν©λλ€. μλ₯Ό λ€μ΄, νμ₯ν μ£Όλ³μ κ½μ΄λ νλΈ, μλ£ μ ν μμ κ³ΌμΌ, μ μμ ν κ·Όμ²μ νλμ μν λ±.
- νκ²½μ μ‘°λͺ
ν¨κ³Ό(λ¦Ό λΌμ΄νΈ, λ°±λΌμ΄νΈ, μννΈλ°μ€ λ±)λ₯Ό μ€λͺ
ν©λλ€.
- μνμ΄ νκ²½μ μμ°μ€λ½κ² μ‘΄μ¬νλ κ²μ²λΌ 보μ΄λλ‘ μ μ ν κ·Έλ¦Όμμ λΉ ννμ ν¬ν¨ν©λλ€.
- μνμ μ©λλ μ₯μ μ κ°μ μ μΌλ‘ μμνλ λ°°κ²½ μμλ₯Ό ν¬ν¨ν©λλ€.
- νλ‘νμ
λν μμ
μ¬μ§ ν¨κ³Ό(μ νμ νΌμ¬κ³ μ¬λ, μννΈ ν¬μ»€μ€, μ€νλμ€ μ‘°λͺ
λ±)λ₯Ό λͺ
μν©λλ€.
9. ν둬ννΈμ λ€μ μμλ€μ λͺ
μμ μΌλ‘ ν¬ν¨νμΈμ:
- "highly detailed commercial photography"
- "award-winning product photography"
- "professional advertising imagery"
- "studio quality"
- "magazine advertisement quality"
10. λ°°κ²½ νκ²½ μμλ₯Ό μν μΉ΄ν
κ³ λ¦¬μ λ§κ² μ νν©λλ€:
- μ€ν¨μΌμ΄ μ ν: κΉ¨λν μμ€ μ λ°, μ°μν νμ₯λ, μ€ν κ°μ νκ²½ λ±
- μλ£ μ ν: μΈλ ¨λ ν
μ΄λΈ, νν° νκ²½, μΌμΈ νΌν¬λ μ₯λ©΄ λ±
- μ μ μ ν: μΈλ ¨λ μμ
곡κ°, νλμ μΈ κ±°μ€, λ―Έλλ©ν μ±
μ λ±
- ν¨μ
/μλ₯: μΈλ ¨λ μΌλ£Έ, λμ 거리, μλ κ°μ€ν λΌμ΄νμ€νμΌ νκ²½ λ±
- μν μ ν: κΉλν μ£Όλ°©, μν, μ리 νκ²½ λ±
11. μ¬μ©μκ° μ 곡ν ꡬ체μ μΈ λ°°κ²½κ³Ό μΆκ° μμ²μ¬νμ μ νν λ°μν©λλ€.
12. ν둬ννΈλ λ―Έλμ λ AIμ μ΅μ νλμ΄μΌ ν©λλ€.
13. ν둬ννΈ λμ "--ar 1:1 --s 750 --q 2" νλΌλ―Έν°λ₯Ό μΆκ°νμ¬ λ―Έλμ λμμ κ³ νμ§ μ μ¬κ°ν λΉμ¨μ κ°μ ν©λλ€.
μΆλ ₯ νμμ μμ΄λ‘ λ λ¨μΌ λ¨λ½μ μμΈν ν둬ννΈμ¬μΌ νλ©°, λμ λ―Έλμ λ νλΌλ―Έν°κ° ν¬ν¨λμ΄μΌ ν©λλ€.
"""
def generate_prompt_with_gemini(product_name, background_info, additional_info=""):
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
if not GEMINI_API_KEY:
return "Gemini API ν€κ° μ€μ λμ§ μμμ΅λλ€. νκ²½ λ³μ GEMINI_API_KEYλ₯Ό μ€μ νκ±°λ μ½λμ μ§μ μ
λ ₯νμΈμ."
try:
genai_generative.configure(api_key=GEMINI_API_KEY)
prompt_request = f"""
μνλͺ
: {product_name}
λ°°κ²½ μ ν: {background_info.get('english', 'studio')}
λ°°κ²½ μΉ΄ν
κ³ λ¦¬: {background_info.get('category', '')}
λ°°κ²½ μ΄λ¦: {background_info.get('name', '')}
μΆκ° μμ²μ¬ν: {additional_info}
μ€μ μꡬμ¬ν:
1. μνμ΄ ν¬κ² λΆκ°λκ³ μ΄λ―Έμ§μμ μ€μ¬μ μΈ μμΉλ₯Ό μ°¨μ§νλλ‘ ν둬ννΈλ₯Ό μμ±ν΄μ£ΌμΈμ.
2. μ΄λ―Έμ§λ μ νν 1:1 λΉμ¨(μ μ¬κ°ν)μ΄μ΄μΌ ν©λλ€.
3. μνμ μ μ¬κ°ν νλ μμ μ μ€μμ μμΉν΄μΌ ν©λλ€.
4. μνμ λμμΈ, μμ, νν, λ‘κ³ λ± λ³Έμ§μ νΉμ±μ μ λ μμ νμ§ λ§μΈμ.
5. νκ²½κ³Όμ μμ°μ€λ¬μ΄ ν΅ν©μ μν μ‘°λͺ
ν¨κ³Όμ κ·Έλ¦Όμλ ν¬ν¨ν΄μ£ΌμΈμ.
6. μνμ λ λ보μ΄κ² νλ λ°°κ²½ νκ²½μ μ€λͺ
ν΄μ£ΌμΈμ.
7. κ³ κΈμ€λ¬μ΄ μμ
κ΄κ³ νμ§μ μ΄λ―Έμ§κ° λλλ‘ νκ²½ μ€λͺ
μ ν΄μ£ΌμΈμ.
8. ν둬ννΈ λμ λ―Έλμ λ νλΌλ―Έν° "--ar 1:1 --s 750 --q 2"λ₯Ό μΆκ°ν΄μ£ΌμΈμ.
νκ΅μ΄ μ
λ ₯ λ΄μ©μ μμ΄λ‘ μ μ ν λ²μνμ¬ λ°μν΄μ£ΌμΈμ.
"""
model = genai_generative.GenerativeModel(
'gemini-2.0-flash',
system_instruction=generate_system_instruction()
)
response = model.generate_content(
prompt_request,
generation_config=genai_generative.types.GenerationConfig(
temperature=0.7,
top_p=0.95,
top_k=64,
max_output_tokens=1024,
)
)
response_text = response.text.strip()
if "--ar 1:1" not in response_text:
response_text = response_text.rstrip(".") + ". --ar 1:1 --s 750 --q 2"
return response_text
except Exception as e:
return f"ν둬ννΈ μμ± μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
def get_selected_background_info(bg_type, simple, studio, nature, indoor, abstract):
if bg_type == "μ¬ν λ°°κ²½":
return {
"category": "μ¬ν λ°°κ²½",
"name": simple,
"english": SIMPLE_BACKGROUNDS.get(simple, "white background")
}
elif bg_type == "μ€νλμ€ λ°°κ²½":
return {
"category": "μ€νλμ€ λ°°κ²½",
"name": studio,
"english": STUDIO_BACKGROUNDS.get(studio, "product photography studio")
}
elif bg_type == "μμ° νκ²½":
return {
"category": "μμ° νκ²½",
"name": nature,
"english": NATURE_BACKGROUNDS.get(nature, "natural environment")
}
elif bg_type == "μ€λ΄ νκ²½":
return {
"category": "μ€λ΄ νκ²½",
"name": indoor,
"english": INDOOR_BACKGROUNDS.get(indoor, "indoor environment")
}
elif bg_type == "μΆμ/νΉμ λ°°κ²½":
return {
"category": "μΆμ/νΉμ λ°°κ²½",
"name": abstract,
"english": ABSTRACT_BACKGROUNDS.get(abstract, "abstract background")
}
else:
return {
"category": "κΈ°λ³Έ λ°°κ²½",
"name": "νμ΄νΈ λ°°κ²½",
"english": "white background"
}
def generate_product_prompt_output(image, bg_type, simple, studio, nature, indoor, abstract, product_name, additional_info):
if image is None:
gr.Warning("μ΄λ―Έμ§λ₯Ό μ
λ‘λν΄μ£ΌμΈμ.")
return "μ΄λ―Έμ§λ₯Ό μ
λ‘λν΄μ£ΌμΈμ.", None, "μ΄λ―Έμ§λ₯Ό μ
λ‘λ ν ν둬ννΈλ₯Ό μμ±ν΄μ£ΌμΈμ."
product_name = product_name.strip() or "μ ν"
background_info = get_selected_background_info(bg_type, simple, studio, nature, indoor, abstract)
try:
prompt = generate_prompt_with_gemini(product_name, background_info, additional_info)
if "Gemini API ν€κ° μ€μ λμ§ μμμ΅λλ€" in prompt:
gr.Warning("Gemini API ν€κ° μ€μ λμ§ μμμ΅λλ€. ν€λ₯Ό λ°κΈλ°μ μ€μ ν΄μ£ΌμΈμ.")
prompt = """
[Gemini API ν€ λλ½]
API ν€ μ€μ λ°©λ²:
1. νκ²½ λ³μ: export GEMINI_API_KEY="your-api-key"
2. μ½λ λ΄ μ§μ μ
λ ₯: GEMINI_API_KEY = "your-api-key"
ν€ λ°κΈ: https://makersuite.google.com/
"""
return prompt, image, "API ν€λ₯Ό μ€μ ν΄μΌ ν©λλ€."
preview = f"""
<div style="padding:10px; border:1px solid #ddd; border-radius:8px; margin-top:10px;">
<h3>ν둬ννΈ μμ½</h3>
<p><strong>μ΄ κΈΈμ΄:</strong> {len(prompt)} κΈμ</p>
<p><strong>λ°°κ²½:</strong> {background_info['category']} > {background_info['name']}</p>
<p><strong>λ―Έλμ λ νλΌλ―Έν°:</strong> {" ".join([param for param in ["--ar 1:1", "--s 750", "--q 2"] if param in prompt])}</p>
</div>
"""
return prompt, image, preview
except Exception as e:
error_msg = f"ν둬ννΈ μμ± μ€ μ€λ₯ λ°μ: {str(e)}"
gr.Error(error_msg)
return error_msg, image, "μ€λ₯κ° λ°μνμ΅λλ€."
# ------------------- Gradio μΈν°νμ΄μ€ κ΅¬μ± -------------------
def create_basic_app():
with gr.Blocks() as basic_app:
with gr.Column():
with gr.Group():
with gr.Column():
with gr.Row():
image1_input = gr.Image(type="pil", label="μ΄λ―Έμ§ μ
λ‘λ", image_mode="RGB")
prompt_input = gr.Textbox(
lines=3,
placeholder="ν둬ννΈλ₯Ό μ
λ ₯νμΈμ. '#1'μΌλ‘ μ
λ‘λν μ΄λ―Έμ§λ₯Ό μ°Έμ‘°ν μ μμ΅λλ€.",
label="ν둬ννΈ μ
λ ₯"
)
with gr.Row():
submit_single_btn = gr.Button('μ΄λ―Έμ§ μμ± (1μ₯)')
submit_btn = gr.Button('μ΄λ―Έμ§ μμ± (4μ₯)')
with gr.Column():
with gr.Row():
with gr.Column():
output_image1 = gr.Image(label="μ΄λ―Έμ§ #1", type="filepath")
output_image3 = gr.Image(label="μ΄λ―Έμ§ #3", type="filepath")
with gr.Column():
output_image2 = gr.Image(label="μ΄λ―Έμ§ #2", type="filepath")
output_image4 = gr.Image(label="μ΄λ―Έμ§ #4", type="filepath")
output_text = gr.Textbox(label="κ²°κ³Ό μ 보", lines=2)
prompt_display = gr.Textbox(label="μ¬μ©λ ν둬ννΈ (μμ΄)", lines=2)
submit_single_btn.click(
fn=lambda image1, prompt: process_images_with_prompt(image1, prompt, 0),
inputs=[image1_input, prompt_input],
outputs=[output_image1, output_text, prompt_display],
)
submit_btn.click(
fn=generate_multiple_images,
inputs=[image1_input, prompt_input],
outputs=[output_image1, output_image2, output_image3, output_image4, output_text, prompt_display],
)
return basic_app
def create_product_prompt_app():
with gr.Blocks(title="κ³ κΈ μν μ΄λ―Έμ§ λ°°κ²½ ν둬ννΈ μμ±κΈ°") as product_app:
gr.Markdown("# κ³ κΈ μν μ΄λ―Έμ§ λ°°κ²½ ν둬ννΈ μμ±κΈ°")
gr.Markdown("μν μ΄λ―Έμ§λ₯Ό μ
λ‘λνκ³ μ΅μ
μ μ ννλ©΄ κ³ νμ§ μμ
μ© ν둬ννΈκ° μμ±λ©λλ€.")
with gr.Row():
product_name = gr.Textbox(label="μνλͺ
(νκ΅μ΄ μ
λ ₯)", placeholder="μ: μ€ν¨μΌμ΄ νλΈ, ν
λΈλ¬ λ±", interactive=True)
background_type = gr.Radio(
choices=["μ¬ν λ°°κ²½", "μ€νλμ€ λ°°κ²½", "μμ° νκ²½", "μ€λ΄ νκ²½", "μΆμ/νΉμ λ°°κ²½"],
label="λ°°κ²½ μ ν",
value="μ¬ν λ°°κ²½"
)
with gr.Row():
with gr.Column(scale=1):
image_input = gr.Image(label="μν μ΄λ―Έμ§ μ
λ‘λ", type="pil")
simple_dropdown = gr.Dropdown(
choices=list(SIMPLE_BACKGROUNDS.keys()),
value=list(SIMPLE_BACKGROUNDS.keys())[0] if SIMPLE_BACKGROUNDS else None,
label="μ¬ν λ°°κ²½ μ ν",
visible=True,
interactive=True
)
studio_dropdown = gr.Dropdown(
choices=list(STUDIO_BACKGROUNDS.keys()),
value=list(STUDIO_BACKGROUNDS.keys())[0] if STUDIO_BACKGROUNDS else None,
label="μ€νλμ€ λ°°κ²½ μ ν",
visible=False,
interactive=True
)
nature_dropdown = gr.Dropdown(
choices=list(NATURE_BACKGROUNDS.keys()),
value=list(NATURE_BACKGROUNDS.keys())[0] if NATURE_BACKGROUNDS else None,
label="μμ° νκ²½ μ ν",
visible=False,
interactive=True
)
indoor_dropdown = gr.Dropdown(
choices=list(INDOOR_BACKGROUNDS.keys()),
value=list(INDOOR_BACKGROUNDS.keys())[0] if INDOOR_BACKGROUNDS else None,
label="μ€λ΄ νκ²½ μ ν",
visible=False,
interactive=True
)
abstract_dropdown = gr.Dropdown(
choices=list(ABSTRACT_BACKGROUNDS.keys()),
value=list(ABSTRACT_BACKGROUNDS.keys())[0] if ABSTRACT_BACKGROUNDS else None,
label="μΆμ/νΉμ λ°°κ²½ μ ν",
visible=False,
interactive=True
)
additional_info = gr.Textbox(
label="μΆκ° μμ²μ¬ν (μ νμ¬ν)",
placeholder="μ: κ³ κΈμ€λ¬μ΄ λλ, λ°μ μ‘°λͺ
, μμ°μ€λ¬μ΄ 보쑰μ μΈ κ°μ²΄λ₯Ό μΆκ°ν΄μ£ΌμΈμ λ±",
lines=3,
interactive=True
)
submit_btn = gr.Button("ν둬ννΈ μμ±", variant="primary")
with gr.Column(scale=1):
prompt_output = gr.Textbox(label="μμ±λ ν둬ννΈ", lines=10)
image_preview = gr.Image(label="μ
λ‘λλ μ΄λ―Έμ§ (#1)", type="pil")
preview_html = gr.HTML("ν둬ννΈ μμ± μ μ¬κΈ°μ λ―Έλ¦¬λ³΄κΈ°κ° νμλ©λλ€.")
def update_dropdowns(bg_type):
return {
simple_dropdown: gr.update(visible=(bg_type == "μ¬ν λ°°κ²½")),
studio_dropdown: gr.update(visible=(bg_type == "μ€νλμ€ λ°°κ²½")),
nature_dropdown: gr.update(visible=(bg_type == "μμ° νκ²½")),
indoor_dropdown: gr.update(visible=(bg_type == "μ€λ΄ νκ²½")),
abstract_dropdown: gr.update(visible=(bg_type == "μΆμ/νΉμ λ°°κ²½"))
}
background_type.change(
fn=update_dropdowns,
inputs=[background_type],
outputs=[simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, abstract_dropdown]
)
def generate_output(image, bg_type, simple, studio, nature, indoor, abstract, product_name, additional_text):
return generate_product_prompt_output(image, bg_type, simple, studio, nature, indoor, abstract, product_name, additional_text)
submit_btn.click(
fn=generate_output,
inputs=[
image_input,
background_type,
simple_dropdown,
studio_dropdown,
nature_dropdown,
indoor_dropdown,
abstract_dropdown,
product_name,
additional_info
],
outputs=[
prompt_output,
image_preview,
preview_html
]
)
return product_app
def main():
basic_app = create_basic_app()
product_app = create_product_prompt_app()
with gr.Blocks() as demo:
gr.Markdown("# ν΅ν© μ΄λ―Έμ§ μμ± λ° ν둬ννΈ μμ± μ±")
with gr.Tabs():
with gr.TabItem("μΌλ° μ΄λ―Έμ§ μμ±"):
basic_app.render()
with gr.TabItem("μν ν둬ννΈ μμ± λ° μ΄λ―Έμ§ μμ±"):
product_app.render()
demo.queue()
demo.launch()
if __name__ == "__main__":
main()
|