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()