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']} &gt; {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()