File size: 27,010 Bytes
395173a 42d38fe f9fa24e 42d38fe 649e6f6 c69cb94 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe 395173a f9fa24e c69cb94 f9fa24e 42d38fe 649e6f6 42d38fe 395173a f9fa24e 42d38fe c69cb94 42d38fe c69cb94 42d38fe c69cb94 42d38fe c69cb94 42d38fe 395173a 42d38fe 395173a 42d38fe 395173a 42d38fe 395173a 42d38fe 395173a 42d38fe f9fa24e 42d38fe 395173a f9fa24e 42d38fe 395173a 42d38fe 395173a 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe 7b03e26 42d38fe 7b03e26 42d38fe f9fa24e c69cb94 f9fa24e c69cb94 f9fa24e c9d177d 42d38fe f9fa24e 649e6f6 f9fa24e 42d38fe 649e6f6 42d38fe 649e6f6 42d38fe |
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 |
import os
import tempfile
import json
from PIL import Image
import gradio as gr
import logging
import re
import time
# ν¨ν€μ§ μν¬νΈ λ°©μμ λ³κ²½
import google.generativeai as genai
from dotenv import load_dotenv
load_dotenv()
# Logging setup
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Gemini API ν€ μ€μ
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
else:
logger.warning("GEMINI_API_KEYκ° μ€μ λμ§ μμμ΅λλ€.")
# λ°°κ²½ 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}")
# κΈ°λ³Έ λ°°κ²½ λ°μ΄ν°
SIMPLE_BACKGROUNDS = {"νμ΄νΈ λ°°κ²½": "white background", "λΈλ λ°°κ²½": "black background", "κ·ΈλΌλ°μ΄μ
λ°°κ²½": "gradient background"}
STUDIO_BACKGROUNDS = {"μ ν μ¬μ§ μ€νλμ€": "product photography studio", "λ―Έλλ© μ€νλμ€": "minimal studio"}
NATURE_BACKGROUNDS = {"μ΄λ ν΄λ³": "tropical beach", "μ²μ": "forest", "μ°μ
μ§λ": "mountain landscape"}
INDOOR_BACKGROUNDS = {"λͺ¨λ 리λΉλ£Έ": "modern living room", "μΈλ ¨λ μ¬λ¬΄μ€": "elegant office", "λμ
리 νΈν
": "luxury hotel"}
ABSTRACT_BACKGROUNDS = {"λ€μ¨ μ‘°λͺ
": "neon lights", "μΆμμ κ·ΈλΌλ°μ΄μ
": "abstract gradient", "μ°μ£Ό λ°°κ²½": "space background"}
# JSON νμΌ λ‘λ ν¨μ
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 FileNotFoundError:
logger.warning(f"κ²½κ³ : {filename} νμΌμ μ°Ύμ μ μμ΅λλ€. κΈ°λ³Έκ°μ μ¬μ©ν©λλ€.")
# κΈ°λ³Έκ° μμ± - νμΌμ΄ μλ κ²½μ° μμ±
try:
with open(file_path, 'w', encoding='utf-8') as f:
if "simple" in filename:
json.dump(SIMPLE_BACKGROUNDS, f, ensure_ascii=False, indent=2)
elif "studio" in filename:
json.dump(STUDIO_BACKGROUNDS, f, ensure_ascii=False, indent=2)
elif "nature" in filename:
json.dump(NATURE_BACKGROUNDS, f, ensure_ascii=False, indent=2)
elif "indoor" in filename:
json.dump(INDOOR_BACKGROUNDS, f, ensure_ascii=False, indent=2)
elif "abstract" in filename:
json.dump(ABSTRACT_BACKGROUNDS, f, ensure_ascii=False, indent=2)
logger.info(f"{filename} νμΌμ κΈ°λ³Έκ°μΌλ‘ μμ±νμ΅λλ€.")
except Exception as e:
logger.error(f"νμΌ μμ± μ€ μ€λ₯: {str(e)}")
# κΈ°λ³Έκ° λ°ν
if "simple" in filename:
return SIMPLE_BACKGROUNDS
elif "studio" in filename:
return STUDIO_BACKGROUNDS
elif "nature" in filename:
return NATURE_BACKGROUNDS
elif "indoor" in filename:
return INDOOR_BACKGROUNDS
elif "abstract" in filename:
return ABSTRACT_BACKGROUNDS
return {}
except json.JSONDecodeError:
logger.warning(f"κ²½κ³ : {filename} νμΌμ JSON νμμ΄ μ¬λ°λ₯΄μ§ μμ΅λλ€. κΈ°λ³Έκ°μ μ¬μ©ν©λλ€.")
return {}
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")
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:
if not GEMINI_API_KEY:
logger.error("Gemini API ν€κ° μ€μ λμ§ μμμ΅λλ€.")
prompt = prompt.replace("IMAGE_TAG_ONE", "#1")
return prompt
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}")
# μλ‘μ΄ API μ¬μ© λ°©μ
response = genai.generate_text(
model="gemini-2.0-flash",
prompt=translation_prompt,
temperature=0.2,
top_p=0.95,
top_k=40,
max_output_tokens=512
)
translated_text = response.result
if translated_text and 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:
if not GEMINI_API_KEY:
return None, "API ν€κ° μ€μ λμ§ μμμ΅λλ€. νκ²½λ³μλ₯Ό νμΈν΄μ£ΌμΈμ."
client = genai.Client(api_key=GEMINI_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
)
)
# μμ νμΌμ νμ JPG νμ₯μλ‘ μμ±
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") # JPGλ ν¬λͺ
λλ₯Ό μ§μνμ§ μμΌλ―λ‘ RGBλ‘ λ³ν
# λ³νλ μ΄λ―Έμ§λ₯Ό JPGλ‘ μ μ₯
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
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=""):
if not GEMINI_API_KEY:
return "Gemini API ν€κ° μ€μ λμ§ μμμ΅λλ€. νκ²½ λ³μ GEMINI_API_KEYλ₯Ό μ€μ νκ±°λ μ½λμ μ§μ μ
λ ₯νμΈμ."
try:
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"λ₯Ό μΆκ°ν΄μ£ΌμΈμ.
νκ΅μ΄ μ
λ ₯ λ΄μ©μ μμ΄λ‘ μ μ ν λ²μνμ¬ λ°μν΄μ£ΌμΈμ.
"""
# google-generativeai ν¨ν€μ§ μ¬μ© λ°©μμΌλ‘ λ³κ²½
system_instruction = generate_system_instruction()
# GenerativeModel λμ genai.chat μ¬μ©
chat = genai.chat(
model="gemini-2.0-flash",
messages=[
{"role": "system", "content": system_instruction},
{"role": "user", "content": prompt_request}
],
generation_config={
"temperature": 0.7,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 1024,
}
)
response_text = chat.last.text.strip()
if "--ar 1:1" not in response_text:
response_text = response_text.rstrip(".") + ". --ar 1:1 --s 750 --q 2"
# λ―Έλμ λ νλΌλ―Έν° μ κ±° (Gemini APIμλ λ¬λ¦¬ λΆνμνλ―λ‘)
response_text = response_text.replace(" --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 create_prompt(image, bg_type, simple, studio, nature, indoor, abstract, product_text, additional_text):
if image is None:
return "μ΄λ―Έμ§λ₯Ό μ
λ‘λν΄μ£ΌμΈμ."
product_text = product_text.strip() or "μ ν"
# λ°°κ²½ μ 보 κ°μ Έμ€κΈ°
background_info = get_selected_background_info(bg_type, simple, studio, nature, indoor, abstract)
try:
prompt = generate_prompt_with_gemini(product_text, background_info, additional_text)
return prompt
except Exception as e:
error_msg = f"ν둬ννΈ μμ± μ€ μ€λ₯ λ°μ: {str(e)}"
return error_msg
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
# μ΄λ―Έμ§ μ
λ‘λ μΉμ
gr.Markdown("## μ΄λ―Έμ§ μ
λ‘λ")
with gr.Row():
image1_input = gr.Image(type="pil", label="μ΄λ―Έμ§ μ
λ‘λ", image_mode="RGB")
# μ νλͺ
μ
λ ₯ μΉμ
gr.Markdown("## μ ν μ 보")
product_name = gr.Textbox(label="μ νλͺ
(νκ΅μ΄ μ
λ ₯)", placeholder="μ: μ€ν¨μΌμ΄ νλΈ, ν
λΈλ¬ λ±")
# λ°°κ²½ μ ν μΉμ
gr.Markdown("## λ°°κ²½ μ€μ ")
background_type = gr.Radio(
choices=["μ¬ν λ°°κ²½", "μ€νλμ€ λ°°κ²½", "μμ° νκ²½", "μ€λ΄ νκ²½", "μΆμ/νΉμ λ°°κ²½"],
label="λ°°κ²½ μ ν",
value="μ¬ν λ°°κ²½"
)
# κ° λ°°κ²½ μ νμ λ§λ λλ‘λ€μ΄ μ»΄ν¬λνΈλ€
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=2
)
# ν둬ννΈ μ
λ ₯ & μμ± μΉμ
gr.Markdown("## ν둬ννΈ μ€μ ")
generate_prompt_btn = gr.Button("ν둬ννΈ μμ±")
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():
gr.Markdown("## μμ±λ μ΄λ―Έμ§")
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)
# λ°°κ²½ μ νμ λ°λΌ λλ‘λ€μ΄ νμ μ
λ°μ΄νΈ
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]
)
# ν둬ννΈ μμ± λ²νΌ ν΄λ¦ μ΄λ²€νΈ
generate_prompt_btn.click(
fn=create_prompt,
inputs=[
image1_input,
background_type,
simple_dropdown,
studio_dropdown,
nature_dropdown,
indoor_dropdown,
abstract_dropdown,
product_name,
additional_info
],
outputs=[prompt_input]
)
# λ¨μΌ μ΄λ―Έμ§ μμ± λ²νΌ μ΄λ²€νΈ μ°κ²°
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],
)
# 4μ₯ μ΄λ―Έμ§ μμ± λ²νΌ μ΄λ²€νΈ μ°κ²°
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],
)
demo.queue()
demo.launch() |