Update app.py
Browse files
app.py
CHANGED
@@ -4,7 +4,6 @@ from PIL import Image
|
|
4 |
import gradio as gr
|
5 |
import logging
|
6 |
import re
|
7 |
-
import io
|
8 |
from io import BytesIO
|
9 |
|
10 |
from google import genai
|
@@ -22,111 +21,115 @@ def save_binary_file(file_name, data):
|
|
22 |
with open(file_name, "wb") as f:
|
23 |
f.write(data)
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
def preprocess_prompt(prompt, image1, image2, image3):
|
26 |
"""
|
27 |
프롬프트를 처리하고 기능 명령을 해석
|
28 |
"""
|
29 |
-
# 기존 preprocess_prompt 함수 코드 유지
|
30 |
-
# 이미지 없는 참조 확인 및 처리
|
31 |
has_img1 = image1 is not None
|
32 |
has_img2 = image2 is not None
|
33 |
has_img3 = image3 is not None
|
34 |
-
|
35 |
-
# #1, #2, #3 참조를 설명으로 변환 (이미지가 없는 경우 무시)
|
36 |
if "#1" in prompt and not has_img1:
|
37 |
prompt = prompt.replace("#1", "첫 번째 이미지(없음)")
|
38 |
else:
|
39 |
prompt = prompt.replace("#1", "첫 번째 이미지")
|
40 |
-
|
41 |
if "#2" in prompt and not has_img2:
|
42 |
prompt = prompt.replace("#2", "두 번째 이미지(없음)")
|
43 |
else:
|
44 |
prompt = prompt.replace("#2", "두 번째 이미지")
|
45 |
-
|
46 |
if "#3" in prompt and not has_img3:
|
47 |
prompt = prompt.replace("#3", "세 번째 이미지(없음)")
|
48 |
else:
|
49 |
prompt = prompt.replace("#3", "세 번째 이미지")
|
50 |
-
|
51 |
-
# 기능 명령 해석
|
52 |
if "1. 이미지 변경" in prompt:
|
53 |
-
# 설명 추출을 시도하지만 실패해도 기본 프롬프트 제공
|
54 |
desc_match = re.search(r'#1을 "(.*?)"으로 바꿔라', prompt)
|
55 |
if desc_match:
|
56 |
description = desc_match.group(1)
|
57 |
prompt = f"첫 번째 이미지를 {description}으로 변경해주세요. 원본 이미지의 주요 내용은 유지하되 새로운 스타일과 분위기로 재해석해주세요."
|
58 |
else:
|
59 |
prompt = "첫 번째 이미지를 창의적으로 변형해주세요. 더 생생하고 예술적인 버전으로 만들어주세요."
|
60 |
-
|
61 |
elif "2. 글자지우기" in prompt:
|
62 |
-
# 지울 텍스트 추출을 시도하지만 실패해도 기본 프롬프트 제공
|
63 |
text_match = re.search(r'#1에서 "(.*?)"를 지워라', prompt)
|
64 |
if text_match:
|
65 |
text_to_remove = text_match.group(1)
|
66 |
prompt = f"첫 번째 이미지에서 '{text_to_remove}' 텍스트를 찾아 자연스럽게 제거해주세요. 텍스트가 있던 부분을 배경과 조화롭게 채워주세요."
|
67 |
else:
|
68 |
prompt = "첫 번째 이미지에서 모든 텍스트를 찾아 자연스럽게 제거해주세요. 깔끔한 이미지로 만들어주세요."
|
69 |
-
|
70 |
-
elif "3. 얼굴바꾸기" in prompt:
|
71 |
-
prompt = "첫 번째 이미지의 인물 얼굴을 두 번째 이미지의 얼굴로 자연스럽게 교체해주세요. 얼굴의 표정과 특징은 두 번째 이미지를 따르되, 나머지 부분은 첫 번째 이미지를 유지해주세요."
|
72 |
-
|
73 |
elif "4. 옷바꾸기" in prompt:
|
74 |
-
|
75 |
-
|
76 |
-
prompt = "첫 번째 이미지의 인물 의상을 두 번째 또는 세 번째 이미지의 의상으로 자연스럽게 교체해주세요. 의상의 스타일과 색상은 참조 이미지를 따르되, 신체 비율과 포즈는 첫 번째 이미지를 유지해주세요."
|
77 |
-
else:
|
78 |
-
prompt = "첫 번째 이미지의 인물 의상을 두 번째 이미지의 의상으로 자연스럽게 교체해주세요. 의상의 스타일과 색상은 두 번째 이미지를 따르되, 신체 비율과 포즈는 첫 번째 이미지를 유지해주세요."
|
79 |
-
|
80 |
elif "5. 배경바꾸기" in prompt:
|
81 |
-
prompt = "첫 번째 이미지의 배경을 두 번째 이미지의 배경으로
|
82 |
-
|
83 |
elif "6. 이미지 합성(상품포함)" in prompt:
|
84 |
-
|
85 |
-
|
86 |
-
prompt = "첫 번째 이미지와 두 번째, 세 번째 이미지를 자연스럽게 합성해주세요. 모든 이미지의 주요 요소를 포함하고, 특히 상품이 잘 보이도록 조화롭게 통합해주세요."
|
87 |
-
else:
|
88 |
-
prompt = "첫 번째 이미지와 두 번째 이미지를 자연스럽게 합성해주세요. 두 이미지의 주요 요소를 포함하고, 특히 상품이 잘 보이도록 조화롭게 통합해주세요."
|
89 |
-
|
90 |
-
elif "7. 이미지 합성(스타일적용)" in prompt:
|
91 |
-
prompt = "첫 번째 이미지의 내용을 두 번째 이미지의 스타일로 변환해주세요. 첫 번째 이미지의 주요 피사체와 구도는 유지하되, 두 번째 이미지의 예술적 스타일, 색상, 질감을 적용해주세요."
|
92 |
-
|
93 |
-
# 간단한 색상 변경 요청 처리
|
94 |
-
elif "을 붉은색으로 바꿔라" in prompt or "를 붉은색으로 바꿔라" in prompt:
|
95 |
-
prompt = "첫 번째 이미지를 붉은색 톤으로 변경해주세요. 전체적인 색상을 붉은 계열로 조정하고 자연스러운 느낌을 유지해주세요."
|
96 |
-
|
97 |
-
# 명확한 이미지 생성 요청 추가
|
98 |
prompt += " 이미지를 생성해주세요."
|
99 |
-
|
100 |
return prompt
|
101 |
|
102 |
def generate_with_images(prompt, images):
|
103 |
"""
|
104 |
-
|
105 |
"""
|
106 |
try:
|
107 |
-
# API 키 확인
|
108 |
api_key = os.environ.get("GEMINI_API_KEY")
|
109 |
if not api_key:
|
110 |
return None, "API 키가 설정되지 않았습니다. 환경변수를 확인해주세요."
|
111 |
-
|
112 |
-
# Gemini 클라이언트 초기화
|
113 |
client = genai.Client(api_key=api_key)
|
114 |
-
|
115 |
logger.info(f"Gemini API 요청 시작 - 프롬프트: {prompt}")
|
116 |
-
|
117 |
-
|
118 |
-
contents = []
|
119 |
-
|
120 |
-
# 텍스트 프롬프트 추가
|
121 |
-
contents.append(prompt)
|
122 |
-
|
123 |
-
# 이미지 추가
|
124 |
for idx, img in enumerate(images, 1):
|
125 |
if img is not None:
|
126 |
contents.append(img)
|
127 |
logger.info(f"이미지 #{idx} 추가됨")
|
128 |
-
|
129 |
-
# 생성 설정 - 공식 문서에 따라 responseModalities 설정
|
130 |
response = client.models.generate_content(
|
131 |
model="gemini-2.0-flash-exp-image-generation",
|
132 |
contents=contents,
|
@@ -138,15 +141,11 @@ def generate_with_images(prompt, images):
|
|
138 |
max_output_tokens=8192
|
139 |
)
|
140 |
)
|
141 |
-
|
142 |
-
# 임시 파일 생성
|
143 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
144 |
temp_path = tmp.name
|
145 |
-
|
146 |
result_text = ""
|
147 |
image_found = False
|
148 |
-
|
149 |
-
# 응답 처리
|
150 |
for part in response.candidates[0].content.parts:
|
151 |
if hasattr(part, 'text') and part.text:
|
152 |
result_text += part.text
|
@@ -155,140 +154,171 @@ def generate_with_images(prompt, images):
|
|
155 |
save_binary_file(temp_path, part.inline_data.data)
|
156 |
image_found = True
|
157 |
logger.info("응답에서 이미지 추출 성공")
|
158 |
-
|
159 |
if not image_found:
|
160 |
return None, f"API에서 이미지를 생성하지 못했습니다. 응답 텍스트: {result_text}"
|
161 |
-
|
162 |
-
# 결과 이미지 반환
|
163 |
result_img = Image.open(temp_path)
|
164 |
if result_img.mode == "RGBA":
|
165 |
result_img = result_img.convert("RGB")
|
166 |
-
|
167 |
return result_img, f"이미지가 성공적으로 생성되었습니다. {result_text}"
|
168 |
-
|
169 |
except Exception as e:
|
170 |
logger.exception("이미지 생성 중 오류 발생:")
|
171 |
return None, f"오류 발생: {str(e)}"
|
172 |
|
173 |
def process_images_with_prompt(image1, image2, image3, prompt):
|
174 |
"""
|
175 |
-
3개의 이미지와 프롬프트를
|
|
|
176 |
"""
|
177 |
try:
|
178 |
-
# 이미지 개수 확인
|
179 |
images = [image1, image2, image3]
|
180 |
valid_images = [img for img in images if img is not None]
|
181 |
-
|
182 |
if not valid_images:
|
183 |
-
return None, "적어도 하나의 이미지를 업로드해주세요."
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
|
|
|
|
|
|
|
|
188 |
if len(valid_images) == 1:
|
189 |
-
|
190 |
logger.info("Default prompt generated for single image")
|
191 |
elif len(valid_images) == 2:
|
192 |
-
|
193 |
logger.info("Default prompt generated for two images")
|
194 |
else:
|
195 |
-
|
196 |
logger.info("Default prompt generated for three images")
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
# 새로운 API 호출 방식 사용
|
202 |
-
return generate_with_images(prompt, valid_images)
|
203 |
-
|
204 |
except Exception as e:
|
205 |
logger.exception("이미지 처리 중 오류 발생:")
|
206 |
-
return None, f"오류 발생: {str(e)}"
|
207 |
|
208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
|
210 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
211 |
with gr.Blocks() as demo:
|
212 |
gr.HTML(
|
213 |
"""
|
214 |
<div style="text-align: center; margin-bottom: 1rem;">
|
215 |
-
<h1
|
216 |
-
<p
|
217 |
</div>
|
218 |
"""
|
219 |
)
|
220 |
|
221 |
with gr.Row():
|
222 |
with gr.Column():
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
|
|
|
|
|
|
|
|
230 |
prompt_input = gr.Textbox(
|
231 |
-
lines=
|
232 |
-
placeholder="
|
233 |
-
label="
|
234 |
)
|
235 |
-
|
236 |
-
# 생성 버튼
|
237 |
-
submit_btn = gr.Button("이미지 생성", variant="primary")
|
238 |
-
|
239 |
with gr.Column():
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
prompt_display = gr.Textbox(label="사용된 프롬프트", visible=True)
|
246 |
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
auto_prompt = preprocess_prompt(prompt, image1, image2, image3)
|
265 |
-
|
266 |
-
# 이미지 생성 함수 호출
|
267 |
-
result_img, status = process_images_with_prompt(image1, image2, image3, prompt)
|
268 |
-
|
269 |
-
return result_img, status, auto_prompt
|
270 |
-
except Exception as e:
|
271 |
-
logger.exception("처리 중 오류 발생:")
|
272 |
-
return None, f"오류 발생: {str(e)}", prompt
|
273 |
-
|
274 |
-
submit_btn.click(
|
275 |
-
fn=process_and_show_prompt,
|
276 |
-
inputs=[image1_input, image2_input, image3_input, prompt_input],
|
277 |
-
outputs=[output_image, output_text, prompt_display],
|
278 |
-
)
|
279 |
-
|
280 |
-
gr.Markdown(
|
281 |
-
"""
|
282 |
-
### 사용 방법:
|
283 |
-
|
284 |
-
1. **자동 합성**: 이미지만 업로드하고 프롬프트를 비워두면 자동으로 합성됩니다.
|
285 |
-
2. **이미지 참조**: #1, #2, #3으로 각 이미지를 참조할 수 있습니다.
|
286 |
-
3. **일부 이미지만**: 필요한 이미지만 업로드해도 기능 실행이 가능합니다.
|
287 |
-
|
288 |
-
> **팁**: 프롬프트를 직접 수정할 수도 있습니다.
|
289 |
-
"""
|
290 |
)
|
291 |
|
292 |
-
|
293 |
-
if __name__ == "__main__":
|
294 |
-
demo.launch(share=True)
|
|
|
4 |
import gradio as gr
|
5 |
import logging
|
6 |
import re
|
|
|
7 |
from io import BytesIO
|
8 |
|
9 |
from google import genai
|
|
|
21 |
with open(file_name, "wb") as f:
|
22 |
f.write(data)
|
23 |
|
24 |
+
def translate_prompt_to_english(prompt):
|
25 |
+
"""
|
26 |
+
입력된 프롬프트에 한글이 포함되어 있으면 Gemini‑2.0‑flash 모델을 사용하여 영어로 번역합니다.
|
27 |
+
한글이 없으면 원본 프롬프트를 그대로 반환합니다.
|
28 |
+
"""
|
29 |
+
if not re.search("[가-힣]", prompt):
|
30 |
+
return prompt
|
31 |
+
try:
|
32 |
+
api_key = os.environ.get("GEMINI_API_KEY")
|
33 |
+
if not api_key:
|
34 |
+
logger.error("Gemini API 키가 설정되지 않았습니다.")
|
35 |
+
return prompt
|
36 |
+
client = genai.Client(api_key=api_key)
|
37 |
+
translation_prompt = f"Translate the following Korean text to English:\n\n{prompt}"
|
38 |
+
logger.info(f"Translation prompt: {translation_prompt}")
|
39 |
+
response = client.models.generate_content(
|
40 |
+
model="gemini-2.0-flash",
|
41 |
+
contents=[translation_prompt],
|
42 |
+
config=types.GenerateContentConfig(
|
43 |
+
response_modalities=['Text'],
|
44 |
+
temperature=0.2,
|
45 |
+
top_p=0.95,
|
46 |
+
top_k=40,
|
47 |
+
max_output_tokens=512
|
48 |
+
)
|
49 |
+
)
|
50 |
+
translated_text = ""
|
51 |
+
for part in response.candidates[0].content.parts:
|
52 |
+
if hasattr(part, 'text') and part.text:
|
53 |
+
translated_text += part.text
|
54 |
+
if translated_text.strip():
|
55 |
+
logger.info(f"Translated text: {translated_text.strip()}")
|
56 |
+
return translated_text.strip()
|
57 |
+
else:
|
58 |
+
logger.warning("번역 결과가 없습니다. 원본 프롬프트 사용")
|
59 |
+
return prompt
|
60 |
+
except Exception as e:
|
61 |
+
logger.exception("번역 중 오류 발생:")
|
62 |
+
return prompt
|
63 |
+
|
64 |
def preprocess_prompt(prompt, image1, image2, image3):
|
65 |
"""
|
66 |
프롬프트를 처리하고 기능 명령을 해석
|
67 |
"""
|
|
|
|
|
68 |
has_img1 = image1 is not None
|
69 |
has_img2 = image2 is not None
|
70 |
has_img3 = image3 is not None
|
71 |
+
|
|
|
72 |
if "#1" in prompt and not has_img1:
|
73 |
prompt = prompt.replace("#1", "첫 번째 이미지(없음)")
|
74 |
else:
|
75 |
prompt = prompt.replace("#1", "첫 번째 이미지")
|
76 |
+
|
77 |
if "#2" in prompt and not has_img2:
|
78 |
prompt = prompt.replace("#2", "두 번째 이미지(없음)")
|
79 |
else:
|
80 |
prompt = prompt.replace("#2", "두 번째 이미지")
|
81 |
+
|
82 |
if "#3" in prompt and not has_img3:
|
83 |
prompt = prompt.replace("#3", "세 번째 이미지(없음)")
|
84 |
else:
|
85 |
prompt = prompt.replace("#3", "세 번째 이미지")
|
86 |
+
|
|
|
87 |
if "1. 이미지 변경" in prompt:
|
|
|
88 |
desc_match = re.search(r'#1을 "(.*?)"으로 바꿔라', prompt)
|
89 |
if desc_match:
|
90 |
description = desc_match.group(1)
|
91 |
prompt = f"첫 번째 이미지를 {description}으로 변경해주세요. 원본 이미지의 주요 내용은 유지하되 새로운 스타일과 분위기로 재해석해주세요."
|
92 |
else:
|
93 |
prompt = "첫 번째 이미지를 창의적으로 변형해주세요. 더 생생하고 예술적인 버전으로 만들어주세요."
|
94 |
+
|
95 |
elif "2. 글자지우기" in prompt:
|
|
|
96 |
text_match = re.search(r'#1에서 "(.*?)"를 지워라', prompt)
|
97 |
if text_match:
|
98 |
text_to_remove = text_match.group(1)
|
99 |
prompt = f"첫 번째 이미지에서 '{text_to_remove}' 텍스트를 찾아 자연스럽게 제거해주세요. 텍스트가 있던 부분을 배경과 조화롭게 채워주세요."
|
100 |
else:
|
101 |
prompt = "첫 번째 이미지에서 모든 텍스트를 찾아 자연스럽게 제거해주세요. 깔끔한 이미지로 만들어주세요."
|
102 |
+
|
|
|
|
|
|
|
103 |
elif "4. 옷바꾸기" in prompt:
|
104 |
+
prompt = "첫 번째 이미지의 인물 의상을 두 번째 이미지의 의상으로 변경해주세요. 의상의 스타일과 색상은 두 번째 이미지를 따르되, 신체 비율과 포즈는 첫 번째 이미지를 유지해주세요."
|
105 |
+
|
|
|
|
|
|
|
|
|
106 |
elif "5. 배경바꾸기" in prompt:
|
107 |
+
prompt = "첫 번째 이미지의 배경을 두 번째 이미지의 배경으로 변경해주세요. 첫 번째 이미지의 주요 피사체는 유지하고, 두 번째 이미지의 배경과 조화롭게 합성해주세요."
|
108 |
+
|
109 |
elif "6. 이미지 합성(상품포함)" in prompt:
|
110 |
+
prompt = "첫 번째 이미지와 두 번째 이미지(또는 세 번째 이미지)를 자연스럽게 합성해주세요. 모든 이미지의 주요 요소를 포함하고, 특히 상품이 돋보이도록 조화롭게 통합해주세요."
|
111 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
prompt += " 이미지를 생성해주세요."
|
|
|
113 |
return prompt
|
114 |
|
115 |
def generate_with_images(prompt, images):
|
116 |
"""
|
117 |
+
API 호출을 통해 이미지를 생성하고 결과 이미지를 반환합니다.
|
118 |
"""
|
119 |
try:
|
|
|
120 |
api_key = os.environ.get("GEMINI_API_KEY")
|
121 |
if not api_key:
|
122 |
return None, "API 키가 설정되지 않았습니다. 환경변수를 확인해주세요."
|
123 |
+
|
|
|
124 |
client = genai.Client(api_key=api_key)
|
|
|
125 |
logger.info(f"Gemini API 요청 시작 - 프롬프트: {prompt}")
|
126 |
+
|
127 |
+
contents = [prompt]
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
for idx, img in enumerate(images, 1):
|
129 |
if img is not None:
|
130 |
contents.append(img)
|
131 |
logger.info(f"이미지 #{idx} 추가됨")
|
132 |
+
|
|
|
133 |
response = client.models.generate_content(
|
134 |
model="gemini-2.0-flash-exp-image-generation",
|
135 |
contents=contents,
|
|
|
141 |
max_output_tokens=8192
|
142 |
)
|
143 |
)
|
144 |
+
|
|
|
145 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
146 |
temp_path = tmp.name
|
|
|
147 |
result_text = ""
|
148 |
image_found = False
|
|
|
|
|
149 |
for part in response.candidates[0].content.parts:
|
150 |
if hasattr(part, 'text') and part.text:
|
151 |
result_text += part.text
|
|
|
154 |
save_binary_file(temp_path, part.inline_data.data)
|
155 |
image_found = True
|
156 |
logger.info("응답에서 이미지 추출 성공")
|
|
|
157 |
if not image_found:
|
158 |
return None, f"API에서 이미지를 생성하지 못했습니다. 응답 텍스트: {result_text}"
|
|
|
|
|
159 |
result_img = Image.open(temp_path)
|
160 |
if result_img.mode == "RGBA":
|
161 |
result_img = result_img.convert("RGB")
|
|
|
162 |
return result_img, f"이미지가 성공적으로 생성되었습니다. {result_text}"
|
|
|
163 |
except Exception as e:
|
164 |
logger.exception("이미지 생성 중 오류 발생:")
|
165 |
return None, f"오류 발생: {str(e)}"
|
166 |
|
167 |
def process_images_with_prompt(image1, image2, image3, prompt):
|
168 |
"""
|
169 |
+
3개의 이미지와 프롬프트를 처리하여 최종 영어 프롬프트(final_prompt)를 생성한 후,
|
170 |
+
API를 호출하여 결과 이미지를 반환합니다.
|
171 |
"""
|
172 |
try:
|
|
|
173 |
images = [image1, image2, image3]
|
174 |
valid_images = [img for img in images if img is not None]
|
|
|
175 |
if not valid_images:
|
176 |
+
return None, "적어도 하나의 이미지를 업로드해주세요.", ""
|
177 |
+
|
178 |
+
if prompt and prompt.strip():
|
179 |
+
processed_prompt = preprocess_prompt(prompt, image1, image2, image3)
|
180 |
+
if re.search("[가-힣]", processed_prompt):
|
181 |
+
final_prompt = translate_prompt_to_english(processed_prompt)
|
182 |
+
else:
|
183 |
+
final_prompt = processed_prompt
|
184 |
+
else:
|
185 |
if len(valid_images) == 1:
|
186 |
+
final_prompt = "Please creatively transform this image into a more vivid and artistic version."
|
187 |
logger.info("Default prompt generated for single image")
|
188 |
elif len(valid_images) == 2:
|
189 |
+
final_prompt = "Please seamlessly composite these two images, integrating their key elements harmoniously into a single image."
|
190 |
logger.info("Default prompt generated for two images")
|
191 |
else:
|
192 |
+
final_prompt = "Please creatively composite these three images, combining their main elements into a cohesive and natural scene."
|
193 |
logger.info("Default prompt generated for three images")
|
194 |
+
|
195 |
+
result_img, status = generate_with_images(final_prompt, valid_images)
|
196 |
+
return result_img, status, final_prompt
|
|
|
|
|
|
|
|
|
197 |
except Exception as e:
|
198 |
logger.exception("이미지 처리 중 오류 발생:")
|
199 |
+
return None, f"오류 발생: {str(e)}", prompt
|
200 |
|
201 |
+
def process_and_show_prompt(image1, image2, image3, prompt):
|
202 |
+
try:
|
203 |
+
result_img, status, final_prompt = process_images_with_prompt(image1, image2, image3, prompt)
|
204 |
+
return result_img, status, final_prompt
|
205 |
+
except Exception as e:
|
206 |
+
logger.exception("처리 중 오류 발생:")
|
207 |
+
return None, f"오류 발생: {str(e)}", prompt
|
208 |
|
209 |
+
# 예제 실행 함수들
|
210 |
+
def run_example_1():
|
211 |
+
"""예제 1: 이미지 변경 예제"""
|
212 |
+
input_path = os.path.join("down", "1_in-1.png")
|
213 |
+
output_path = os.path.join("down", "1_out-1.webp")
|
214 |
+
try:
|
215 |
+
input_img = Image.open(input_path)
|
216 |
+
except Exception as e:
|
217 |
+
return None, f"입력 이미지 열기 오류: {str(e)}", ""
|
218 |
+
prompt = "#1 이미지의 [청색 상어레고를 검은 고래레고]으로 변경하라."
|
219 |
+
result_img, status, final_prompt = process_and_show_prompt(input_img, None, None, prompt)
|
220 |
+
if result_img is not None:
|
221 |
+
result_img.save(output_path, "WEBP")
|
222 |
+
return result_img, status, final_prompt
|
223 |
+
|
224 |
+
def run_example_2():
|
225 |
+
"""예제 2: 글자지우기 예제"""
|
226 |
+
input_path = os.path.join("down", "2_in-1.png")
|
227 |
+
output_path = os.path.join("down", "2_out-1.webp")
|
228 |
+
try:
|
229 |
+
input_img = Image.open(input_path)
|
230 |
+
except Exception as e:
|
231 |
+
return None, f"입력 이미지 열기 오류: {str(e)}", ""
|
232 |
+
prompt = "#1 이미지의 [중국어를 모두]를 제거하라."
|
233 |
+
result_img, status, final_prompt = process_and_show_prompt(input_img, None, None, prompt)
|
234 |
+
if result_img is not None:
|
235 |
+
result_img.save(output_path, "WEBP")
|
236 |
+
return result_img, status, final_prompt
|
237 |
+
|
238 |
+
# -------------------------------------------------------------------
|
239 |
+
# 예제 적용 부분 (참조 코드 적���)
|
240 |
+
# -------------------------------------------------------------------
|
241 |
+
# Set up the interaction with two outputs.
|
242 |
+
submit_btn.click(
|
243 |
+
fn=process_image_and_prompt,
|
244 |
+
inputs=[image_input, prompt_input, gemini_api_key],
|
245 |
+
outputs=[output_gallery, output_text],
|
246 |
+
)
|
247 |
+
|
248 |
+
gr.Markdown("## Try these examples", elem_classes="gr-examples-header")
|
249 |
+
|
250 |
+
examples = [
|
251 |
+
["data/1.webp", 'change text to "AMEER"', ""],
|
252 |
+
["data/2.webp", "remove the spoon from hand only", ""],
|
253 |
+
["data/3.webp", 'change text to "Make it "', ""],
|
254 |
+
["data/1.jpg", "add joker style only on face", ""],
|
255 |
+
["data/1777043.jpg", "add joker style only on face", ""],
|
256 |
+
["data/2807615.jpg", "add lipstick on lip only", ""],
|
257 |
+
["data/76860.jpg", "add lipstick on lip only", ""],
|
258 |
+
["data/2807615.jpg", "make it happy looking face only", ""],
|
259 |
+
]
|
260 |
+
|
261 |
+
gr.Examples(
|
262 |
+
examples=examples,
|
263 |
+
inputs=[image_input, prompt_input],
|
264 |
+
elem_id="examples-grid"
|
265 |
+
)
|
266 |
+
# -------------------------------------------------------------------
|
267 |
+
|
268 |
+
# 기존 Gradio 인터페이스 구성 (예제 적용 외 다른 코드는 그대로 유지)
|
269 |
with gr.Blocks() as demo:
|
270 |
gr.HTML(
|
271 |
"""
|
272 |
<div style="text-align: center; margin-bottom: 1rem;">
|
273 |
+
<h1>Gemini for Image Editing</h1>
|
274 |
+
<p>Upload an image and enter a prompt to generate outputs.</p>
|
275 |
</div>
|
276 |
"""
|
277 |
)
|
278 |
|
279 |
with gr.Row():
|
280 |
with gr.Column():
|
281 |
+
image_input = gr.Image(
|
282 |
+
type="pil",
|
283 |
+
label="Upload Image",
|
284 |
+
image_mode="RGBA",
|
285 |
+
elem_id="image-input"
|
286 |
+
)
|
287 |
+
gemini_api_key = gr.Textbox(
|
288 |
+
lines=1,
|
289 |
+
placeholder="Enter Gemini API Key (optional)",
|
290 |
+
label="Gemini API Key (optional)"
|
291 |
+
)
|
292 |
prompt_input = gr.Textbox(
|
293 |
+
lines=2,
|
294 |
+
placeholder="Enter prompt here...",
|
295 |
+
label="Prompt"
|
296 |
)
|
297 |
+
submit_btn = gr.Button("Generate")
|
|
|
|
|
|
|
298 |
with gr.Column():
|
299 |
+
output_gallery = gr.Gallery(label="Generated Outputs")
|
300 |
+
output_text = gr.Textbox(
|
301 |
+
label="Gemini Output",
|
302 |
+
placeholder="Text response will appear here if no image is generated."
|
303 |
+
)
|
|
|
304 |
|
305 |
+
gr.Markdown("## Try these examples", elem_classes="gr-examples-header")
|
306 |
+
|
307 |
+
examples = [
|
308 |
+
["data/1.webp", 'change text to "AMEER"', ""],
|
309 |
+
["data/2.webp", "remove the spoon from hand only", ""],
|
310 |
+
["data/3.webp", 'change text to "Make it "', ""],
|
311 |
+
["data/1.jpg", "add joker style only on face", ""],
|
312 |
+
["data/1777043.jpg", "add joker style only on face", ""],
|
313 |
+
["data/2807615.jpg", "add lipstick on lip only", ""],
|
314 |
+
["data/76860.jpg", "add lipstick on lip only", ""],
|
315 |
+
["data/2807615.jpg", "make it happy looking face only", ""],
|
316 |
+
]
|
317 |
+
|
318 |
+
gr.Examples(
|
319 |
+
examples=examples,
|
320 |
+
inputs=[image_input, prompt_input],
|
321 |
+
elem_id="examples-grid"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
322 |
)
|
323 |
|
324 |
+
demo.queue(max_size=50).launch()
|
|
|
|