File size: 10,761 Bytes
8d852cf
 
 
 
 
 
 
 
 
 
1e9bbd5
8d852cf
ddcfe75
 
8d852cf
e0e8bcb
 
 
 
 
8d852cf
 
 
 
ddcfe75
8d852cf
e0e8bcb
8d852cf
 
e0e8bcb
8d852cf
ddcfe75
1e9bbd5
 
 
8d852cf
e0e8bcb
 
 
 
 
 
 
8d852cf
 
e0e8bcb
8d852cf
1e9bbd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d852cf
 
 
 
 
1e9bbd5
8d852cf
e0e8bcb
8d852cf
 
 
e0e8bcb
8d852cf
1e9bbd5
 
8d852cf
 
 
 
1e9bbd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d852cf
 
 
e0e8bcb
 
ddcfe75
8d852cf
45f2341
e0e8bcb
993c58c
45f2341
bfd9212
45f2341
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfd9212
1e9bbd5
 
 
 
 
 
 
 
 
e0e8bcb
993c58c
1e9bbd5
 
 
 
 
 
 
993c58c
e0e8bcb
 
bfd9212
8d852cf
 
1e9bbd5
 
 
 
 
 
 
 
 
 
 
8d852cf
 
e0e8bcb
 
ddcfe75
8d852cf
e0e8bcb
 
ddcfe75
8d852cf
e0e8bcb
8d852cf
 
 
 
e0e8bcb
 
 
 
 
 
 
8d852cf
 
 
45f2341
8d852cf
 
 
1e9bbd5
 
 
8d852cf
bfd9212
e0e8bcb
 
8d852cf
e0e8bcb
8d852cf
e0e8bcb
1e9bbd5
8d852cf
 
