File size: 16,827 Bytes
8d852cf
 
 
 
 
 
 
9a736d4
8d852cf
ddcfe75
 
8d852cf
e0e8bcb
 
 
 
 
8d852cf
 
 
 
ddcfe75
8d852cf
e0e8bcb
8d852cf
 
e0e8bcb
8d852cf
ddcfe75
0ae66bb
ddd42e5
0ae66bb
1e9bbd5
8d852cf
e0e8bcb
 
 
 
 
 
 
8d852cf
 
e0e8bcb
8d852cf
0ae66bb
 
 
1e9bbd5
0ae66bb
 
 
 
654ca6d
0ae66bb
fd7e6af
0ae66bb
fd7e6af
9a736d4
1e9bbd5
 
8d852cf
 
 
 
 
fd7e6af
8d852cf
e0e8bcb
8d852cf
 
 
e0e8bcb
8d852cf
9a736d4
fd7e6af
8d852cf
fd7e6af
 
 
9a736d4
fd7e6af
 
8d852cf
 
1e9bbd5
fd7e6af
1e9bbd5
811d552
1e9bbd5
811d552
 
fd7e6af
 
 
 
9a736d4
fd7e6af
 
 
9a736d4
fd7e6af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e9bbd5
 
 
0ae66bb
1e9bbd5
 
811d552
8d852cf
 
e0e8bcb
fd7e6af
ddcfe75
8d852cf
ddd42e5
 
 
 
993c58c
ddd42e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
811d552
ddd42e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
993c58c
ddd42e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
811d552
 
1e9bbd5
fd7e6af
 
 
 
ddd42e5
 
 
 
 
 
 
 
 
fd7e6af
1e9bbd5
fd7e6af
 
8d852cf
ddd42e5
 
ddcfe75
8d852cf
ddd42e5
 
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
import json
import os
import time
import tempfile
from PIL import Image
import gradio as gr
import logging
import io

from google import genai
from google.genai import types

# .env ํŒŒ์ผ์— ์ €์žฅ๋œ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๋กœ๋“œ (python-dotenv ์„ค์น˜ ํ•„์š”: pip install python-dotenv)
from dotenv import load_dotenv
load_dotenv()

# ๋กœ๊น… ์„ค์ • (๋กœ๊ทธ ๋ ˆ๋ฒจ: DEBUG)
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def save_binary_file(file_name, data):
    logger.debug(f"ํŒŒ์ผ์— ์ด์ง„ ๋ฐ์ดํ„ฐ ์ €์žฅ ์ค‘: {file_name}")
    with open(file_name, "wb") as f:
        f.write(data)
    logger.debug(f"ํŒŒ์ผ ์ €์žฅ ์™„๋ฃŒ: {file_name}")


