File size: 10,729 Bytes
8d852cf 1e9bbd5 8d852cf ddcfe75 8d852cf e0e8bcb 8d852cf ddcfe75 8d852cf e0e8bcb 8d852cf e0e8bcb 8d852cf ddcfe75 654ca6d 1e9bbd5 8d852cf e0e8bcb 8d852cf e0e8bcb 8d852cf 1e9bbd5 811d552 1e9bbd5 654ca6d 1e9bbd5 8d852cf 811d552 8d852cf e0e8bcb 8d852cf e0e8bcb 8d852cf 811d552 1e9bbd5 8d852cf 1e9bbd5 811d552 1e9bbd5 811d552 1e9bbd5 811d552 1e9bbd5 811d552 1e9bbd5 811d552 8d852cf e0e8bcb 811d552 ddcfe75 8d852cf 654ca6d 811d552 993c58c 811d552 654ca6d 811d552 654ca6d 811d552 654ca6d 811d552 654ca6d 811d552 654ca6d 811d552 1e9bbd5 993c58c 811d552 8d852cf 1e9bbd5 811d552 654ca6d 1e9bbd5 811d552 8d852cf 654ca6d 811d552 ddcfe75 8d852cf 811d552 ddcfe75 8d852cf e0e8bcb 8d852cf e0e8bcb 654ca6d e0e8bcb 8d852cf 654ca6d 8d852cf 654ca6d 8d852cf bfd9212 654ca6d 811d552 8d852cf 811d552 8d852cf 811d552 8d852cf 811d552 654ca6d 811d552 8d852cf e0e8bcb 1e9bbd5 654ca6d 1e9bbd5 654ca6d 1e9bbd5 811d552 |
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 |
import json
import os
import time
import tempfile
from PIL import Image
import gradio as gr
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 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 ν΄λΌμ΄μΈνΈ μ΄κΈ°ν μλ£.")
# PIL μ΄λ―Έμ§ κ°μ²΄λ‘ λ³ν
person_img = Image.open(person_img_path)
product_img = Image.open(product_img_path)
# 컨ν
μΈ λ¦¬μ€νΈ μμ±
contents = [person_img, product_img]
# λ°°κ²½ μ΄λ―Έμ§κ° μμΌλ©΄ μΆκ°
if background_img_path:
background_img = Image.open(background_img_path)
contents.append(background_img)
logger.debug("λ°°κ²½ μ΄λ―Έμ§ μΆκ°λ¨")
# λ§μ§λ§μ ν둬ννΈ μΆκ°
contents.append(prompt)
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
response_text = ""
for part in response.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
logger.debug("μ΄λ―Έμ§ μμ± μλ£.")
return temp_path, response_text
except Exception as e:
logger.exception("μ΄λ―Έμ§ μμ± μ€ μ€λ₯ λ°μ:")
return None, 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 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=".png", delete=False) as tmp_person:
person_path = tmp_person.name
person_pil.save(person_path)
logger.debug(f"μ¬λ μ΄λ―Έμ§ μ μ₯ μλ£: {person_path}")
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_product:
product_path = tmp_product.name
product_pil.save(product_path)
logger.debug(f"μν μ΄λ―Έμ§ μ μ₯ μλ£: {product_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}")
# μ΄λ―Έμ§ ν©μ± μ€ν
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}")
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
else:
logger.error("merge_images ν¨μμμ None λ°νλ¨.")
return [], response_text # μ€λ₯ μ λΉ λ¦¬μ€νΈ λ°ν
except Exception as e:
logger.exception("process_images_and_prompt ν¨μμμ μ€λ₯ λ°μ:")
return [], str(e) # μ€λ₯ μ λΉ λ¦¬μ€νΈμ μ€λ₯ λ©μμ§ λ°ν
# --- 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>μ¬λ, μν, λ°°κ²½ μ΄λ―Έμ§λ₯Ό ν©μ±νλ μ ν리μΌμ΄μ
μ
λλ€.</p>
</div>
</div>
"""
)
gr.Markdown("μ¬λ μ΄λ―Έμ§, μν μ΄λ―Έμ§, λ°°κ²½ μ΄λ―Έμ§λ₯Ό μ
λ‘λνκ³ , μ΄λ»κ² ν©μ±ν μ§ μ€λͺ
ν΄μ£ΌμΈμ.")
with gr.Row():
with gr.Column():
person_input = gr.Image(type="pil", label="μ¬λ μ΄λ―Έμ§ (νμ)", image_mode="RGB")
product_input = gr.Image(type="pil", label="μν μ΄λ―Έμ§ (νμ)", image_mode="RGB")
background_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="AI μλ΅ ν
μ€νΈ", visible=True)
submit_btn.click(
fn=process_images_and_prompt,
inputs=[person_input, product_input, background_input, prompt_input],
outputs=[output_gallery, output_text],
)
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>
<li><strong>μμ΄ ν둬ννΈ:</strong> λ λμ κ²°κ³Όλ₯Ό μν΄ μμ΄μ νκ΅μ΄λ₯Ό ν¨κ» μ¬μ©ν΄ 보μΈμ.</li>
<li><strong>λ°°κ²½ μ νμ¬ν:</strong> λ°°κ²½ μ΄λ―Έμ§λ μ νμ¬νμ
λλ€. λ°°κ²½ μμ΄ μ¬λκ³Ό μνλ§ ν©μ±ν μλ μμ΅λλ€.</li>
</ul>
</div>
""")
# --- μ€ν ---
if __name__ == "__main__":
demo.launch(share=True) |