bfd9212
45f2341
bfd9212
8d852cf
e0e8bcb
1e9bbd5
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import time
import uuid
import tempfile
from PIL import Image
import gradio as gr
import base64
import mimetypes
import logging
from io import BytesIO

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(text, original_image_path, background_image_path=None, style_image_path=None, model="gemini-2.0-flash-exp-image-generation"):
    logger.debug(f"generate ํ•จ์ˆ˜ ์‹œ์ž‘ - ํ…์ŠคํŠธ: '{text}', ์›๋ณธ ํŒŒ์ผ๋ช…: '{original_image_path}', ๋ชจ๋ธ: '{model}'")
    
    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 ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ.")

        # PIL ์ด๋ฏธ์ง€ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜
        original_img = Image.open(original_image_path)
        
        # ์ปจํ…์ธ  ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ (๊ณต์‹ ๋ฌธ์„œ ๋ฐฉ์‹๋Œ€๋กœ)
        contents = []
        
        # ํ…์ŠคํŠธ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์ž‘์„ฑ
        prompt = text
        if background_image_path and "๋ฐฐ๊ฒฝ" not in text.lower():
            prompt += " ์›๋ณธ ์ด๋ฏธ์ง€์˜ ๋ฐฐ๊ฒฝ์„ ๋‘ ๋ฒˆ์งธ ์—…๋กœ๋“œ๋œ ์ด๋ฏธ์ง€๋กœ ์™„์ „ํžˆ ๊ต์ฒดํ•ด ์ฃผ์„ธ์š”. ์ด๋ฏธ์ง€๋ฅผ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ๋ณด์—ฌ์ฃผ์„ธ์š”."
        if style_image_path and "์Šคํƒ€์ผ" not in text.lower():
            prompt += " ์„ธ ๋ฒˆ์งธ ์ด๋ฏธ์ง€์˜ ์Šคํƒ€์ผ์„ ์ „์ฒด์ ์œผ๋กœ ์ ์šฉํ•ด ์ฃผ์„ธ์š”."
            
        contents.append(prompt)
        contents.append(original_img)
        
        # ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€ (์žˆ๋Š” ๊ฒฝ์šฐ)
        if background_image_path:
            background_img = Image.open(background_image_path)
            contents.append(background_img)
            logger.debug("๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€๋จ")
            
        # ์Šคํƒ€์ผ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€ (์žˆ๋Š” ๊ฒฝ์šฐ)
        if style_image_path:
            style_img = Image.open(style_image_path)
            contents.append(style_img)
            logger.debug("์Šคํƒ€์ผ ์ด๋ฏธ์ง€ ์ถ”๊ฐ€๋จ")
            
        logger.debug(f"์ปจํ…์ธ  ๊ฐ์ฒด ์ƒ์„ฑ ์™„๋ฃŒ: {len(contents)} ์•„์ดํ…œ")

        # ์ƒ์„ฑ ์„ค์ •
        generate_content_config = types.GenerateContentConfig(
            temperature=1,
            top_p=0.95,
            top_k=40,
            max_output_tokens=8192,
            response_modalities=["text", "image"],  # ๋ฌธ์„œ์— ๋งž๊ฒŒ ๋Œ€์†Œ๋ฌธ์ž ์ˆ˜์ •
        )
        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 = client.models.generate_content(
                model=model,
                contents=contents,
                config=generate_content_config,
            )
            
            logger.debug("์‘๋‹ต ์ฒ˜๋ฆฌ ์‹œ์ž‘...")
            
            # ์‘๋‹ต์—์„œ ์ด๋ฏธ์ง€ ์ถ”์ถœ
            image_saved = False
            for part in response.candidates[0].content.parts:
                if hasattr(part, 'text') and part.text:
                    logger.info(f"์ˆ˜์‹ ๋œ ํ…์ŠคํŠธ: {part.text}")
                    print(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

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

    except Exception as e:
        logger.exception("์ด๋ฏธ์ง€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ:")
        return None  # ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ None ๋ฐ˜ํ™˜


def process_image_and_prompt(original_pil, prompt, background_pil=None, style_pil=None):
    logger.debug(f"process_image_and_prompt ํ•จ์ˆ˜ ์‹œ์ž‘ - ํ”„๋กฌํ”„ํŠธ: '{prompt}'")
    try:
        # ์›๋ณธ ์ด๋ฏธ์ง€ ์ €์žฅ
        with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
            original_path = tmp.name
            original_pil.save(original_path)
            logger.debug(f"์›๋ณธ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {original_path}")

        # ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ €์žฅ (์ œ๊ณต๋œ ๊ฒฝ์šฐ)
        background_path = None
        if background_pil is not None:
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_bg:
                background_path = tmp_bg.name
                background_pil.save(background_path)
                logger.debug(f"๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {background_path}")

        # ์Šคํƒ€์ผ ์ด๋ฏธ์ง€ ์ €์žฅ (์ œ๊ณต๋œ ๊ฒฝ์šฐ)
        style_path = None
        if style_pil is not None:
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_style:
                style_path = tmp_style.name
                style_pil.save(style_path)
                logger.debug(f"์Šคํƒ€์ผ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {style_path}")

        # ํ”„๋กฌํ”„ํŠธ ๋ณด๊ฐ• (์˜์–ด์™€ ํ•œ๊ตญ์–ด ๋‘ ์–ธ์–ด๋กœ ์ œ๊ณต)
        if prompt and not prompt.strip():
            if background_path and style_path:
                prompt = "์›๋ณธ ์ด๋ฏธ์ง€์˜ ์ธ๋ฌผ์„ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐฐ๊ฒฝ์„ ๋‘ ๋ฒˆ์งธ ์ด๋ฏธ์ง€๋กœ ๊ต์ฒดํ•˜๊ณ  ์„ธ ๋ฒˆ์งธ ์ด๋ฏธ์ง€์˜ ์Šคํƒ€์ผ์„ ์ ์šฉํ•ด ์ฃผ์„ธ์š”. Please replace the background with the second image while keeping the person, and apply the style of the third image."
            elif background_path:
                prompt = "์›๋ณธ ์ด๋ฏธ์ง€์˜ ์ธ๋ฌผ์„ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐฐ๊ฒฝ์„ ๋‘ ๋ฒˆ์งธ ์ด๋ฏธ์ง€๋กœ ๊ต์ฒดํ•ด ์ฃผ์„ธ์š”. Please replace the background with the second image while keeping the person."
            elif style_path:
                prompt = "์›๋ณธ ์ด๋ฏธ์ง€์— ๋‘ ๋ฒˆ์งธ ์ด๋ฏธ์ง€์˜ ์Šคํƒ€์ผ์„ ์ ์šฉํ•ด ์ฃผ์„ธ์š”. Please apply the style of the second image to the original image."

        model = "gemini-2.0-flash-exp-image-generation"

        gemma_edited_image_path = generate(
            text=prompt,
            original_image_path=original_path,
            background_image_path=background_path,
            style_image_path=style_path,
            model=model
        )

        if gemma_edited_image_path:
            logger.debug(f"์ด๋ฏธ์ง€ ์ƒ์„ฑ ์™„๋ฃŒ. ๊ฒฝ๋กœ: {gemma_edited_image_path}")
            result_img = Image.open(gemma_edited_image_path)
            if result_img.mode == "RGBA":
                result_img = result_img.convert("RGB")
            
            # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
            try:
                os.unlink(original_path)
                if background_path:
                    os.unlink(background_path)
                if style_path:
                    os.unlink(style_path)
            except Exception as e:
                logger.warning(f"์ž„์‹œ ํŒŒ์ผ ์‚ญ์ œ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
            
            return [result_img]
        else:
            logger.error("generate ํ•จ์ˆ˜์—์„œ None ๋ฐ˜ํ™˜๋จ.")
            return []  # ์˜ค๋ฅ˜ ์‹œ ๋นˆ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜

    except Exception as e:
        logger.exception("process_image_and_prompt ํ•จ์ˆ˜์—์„œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ:")
        return []  # ์˜ค๋ฅ˜ ์‹œ ๋นˆ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜


# --- Gradio ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌ์„ฑ ---
with gr.Blocks() as demo:
    gr.HTML(
        """
        <div style='display: flex; align-items: center; justify-content: center; gap: 20px'>
            <div style="background-color: var(--block-background-fill); border-radius: 8px">
                <img src="https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png" style="width: 100px; height: 100px;">
            </div>
            <div>
                <h1>Gemini๋ฅผ ์ด์šฉํ•œ ์ด๋ฏธ์ง€ ํŽธ์ง‘</h1>
                <p>Gemini API ํ‚ค๋Š” ํ™˜๊ฒฝ๋ณ€์ˆ˜(GEMINI_API_KEY)๋กœ ์„ค์ •๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.</p>
            </div>
        </div>
        """
    )
    gr.Markdown("์›๋ณธ, ๋ฐฐ๊ฒฝ, ์Šคํƒ€์ผ ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•˜๊ณ , ํŽธ์ง‘ํ•  ๋‚ด์šฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”.")

    with gr.Row():
        with gr.Column():
            original_input = gr.Image(type="pil", label="์›๋ณธ ์ด๋ฏธ์ง€", image_mode="RGB")
            background_input = gr.Image(type="pil", label="๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€", image_mode="RGB")
            style_input = gr.Image(type="pil", label="์Šคํƒ€์ผ ์ด๋ฏธ์ง€", image_mode="RGB")
            prompt_input = gr.Textbox(
                lines=2,
                placeholder="ํŽธ์ง‘ํ•  ๋‚ด์šฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”...",
                label="ํŽธ์ง‘ ํ”„๋กฌํ”„ํŠธ"
            )
            submit_btn = gr.Button("์ด๋ฏธ์ง€ ํŽธ์ง‘ ์‹คํ–‰")
        with gr.Column():
            output_gallery = gr.Gallery(label="ํŽธ์ง‘ ๊ฒฐ๊ณผ")
            output_text = gr.Textbox(label="API ์‘๋‹ต ํ…์ŠคํŠธ", visible=True)

    submit_btn.click(
        fn=process_image_and_prompt,
        inputs=[original_input, prompt_input, background_input, style_input],
        outputs=output_gallery,
    )

    gr.HTML("""
    <div style="margin-top: 20px; padding: 10px; background-color: #f8f9fa; border-radius: 8px;">
        <h3>์‚ฌ์šฉ ํŒ:</h3>
        <ul>
            <li><strong>ํ”„๋กฌํ”„ํŠธ ์ž‘์„ฑ ์˜ˆ์‹œ:</strong> "์›๋ณธ ์ธ๋ฌผ์„ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐฐ๊ฒฝ์„ ๋‘ ๋ฒˆ์งธ ์ด๋ฏธ์ง€๋กœ ๊ต์ฒดํ•ด ์ฃผ์„ธ์š”."</li>
            <li><strong>๋ฐฐ๊ฒฝ ๊ต์ฒด ๋ช…ํ™•ํ™”:</strong> "๋ฐฐ๊ฒฝ๋งŒ ์™„์ „ํžˆ ๊ต์ฒดํ•˜๊ณ  ์›๋ณธ ์ธ๋ฌผ์€ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•ด ์ฃผ์„ธ์š”."</li>
            <li><strong>์Šคํƒ€์ผ ์ ์šฉ:</strong> "์„ธ ๋ฒˆ์งธ ์ด๋ฏธ์ง€์˜ ์˜ˆ์ˆ  ์Šคํƒ€์ผ์„ ์ „์ฒด ์ด๋ฏธ์ง€์— ์ ์šฉํ•ด ์ฃผ์„ธ์š”."</li>
            <li><strong>์˜์–ด ํ”„๋กฌํ”„ํŠธ:</strong> ๋” ๋‚˜์€ ๊ฒฐ๊ณผ๋ฅผ ์œ„ํ•ด ์˜์–ด์™€ ํ•œ๊ตญ์–ด๋ฅผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•ด ๋ณด์„ธ์š”.</li>
        </ul>
    </div>
    """)

# --- ์‹คํ–‰ ---
demo.launch(share=True)