def generate_image_from_prompt(prompt, model="gemini-2.0-flash-exp-image-generation"):
    """ํ…์ŠคํŠธ ํ”„๋กฌํ”„ํŠธ๋งŒ์œผ๋กœ ์ด๋ฏธ์ง€ ์ƒ์„ฑ"""
    logger.debug(f"generate_image_from_prompt ํ•จ์ˆ˜ ์‹œ์ž‘ - ํ”„๋กฌํ”„ํŠธ: '{prompt}'")
    
    try:
        # API ํ‚ค๋Š” ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋ถˆ๋Ÿฌ์˜ด
        effective_api_key = os.environ.get("GEMINI_API_KEY")
        if effective_api_key:
            logger.debug("ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ API ํ‚ค ๋ถˆ๋Ÿฌ์˜ด")
        else:
            logger.error("API ํ‚ค๊ฐ€ ํ™˜๊ฒฝ๋ณ€์ˆ˜์— ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
            raise ValueError("API ํ‚ค๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")

        client = genai.Client(api_key=effective_api_key)
        logger.debug("Gemini ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ.")

        # ํ”„๋กฌํ”„ํŠธ ์ฒ˜๋ฆฌ
        if not prompt or not prompt.strip():
            prompt = "A creative and visually appealing image that captures imagination. Use vibrant colors and interesting composition."
        
        # ํ•œ๊ตญ์–ด ํ”„๋กฌํ”„ํŠธ์— ์˜์–ด ์„ค๋ช… ์ถ”๊ฐ€
        if not any(ord(c) < 128 for c in prompt):
            prompt += " Create a highly detailed, visually stunning image that captures the essence of the description."

        # ์ปจํ…์ธ  ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
        parts = [
            types.Part.from_text(text=prompt)
        ]
        
        logger.debug(f"์ปจํ…์ธ  ๊ฐ์ฒด ์ƒ์„ฑ ์™„๋ฃŒ: {len(parts)} ์•„์ดํ…œ")

        # ์ƒ์„ฑ ์„ค์ •
        generate_content_config = types.GenerateContentConfig(
            temperature=1,
            top_p=0.95,
            top_k=40,
            max_output_tokens=8192,
            response_modalities=["image", "text"],
        )
        logger.debug(f"์ƒ์„ฑ ์„ค์ •: {generate_content_config}")

        with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
            temp_path = tmp.name
            logger.debug(f"์ž„์‹œ ํŒŒ์ผ ์ƒ์„ฑ๋จ: {temp_path}")

            # ์ŠคํŠธ๋ฆฌ๋ฐ ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ ์ˆ˜์‹ 
            response_stream = client.models.generate_content_stream(
                model=model,
                contents=[
                    types.Content(
                        role="user",
                        parts=parts,
                    ),
                ],
                config=generate_content_config,
            )
            
            logger.debug("์‘๋‹ต ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ ์‹œ์ž‘...")
            
            # ์‘๋‹ต์—์„œ ์ด๋ฏธ์ง€์™€ ํ…์ŠคํŠธ ์ถ”์ถœ
            image_saved = False
            response_text = ""
            
            for chunk in response_stream:
                logger.debug(f"chunk ์ˆ˜์‹ : {chunk}")
                
                # ์‘๋‹ต ๊ฒ€์ฆ
                if not hasattr(chunk, 'candidates') or not chunk.candidates or len(chunk.candidates) == 0:
                    logger.warning("chunk์— candidates๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.")
                    continue
                    
                if not hasattr(chunk.candidates[0], 'content') or chunk.candidates[0].content is None:
                    logger.warning("chunk.candidates[0]์— content๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.")
                    continue
                    
                if not hasattr(chunk.candidates[0].content, 'parts') or not chunk.candidates[0].content.parts:
                    logger.warning("chunk.candidates[0].content์— parts๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.")
                    continue
                
                for part in chunk.candidates[0].content.parts:
                    if hasattr(part, 'text') and part.text:
                        response_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)
                        logger.info(f"MIME ํƒ€์ž… {part.inline_data.mime_type}์˜ ํŒŒ์ผ์ด ์ €์žฅ๋จ: {temp_path}")
                        image_saved = True

            if not image_saved:
                logger.warning("์ด๋ฏธ์ง€๊ฐ€ ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
                return None, response_text or "์ด๋ฏธ์ง€๊ฐ€ ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ํ”„๋กฌํ”„ํŠธ๋กœ ์‹œ๋„ํ•ด๋ณด์„ธ์š”."

        logger.debug("์ด๋ฏธ์ง€ ์ƒ์„ฑ ์™„๋ฃŒ.")
        return temp_path, response_text

    except Exception as e:
        logger.exception("์ด๋ฏธ์ง€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ:")
        return None, f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"  # ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ None๊ณผ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€ ๋ฐ˜ํ™˜


def merge_images(person_img_path, product_img_path, background_img_path, prompt, model="gemini-2.0-flash-exp-image-generation"):
    """๊ธฐ์กด ์ด๋ฏธ์ง€ ํ•ฉ์„ฑ ํ•จ์ˆ˜ (์ด์ „ ์ฝ”๋“œ์™€ ๋™์ผ)"""
    logger.debug(f"merge_images ํ•จ์ˆ˜ ์‹œ์ž‘ - ํ”„๋กฌํ”„ํŠธ: '{prompt}'")
    
    try:
        # API ํ‚ค๋Š” ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋ถˆ๋Ÿฌ์˜ด
        effective_api_key = os.environ.get("GEMINI_API_KEY")
        if effective_api_key:
            logger.debug("ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ API ํ‚ค ๋ถˆ๋Ÿฌ์˜ด")
        else:
            logger.error("API ํ‚ค๊ฐ€ ํ™˜๊ฒฝ๋ณ€์ˆ˜์— ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
            raise ValueError("API ํ‚ค๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")

        client = genai.Client(api_key=effective_api_key)
        logger.debug("Gemini ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ.")

        # ์ด๋ฏธ์ง€ ํŒŒ์ผ ์—…๋กœ๋“œ
        person_file = client.files.upload(file=person_img_path)
        logger.debug(f"์‚ฌ๋žŒ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ์™„๋ฃŒ: {person_file.uri}")
        
        product_file = client.files.upload(file=product_img_path)
        logger.debug(f"์ƒํ’ˆ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ์™„๋ฃŒ: {product_file.uri}")
        
        # ์ปจํ…์ธ  ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
        parts = []
        
        # ์‚ฌ๋žŒ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€
        parts.append(
            types.Part.from_uri(
                file_uri=person_file.uri,
                mime_type=person_file.mime_type
            )
        )
        
        # ์ƒํ’ˆ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€
        parts.append(
            types.Part.from_uri(
                file_uri=product_file.uri,
                mime_type=product_file.mime_type
            )
        )
        
        # ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€๊ฐ€ ์žˆ์œผ๋ฉด ์ถ”๊ฐ€
        if background_img_path:
            background_file = client.files.upload(file=background_img_path)
            logger.debug(f"๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ์™„๋ฃŒ: {background_file.uri}")
            parts.append(
                types.Part.from_uri(
                    file_uri=background_file.uri,
                    mime_type=background_file.mime_type
                )
            )
            logger.debug("๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€๋จ")
        
        # ๋งˆ์ง€๋ง‰์— ํ”„๋กฌํ”„ํŠธ ์ถ”๊ฐ€
        parts.append(
            types.Part.from_text(text=prompt)
        )
        
        logger.debug(f"์ปจํ…์ธ  ๊ฐ์ฒด ์ƒ์„ฑ ์™„๋ฃŒ: {len(parts)} ์•„์ดํ…œ")

        # ์ƒ์„ฑ ์„ค์ •
        generate_content_config = types.GenerateContentConfig(
            temperature=1,
            top_p=0.95,
            top_k=40,
            max_output_tokens=8192,
            response_modalities=["image", "text"],
        )
        logger.debug(f"์ƒ์„ฑ ์„ค์ •: {generate_content_config}")

        with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
            temp_path = tmp.name
            logger.debug(f"์ž„์‹œ ํŒŒ์ผ ์ƒ์„ฑ๋จ: {temp_path}")

            # ์ŠคํŠธ๋ฆฌ๋ฐ ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ ์ˆ˜์‹ 
            response_stream = client.models.generate_content_stream(
                model=model,
                contents=[
                    types.Content(
                        role="user",
                        parts=parts,
                    ),
                ],
                config=generate_content_config,
            )
            
            logger.debug("์‘๋‹ต ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ ์‹œ์ž‘...")
            
            # ์‘๋‹ต์—์„œ ์ด๋ฏธ์ง€์™€ ํ…์ŠคํŠธ ์ถ”์ถœ
            image_saved = False
            response_text = ""
            
            for chunk in response_stream:
                logger.debug(f"chunk ์ˆ˜์‹ : {chunk}")
                
                # ์‘๋‹ต ๊ฒ€์ฆ
                if not hasattr(chunk, 'candidates') or not chunk.candidates or len(chunk.candidates) == 0:
                    logger.warning("chunk์— candidates๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.")
                    continue
                    
                if not hasattr(chunk.candidates[0], 'content') or chunk.candidates[0].content is None:
                    logger.warning("chunk.candidates[0]์— content๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.")
                    continue
                    
                if not hasattr(chunk.candidates[0].content, 'parts') or not chunk.candidates[0].content.parts:
                    logger.warning("chunk.candidates[0].content์— parts๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.")
                    continue
                
                for part in chunk.candidates[0].content.parts:
                    if hasattr(part, 'text') and part.text:
                        response_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)
                        logger.info(f"MIME ํƒ€์ž… {part.inline_data.mime_type}์˜ ํŒŒ์ผ์ด ์ €์žฅ๋จ: {temp_path}")
                        image_saved = True

            if not image_saved:
                logger.warning("์ด๋ฏธ์ง€๊ฐ€ ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
                return None, response_text or "์ด๋ฏธ์ง€๊ฐ€ ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ํ”„๋กฌํ”„ํŠธ๋‚˜ ์ด๋ฏธ์ง€๋กœ ์‹œ๋„ํ•ด๋ณด์„ธ์š”."

        logger.debug("์ด๋ฏธ์ง€ ์ƒ์„ฑ ์™„๋ฃŒ.")
        return temp_path, response_text

    except Exception as e:
        logger.exception("์ด๋ฏธ์ง€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ:")
        return None, f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"  # ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ None๊ณผ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€ ๋ฐ˜ํ™˜


def process_images_and_prompt(person_pil, product_pil, background_pil, prompt):
    """
    ์ด๋ฏธ์ง€ ๋ฐ ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•˜์—ฌ ์ด๋ฏธ์ง€๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜
    
    ์ด๋ฏธ์ง€ ์ž…๋ ฅ์ด ์—†๋Š” ๊ฒฝ์šฐ ํ…์ŠคํŠธ ๊ธฐ๋ฐ˜ ์ด๋ฏธ์ง€ ์ƒ์„ฑ์œผ๋กœ ์ „ํ™˜
    ์ด๋ฏธ์ง€ ์ž…๋ ฅ์ด ์žˆ๋Š” ๊ฒฝ์šฐ ๊ธฐ์กด์˜ ์ด๋ฏธ์ง€ ํ•ฉ์„ฑ ๋กœ์ง ์œ ์ง€
    """
    logger.debug(f"process_images_and_prompt ํ•จ์ˆ˜ ์‹œ์ž‘ - ํ”„๋กฌํ”„ํŠธ: '{prompt}'")
    
    try:
        # ์ด๋ฏธ์ง€ ์ž…๋ ฅ์ด ๋ชจ๋‘ ์—†๋Š” ๊ฒฝ์šฐ ํ…์ŠคํŠธ ๊ธฐ๋ฐ˜ ์ด๋ฏธ์ง€ ์ƒ์„ฑ
        if person_pil is None and product_pil is None and background_pil is None:
            logger.debug("์ด๋ฏธ์ง€ ์—†์Œ. ํ…์ŠคํŠธ ๊ธฐ๋ฐ˜ ์ด๋ฏธ์ง€ ์ƒ์„ฑ์œผ๋กœ ์ „ํ™˜")
            result_path, response_text = generate_image_from_prompt(prompt)
            
            if result_path:
                try:
                    result_img = Image.open(result_path)
                    if result_img.mode == "RGBA":
                        result_img = result_img.convert("RGB")
                    
                    return [result_img], response_text or "์ด๋ฏธ์ง€๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
                except Exception as e:
                    logger.exception(f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
                    return [], f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜: {str(e)}"
            else:
                return [], response_text or "์ด๋ฏธ์ง€ ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."
        
        # ํ•„์ˆ˜ ์ด๋ฏธ์ง€ ํ™•์ธ (์ด๋ฏธ์ง€ ํ•ฉ์„ฑ ๋ชจ๋“œ)
        if person_pil is None:
            return [], "์‚ฌ๋žŒ ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
        if product_pil is None:
            return [], "์ƒํ’ˆ ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
            
        # ๊ธฐ๋ณธ ํ”„๋กฌํ”„ํŠธ ์„ค์ • (๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ)
        if not prompt or not prompt.strip():
            if background_pil:
                prompt = "์ด ๋ฐฐ๊ฒฝ์— ์ด ์‚ฌ๋žŒ์ด ์ด ์ƒํ’ˆ์„ ์‚ฌ์šฉํ•˜๋Š” ๋ชจ์Šต์„ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋ณด์—ฌ์ฃผ์„ธ์š”. ์ƒํ’ˆ์„ ์ž˜ ๋ณด์ด๊ฒŒ ํ•ด์ฃผ์„ธ์š”. Create a natural composite image showing this person using this product in this background setting. Make sure the product is clearly visible."
            else:
                prompt = "์ด ์‚ฌ๋žŒ์ด ์ด ์ƒํ’ˆ์„ ์‚ฌ์šฉํ•˜๋Š” ๋ชจ์Šต์„ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋ณด์—ฌ์ฃผ์„ธ์š”. ์ƒํ’ˆ์„ ์ž˜ ๋ณด์ด๊ฒŒ ํ•ด์ฃผ์„ธ์š”. Create a natural composite image showing this person using this product. Make sure the product is clearly visible."
        
        # ํ”„๋กฌํ”„ํŠธ์— ์˜์–ด๊ฐ€ ์—†์œผ๋ฉด ์˜์–ด ํ”„๋กฌํ”„ํŠธ ์ถ”๊ฐ€ (๋” ๋‚˜์€ ๊ฒฐ๊ณผ๋ฅผ ์œ„ํ•ด)
        if not any(ord(c) < 128 for c in prompt):
            if background_pil:
                prompt += " Create a realistic composite image of this person with this product in this background."
            else:
                prompt += " Create a realistic composite image of this person with this product."
        
        # ์ด๋ฏธ์ง€ ์ €์žฅ
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_person:
            person_path = tmp_person.name
            # RGB๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ €์žฅ
            person_img = person_pil
            if person_img.mode != 'RGB':
                person_img = person_img.convert('RGB')
            person_img.save(person_path, 'JPEG')
            logger.debug(f"์‚ฌ๋žŒ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {person_path}")
            
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_product:
            product_path = tmp_product.name
            # RGB๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ €์žฅ
            product_img = product_pil
            if product_img.mode != 'RGB':
                product_img = product_img.convert('RGB')
            product_img.save(product_path, 'JPEG')
            logger.debug(f"์ƒํ’ˆ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {product_path}")
        
        # ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ €์žฅ (์žˆ๋Š” ๊ฒฝ์šฐ)
        background_path = None
        if background_pil is not None:
            with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_bg:
                background_path = tmp_bg.name
                # RGB๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ €์žฅ
                background_img = background_pil
                if background_img.mode != 'RGB':
                    background_img = background_img.convert('RGB')
                background_img.save(background_path, 'JPEG')
                logger.debug(f"๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {background_path}")

        # ์ด๋ฏธ์ง€ ํ•ฉ์„ฑ ์‹คํ–‰
        result_path, response_text = merge_images(
            person_img_path=person_path,
            product_img_path=product_path,
            background_img_path=background_path,
            prompt=prompt
        )

        # ์ด๋ฏธ์ง€ ๋ฐ˜ํ™˜ ๋ฐ ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        if result_path:
            logger.debug(f"์ด๋ฏธ์ง€ ์ƒ์„ฑ ์™„๋ฃŒ. ๊ฒฝ๋กœ: {result_path}")
            try:
                result_img = Image.open(result_path)
                if result_img.mode == "RGBA":
                    result_img = result_img.convert("RGB")
                
                # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
                try:
                    os.unlink(person_path)
                    os.unlink(product_path)
                    if background_path:
                        os.unlink(background_path)
                except Exception as e:
                    logger.warning(f"์ž„์‹œ ํŒŒ์ผ ์‚ญ์ œ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
                
                return [result_img], response_text or "์ด๋ฏธ์ง€๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
            except Exception as e:
                logger.exception(f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
                return [], f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜: {str(e)}"
        else:
            logger.error("merge_images ํ•จ์ˆ˜์—์„œ None ๋ฐ˜ํ™˜๋จ.")
            return [], response_text or "์ด๋ฏธ์ง€ ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์ด๋ฏธ์ง€๋‚˜ ํ”„๋กฌํ”„ํŠธ๋กœ ์‹œ๋„ํ•ด๋ณด์„ธ์š”."

    except Exception as e:
        logger.exception("process_images_and_prompt ํ•จ์ˆ˜์—์„œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ:")
        return [], f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"  # ์˜ค๋ฅ˜ ์‹œ ๋นˆ ๋ฆฌ์ŠคํŠธ์™€ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€ ๋ฐ˜ํ™˜