ssboost commited on
Commit
ccb0626
ยท
verified ยท
1 Parent(s): 0334f57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +830 -1
app.py CHANGED
@@ -1,2 +1,831 @@
1
  import os
2
- exec(os.environ.get('APP'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import sys
3
+ import base64
4
+ import io
5
+ import logging
6
+ import tempfile
7
+ import traceback
8
+ import requests
9
+ from PIL import Image
10
+ import gradio as gr
11
+ from openai import OpenAI
12
+ import replicate
13
+ from google import genai
14
+ from google.genai import types
15
+
16
+ # ๋กœ๊น… ์„ค์ •
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
20
+ handlers=[
21
+ logging.FileHandler("app.log"),
22
+ logging.StreamHandler(sys.stdout)
23
+ ]
24
+ )
25
+ logger = logging.getLogger("image-enhancer-app")
26
+
27
+ # API ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” (์•ˆ์ „ํ•˜๊ฒŒ)
28
+ openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", ""))
29
+
30
+ # Gemini ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” - API ํ‚ค๊ฐ€ ์žˆ์„ ๋•Œ๋งŒ
31
+ gemini_api_key = os.environ.get("GEMINI_API_KEY")
32
+ if gemini_api_key and gemini_api_key.strip():
33
+ try:
34
+ gemini_client = genai.Client(api_key=gemini_api_key)
35
+ logger.info("Gemini client initialized successfully")
36
+ except Exception as e:
37
+ logger.error(f"Failed to initialize Gemini client: {e}")
38
+ gemini_client = None
39
+ else:
40
+ logger.warning("GEMINI_API_KEY not found or empty, Gemini client not initialized")
41
+ gemini_client = None
42
+
43
+ # ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ ๋กœ๋“œ
44
+ BACKGROUNDS_DATA = os.environ.get("BACKGROUNDS_DATA", "")
45
+ # ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋น„๋ฐ€๋ฒˆํ˜ธ ๋กœ๋“œ
46
+ APP_PASSWORD = os.environ.get("APP_PASSWORD", "")
47
+
48
+ if not BACKGROUNDS_DATA:
49
+ logger.error("BACKGROUNDS_DATA environment variable not found")
50
+ raise ValueError("BACKGROUNDS_DATA ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
51
+
52
+ if not APP_PASSWORD:
53
+ logger.error("APP_PASSWORD environment variable not found")
54
+ raise ValueError("APP_PASSWORD ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
55
+
56
+ # ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๋ฐ์ดํ„ฐ๋ฅผ ํŒŒ์ด์ฌ ์ฝ”๋“œ๋กœ ์‹คํ–‰ํ•˜์—ฌ ๋ฐฐ๊ฒฝ ๋”•์…”๋„ˆ๋ฆฌ๋“ค ์ƒ์„ฑ
57
+ try:
58
+ exec(BACKGROUNDS_DATA)
59
+ logger.info("Background data loaded from environment variable")
60
+ except Exception as e:
61
+ logger.error(f"Failed to load background data: {e}")
62
+ raise ValueError(f"๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์‹คํŒจ: {e}")
63
+
64
+ # ์ž„์‹œ ํŒŒ์ผ ์ €์žฅ ํ•จ์ˆ˜
65
+ def save_uploaded_file(uploaded_file, suffix='.png'):
66
+ try:
67
+ logger.info(f"Processing uploaded file: {type(uploaded_file)}")
68
+
69
+ if uploaded_file is None:
70
+ logger.warning("Uploaded file is None")
71
+ return None
72
+
73
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
74
+ temp_filename = temp_file.name
75
+ logger.info(f"Created temporary file: {temp_filename}")
76
+
77
+ # Gradio ์—…๋กœ๋“œ ํŒŒ์ผ ์ฒ˜๋ฆฌ
78
+ if isinstance(uploaded_file, str): # ์ด๋ฏธ ํŒŒ์ผ ๊ฒฝ๋กœ์ธ ๊ฒฝ์šฐ
79
+ logger.info(f"Uploaded file is already a path: {uploaded_file}")
80
+ return uploaded_file
81
+
82
+ # PIL Image ์ฒ˜๋ฆฌ
83
+ if isinstance(uploaded_file, Image.Image):
84
+ logger.info("Uploaded file is a PIL Image")
85
+ uploaded_file.save(temp_filename, format="PNG")
86
+ return temp_filename
87
+
88
+ # ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
89
+ with open(temp_filename, "wb") as f:
90
+ if hasattr(uploaded_file, "read"): # ํŒŒ์ผ ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ
91
+ logger.info("Processing file object")
92
+ content = uploaded_file.read()
93
+ f.write(content)
94
+ logger.info(f"Wrote {len(content)} bytes to {temp_filename}")
95
+ else: # ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ์ธ ๊ฒฝ์šฐ
96
+ logger.info("Processing binary data")
97
+ f.write(uploaded_file)
98
+ logger.info(f"Wrote data to {temp_filename}")
99
+
100
+ return temp_filename
101
+ except Exception as e:
102
+ logger.error(f"Error saving uploaded file: {e}")
103
+ logger.error(traceback.format_exc())
104
+ return None
105
+
106
+ # ํ…์ŠคํŠธ ๋ฒˆ์—ญ ํ•จ์ˆ˜ (ํ•œ๊ตญ์–ด โ†’ ์˜์–ด) - Gemini 2.0 Flash ์ „์šฉ
107
+ def translate_to_english(text):
108
+ """ํ•œ๊ตญ์–ด ํ…์ŠคํŠธ๋ฅผ ์˜์–ด๋กœ ๋ฒˆ์—ญ (Gemini 2.0 Flash ์‚ฌ์šฉ)"""
109
+ try:
110
+ if not text or not text.strip():
111
+ return ""
112
+
113
+ # Gemini ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ดˆ๊ธฐํ™”๋˜์—ˆ๋Š”์ง€ ํ™•์ธ
114
+ if gemini_client is None:
115
+ logger.warning("Gemini client not available, returning original text")
116
+ return text
117
+
118
+ # Gemini 2.0 Flash๋ฅผ ์‚ฌ์šฉํ•œ ๋ฒˆ์—ญ
119
+ try:
120
+ response = gemini_client.models.generate_content(
121
+ model="gemini-2.0-flash",
122
+ config=types.GenerateContentConfig(
123
+ system_instruction="You are a professional translator. Translate the given Korean text to English. Keep the translation natural and contextually appropriate for image generation prompts. If the text is already in English, return it as is. Only return the translated text without any additional explanation.",
124
+ max_output_tokens=200,
125
+ temperature=0.1
126
+ ),
127
+ contents=[f"Translate this to English: {text}"]
128
+ )
129
+
130
+ translated = response.text.strip()
131
+ logger.info(f"Translated '{text}' to '{translated}' using Gemini 2.0 Flash")
132
+ return translated
133
+
134
+ except Exception as e:
135
+ logger.error(f"Gemini translation error: {e}")
136
+ logger.warning("Translation failed, returning original text")
137
+ return text
138
+
139
+ except Exception as e:
140
+ logger.error(f"Translation error: {e}")
141
+ return text
142
+
143
+ # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ํ•จ์ˆ˜ (์ข…ํšก๋น„์™€ ์š”์ฒญ์‚ฌํ•ญ ํ†ตํ•ฉ)
144
+ def generate_prompt(background_type, background_name, user_request, aspect_ratio="1:1"):
145
+ # ๊ธฐ๋ณธ ๊ณ ์ • ํ”„๋กฌํ”„ํŠธ (์ข…ํšก๋น„ ์ •๋ณด ํฌํ•จ) - ์˜์–ด๋กœ ๋ณ€๊ฒฝ
146
+ fixed_prompt = f"""
147
+ ## Fixed Prompt (Required)
148
+ [Aspect Ratio: {aspect_ratio}]
149
+ [Foreground: all uploaded product images, preserve their original proportions and clarity]
150
+ [Preserve originals: keep the same random seed; maintain exact shape and aspect ratio; no vertical or horizontal scaling; do not alter any existing logos or text]
151
+ [Product sizing: ensure product images maintain at least 50% of their height relative to the background]
152
+ [Composition: products must be naturally composited with the background, maintain proper shadows aligned with lighting]
153
+ [Product placement: if products already exist in the background prompt, follow their exact arrangement and positioning]
154
+ """
155
+
156
+ # ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ ์„ ํƒ
157
+ if background_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ":
158
+ background_prompt = SIMPLE_BACKGROUNDS.get(background_name, "")
159
+ elif background_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ":
160
+ background_prompt = STUDIO_BACKGROUNDS.get(background_name, "")
161
+ elif background_type == "์ž์—ฐ ํ™˜๊ฒฝ":
162
+ background_prompt = NATURE_BACKGROUNDS.get(background_name, "")
163
+ elif background_type == "์‹ค๋‚ด ํ™˜๊ฒฝ":
164
+ background_prompt = INDOOR_BACKGROUNDS.get(background_name, "")
165
+ elif background_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ":
166
+ background_prompt = SPECIAL_BACKGROUNDS.get(background_name, "")
167
+ elif background_type == "์ฃผ์–ผ๋ฆฌ":
168
+ background_prompt = JEWELRY_BACKGROUNDS.get(background_name, "")
169
+ elif background_type == "ํŠน์ˆ˜ํšจ๊ณผ":
170
+ background_prompt = SPECIAL_EFFECTS_BACKGROUNDS.get(background_name, "")
171
+ else:
172
+ background_prompt = "clean white background with soft even lighting"
173
+
174
+ # ์‚ฌ์šฉ์ž ์š”์ฒญ์‚ฌํ•ญ ์ฒ˜๋ฆฌ
175
+ if user_request and user_request.strip():
176
+ # ํ•œ๊ตญ์–ด ์š”์ฒญ์‚ฌํ•ญ์„ ์˜์–ด๋กœ ๋ฒˆ์—ญ (Gemini 2.0 Flash ์‚ฌ์šฉ)
177
+ translated_request = translate_to_english(user_request)
178
+
179
+ # ๋ฒˆ์—ญ๋œ ์š”์ฒญ์‚ฌํ•ญ์„ ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ์— ํ†ตํ•ฉ
180
+ integrated_background = f"{background_prompt} Additionally, incorporate the following elements naturally into the scene: {translated_request}. Ensure these elements blend harmoniously with the existing background while maintaining the overall aesthetic and lighting."
181
+
182
+ # ์š”์ฒญ ํ”„๋กฌํ”„ํŠธ ์„น์…˜ (๋ฒˆ์—ญ๋œ ๋‚ด์šฉ ์‚ฌ์šฉ)
183
+ request_prompt = f"""
184
+ ## Request Prompt
185
+ {translated_request}
186
+ """
187
+
188
+ # ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ ์„น์…˜
189
+ background_section = f"""
190
+ ## Background Prompt (Background Settings)
191
+ {integrated_background}
192
+ """
193
+ else:
194
+ # ์š”์ฒญ์‚ฌํ•ญ์ด ์—†๋Š” ๊ฒฝ์šฐ
195
+ request_prompt = f"""
196
+ ## Request Prompt
197
+ No specific request
198
+ """
199
+
200
+ # ์š”์ฒญ์‚ฌํ•ญ์ด ์—†๋Š” ๊ฒฝ์šฐ ๊ธฐ๋ณธ ๋ฐฐ๊ฒฝ๋งŒ ์‚ฌ์šฉ
201
+ background_section = f"""
202
+ ## Background Prompt (Background Settings)
203
+ {background_prompt}
204
+ """
205
+
206
+ # ์ตœ์ข… ํ”„๋กฌํ”„ํŠธ ์กฐํ•ฉ
207
+ final_prompt = fixed_prompt + request_prompt + background_section
208
+
209
+ return final_prompt
210
+
211
+ # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ํ•จ์ˆ˜
212
+ def edit_and_enhance_image(
213
+ prompt,
214
+ image,
215
+ quality_level="gpt",
216
+ aspect_ratio="1:1",
217
+ output_format="jpg",
218
+ enable_enhancement=True,
219
+ enhancement_level=2
220
+ ):
221
+ try:
222
+ logger.info(f"Editing image with prompt: '{prompt[:50]}...' (truncated)")
223
+ logger.info(f"Parameters: quality_level={quality_level}, aspect_ratio={aspect_ratio}, output_format={output_format}")
224
+ logger.info(f"Enhancement requested: {enable_enhancement}, level: {enhancement_level}")
225
+
226
+ if image is None:
227
+ logger.error("No image provided")
228
+ return None, None, None, "์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."
229
+
230
+ # ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ
231
+ processed_image = None
232
+ temp_paths = [] # ๋‚˜์ค‘์— ์ •๋ฆฌํ•  ๊ฒฝ๋กœ ์ถ”์ 
233
+
234
+ img_path = save_uploaded_file(image)
235
+ if img_path:
236
+ logger.info(f"Saved image to temp path: {img_path}")
237
+ processed_image = open(img_path, "rb")
238
+ temp_paths.append(img_path)
239
+ else:
240
+ logger.error("Failed to save image")
241
+ return None, None, None, "์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด ๋ณด์„ธ์š”."
242
+
243
+ # ๋ชจ๋ธ ์„ ํƒ์— ๋”ฐ๋ฅธ ์ฒ˜๋ฆฌ
244
+ edited_images = []
245
+ usage_info = ""
246
+ error_msg = None
247
+
248
+ try:
249
+ if quality_level == "gpt":
250
+ # GPT ๋ชจ๋ธ ์‚ฌ์šฉ
251
+ if not openai_client.api_key:
252
+ logger.error("OpenAI API key is not set")
253
+ return None, None, None, "OpenAI API ํ‚ค๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. API ํ‚ค๋ฅผ ์„ค์ •ํ•ด์ฃผ์„ธ์š”."
254
+
255
+ # ์ข…ํšก๋น„๋ฅผ ํฌ๊ธฐ๋กœ ๋ณ€ํ™˜
256
+ size_mapping = {
257
+ "1:1": "1024x1024",
258
+ "3:2": "1536x1024",
259
+ "2:3": "1024x1536"
260
+ }
261
+ size = size_mapping.get(aspect_ratio, "1024x1024")
262
+
263
+ params = {
264
+ "prompt": prompt,
265
+ "model": "gpt-image-1",
266
+ "n": 1,
267
+ "size": size,
268
+ "image": processed_image
269
+ }
270
+
271
+ logger.info(f"Calling OpenAI API for image editing")
272
+ response = openai_client.images.edit(**params)
273
+ logger.info("OpenAI API call successful")
274
+
275
+ # ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ
276
+ for i, data in enumerate(response.data):
277
+ logger.info(f"Processing result image {i+1}/{len(response.data)}")
278
+
279
+ if hasattr(data, 'b64_json') and data.b64_json:
280
+ image_data = base64.b64decode(data.b64_json)
281
+ image = Image.open(io.BytesIO(image_data))
282
+ elif hasattr(data, 'url') and data.url:
283
+ response_url = requests.get(data.url)
284
+ image = Image.open(io.BytesIO(response_url.content))
285
+ else:
286
+ logger.warning(f"No image data found in response item {i+1}")
287
+ continue
288
+
289
+ # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
290
+ if output_format.lower() != "png" and image.mode == "RGBA":
291
+ background = Image.new("RGB", image.size, (255, 255, 255))
292
+ background.paste(image, mask=image.split()[3])
293
+ image = background
294
+
295
+ edited_images.append(image)
296
+
297
+ usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (GPT ๋ชจ๋ธ ์‚ฌ์šฉ)"
298
+
299
+ else: # quality_level == "flux"
300
+ # Flux ๋ชจ๋ธ ์‚ฌ์šฉ (ํ•ญ์ƒ ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  1ํšŒ ์ ์šฉ)
301
+ if not os.environ.get("REPLICATE_API_TOKEN"):
302
+ logger.error("Replicate API token is not set")
303
+ return None, None, None, "Replicate API ํ† ํฐ์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. API ํ† ํฐ์„ ์„ค์ •ํ•ด์ฃผ์„ธ์š”."
304
+
305
+ logger.info(f"Using Flux model for image editing")
306
+
307
+ # Flux ๋ชจ๋ธ๋กœ ์ด๋ฏธ์ง€ ์ƒ์„ฑ
308
+ output = replicate.run(
309
+ "black-forest-labs/flux-kontext-pro",
310
+ input={
311
+ "prompt": prompt,
312
+ "input_image": processed_image,
313
+ "output_format": output_format.lower(),
314
+ "aspect_ratio": aspect_ratio,
315
+ "safety_tolerance": 2
316
+ }
317
+ )
318
+
319
+ logger.info(f"Flux API response received")
320
+
321
+ # Flux API ์‘๋‹ต ์ฒ˜๋ฆฌ
322
+ flux_image = None
323
+ if output:
324
+ # output์ด ๋ฐ”์ดํŠธ ์ŠคํŠธ๋ฆผ์ธ ๊ฒฝ์šฐ
325
+ if hasattr(output, 'read'):
326
+ image_data = output.read()
327
+ flux_image = Image.open(io.BytesIO(image_data))
328
+ # output์ด URL์ธ ๊ฒฝ์šฐ
329
+ elif isinstance(output, str) and output.startswith('http'):
330
+ response_url = requests.get(output)
331
+ flux_image = Image.open(io.BytesIO(response_url.content))
332
+ # output์ด ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ์ธ ๊ฒฝ์šฐ
333
+ else:
334
+ flux_image = Image.open(io.BytesIO(output))
335
+
336
+ # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
337
+ if output_format.lower() != "png" and flux_image.mode == "RGBA":
338
+ background = Image.new("RGB", flux_image.size, (255, 255, 255))
339
+ background.paste(flux_image, mask=flux_image.split()[3])
340
+ flux_image = background
341
+
342
+ # Flux ๋ชจ๋ธ์€ ํ•ญ์ƒ ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ ๊ฐœ์„ ์„ ์ž๋™ ์ ์šฉ
343
+ try:
344
+ logger.info("Applying automatic first enhancement for Flux model")
345
+
346
+ # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ
347
+ temp_flux_path = tempfile.mktemp(suffix='.png')
348
+ flux_image.save(temp_flux_path)
349
+ temp_paths.append(temp_flux_path)
350
+
351
+ # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ ํ–ฅ์ƒ (Flux ๋ชจ๋ธ ๊ธฐ๋ณธ ์ ์šฉ)
352
+ first_enhanced_output = replicate.run(
353
+ "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
354
+ input={
355
+ "image": open(temp_flux_path, "rb"),
356
+ "scale_factor": 2,
357
+ "resemblance": 0.8,
358
+ "creativity": 0.2,
359
+ "output_format": output_format.lower(),
360
+ "prompt": prompt,
361
+ "negative_prompt": "(worst quality, low quality, normal quality:2)"
362
+ }
363
+ )
364
+
365
+ if first_enhanced_output and isinstance(first_enhanced_output, list) and len(first_enhanced_output) > 0:
366
+ first_enhanced_url = first_enhanced_output[0]
367
+ first_enhanced_response = requests.get(first_enhanced_url)
368
+
369
+ if first_enhanced_response.status_code == 200:
370
+ first_enhanced_image = Image.open(io.BytesIO(first_enhanced_response.content))
371
+
372
+ # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
373
+ if output_format.lower() != "png" and first_enhanced_image.mode == "RGBA":
374
+ background = Image.new("RGB", first_enhanced_image.size, (255, 255, 255))
375
+ background.paste(first_enhanced_image, mask=first_enhanced_image.split()[3])
376
+ first_enhanced_image = background
377
+
378
+ edited_images.append(first_enhanced_image)
379
+ usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ + ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์ ์šฉ)"
380
+ logger.info("First enhancement completed for Flux model")
381
+ else:
382
+ # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ ์‹œ ์›๋ณธ ์‚ฌ์šฉ
383
+ edited_images.append(flux_image)
384
+ usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ ์‚ฌ์šฉ, ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ)"
385
+ else:
386
+ # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ ์‹œ ์›๋ณธ ์‚ฌ์šฉ
387
+ edited_images.append(flux_image)
388
+ usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ ์‚ฌ์šฉ, ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ)"
389
+
390
+ except Exception as e:
391
+ logger.error(f"Error in first enhancement for Flux: {e}")
392
+ # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ ์‹œ ์›๋ณธ ์‚ฌ์šฉ
393
+ edited_images.append(flux_image)
394
+ usage_info = f"์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ ์‚ฌ์šฉ, ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์˜ค๋ฅ˜: {str(e)})"
395
+
396
+ else:
397
+ logger.error("No output from Flux API")
398
+ error_msg = "Flux API์—์„œ ์‘๋‹ต์„ ๋ฐ›์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."
399
+
400
+ except Exception as e:
401
+ if quality_level == "gpt":
402
+ logger.error(f"OpenAI API call error: {e}")
403
+ error_msg = f"OpenAI API ํ˜ธ์ถœ ์˜ค๋ฅ˜: {str(e)}"
404
+ else:
405
+ logger.error(f"Flux API call error: {e}")
406
+ error_msg = f"Flux API ํ˜ธ์ถœ ์˜ค๋ฅ˜: {str(e)}"
407
+
408
+ finally:
409
+ # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
410
+ if processed_image and hasattr(processed_image, 'close'):
411
+ processed_image.close()
412
+
413
+ # ํ™”์งˆ ํ–ฅ์ƒ ์ฒ˜๋ฆฌ (GPT ๋ชจ๋ธ์€ ์ผ๋ฐ˜์ ์ธ ํ™”์งˆ๊ฐœ์„ , Flux ๋ชจ๋ธ์€ 2์ฐจ ํ™”์งˆ๊ฐœ์„ )
414
+ enhanced_image = None
415
+ temp_image_path = None
416
+
417
+ if enable_enhancement and edited_images and not error_msg:
418
+ try:
419
+ if quality_level == "gpt":
420
+ # GPT ๋ชจ๋ธ: ์ผ๋ฐ˜์ ์ธ ํ™”์งˆ ๊ฐœ์„ 
421
+ logger.info(f"Enhancing GPT image with Replicate API, enhancement level: {enhancement_level}")
422
+ enhancement_info = "ํ™”์งˆ ๊ฐœ์„ "
423
+ else:
424
+ # Flux ๋ชจ๋ธ: 2์ฐจ ํ™”์งˆ ๊ฐœ์„  (์ด๋ฏธ 1์ฐจ๋Š” ์ ์šฉ๋จ)
425
+ logger.info(f"Applying second enhancement for Flux image, enhancement level: {enhancement_level}")
426
+ enhancement_info = "2์ฐจ ํ™”์งˆ ๊ฐœ์„ "
427
+
428
+ if not os.environ.get("REPLICATE_API_TOKEN"):
429
+ logger.error("Replicate API token is not set")
430
+ usage_info += f" | {enhancement_info} ์‹คํŒจ: Replicate API ํ† ํฐ์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."
431
+ else:
432
+ # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ
433
+ temp_image_path = tempfile.mktemp(suffix='.png')
434
+ edited_images[0].save(temp_image_path)
435
+ temp_paths.append(temp_image_path)
436
+
437
+ # Replicate API๋กœ ํ™”์งˆ ํ–ฅ์ƒ
438
+ output = replicate.run(
439
+ "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
440
+ input={
441
+ "image": open(temp_image_path, "rb"),
442
+ "scale_factor": enhancement_level,
443
+ "resemblance": 0.8,
444
+ "creativity": 0.2,
445
+ "output_format": output_format.lower(),
446
+ "prompt": prompt,
447
+ "negative_prompt": "(worst quality, low quality, normal quality:2)"
448
+ }
449
+ )
450
+
451
+ logger.info(f"Replicate API response: {output}")
452
+
453
+ if output and isinstance(output, list) and len(output) > 0:
454
+ enhanced_url = output[0]
455
+ enhanced_response = requests.get(enhanced_url)
456
+ if enhanced_response.status_code == 200:
457
+ enhanced_image = Image.open(io.BytesIO(enhanced_response.content))
458
+
459
+ if output_format.lower() != "png" and enhanced_image.mode == "RGBA":
460
+ background = Image.new("RGB", enhanced_image.size, (255, 255, 255))
461
+ background.paste(enhanced_image, mask=enhanced_image.split()[3])
462
+ enhanced_image = background
463
+
464
+ if quality_level == "gpt":
465
+ usage_info += f" | {enhancement_info} ์™„๋ฃŒ: Replicate Clarity Upscaler ์‚ฌ์šฉ"
466
+ else:
467
+ usage_info += f" | {enhancement_info} ์™„๋ฃŒ: ์ด 2ํšŒ ํ™”์งˆ๊ฐœ์„  ์ ์šฉ"
468
+ else:
469
+ usage_info += f" | {enhancement_info} ์‹คํŒจ: ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์˜ค๋ฅ˜"
470
+ else:
471
+ usage_info += f" | {enhancement_info} ์‹คํŒจ: Replicate API ์‘๋‹ต ์—†์Œ"
472
+
473
+ except Exception as e:
474
+ logger.error(f"Error enhancing image: {e}")
475
+ if quality_level == "gpt":
476
+ usage_info += f" | ํ™”์งˆ ๊ฐœ์„  ์‹คํŒจ: {str(e)}"
477
+ else:
478
+ usage_info += f" | 2์ฐจ ํ™”์งˆ ๊ฐœ์„  ์‹คํŒจ: {str(e)}"
479
+
480
+ # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
481
+ for path in temp_paths:
482
+ if os.path.exists(path):
483
+ try:
484
+ os.remove(path)
485
+ logger.info(f"Removed temp file: {path}")
486
+ except Exception as e:
487
+ logger.error(f"Error removing temp file {path}: {e}")
488
+
489
+ # ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
490
+ if error_msg:
491
+ return None, None, None, error_msg
492
+ elif edited_images:
493
+ if enable_enhancement and enhanced_image:
494
+ return edited_images, [enhanced_image], usage_info, None
495
+ else:
496
+ return edited_images, None, usage_info, None
497
+ else:
498
+ return None, None, None, "์ด๋ฏธ์ง€ ํŽธ์ง‘์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."
499
+
500
+ except Exception as e:
501
+ logger.error(f"Error in edit_and_enhance_image function: {e}")
502
+ logger.error(traceback.format_exc())
503
+ return None, None, None, f"์—๋Ÿฌ ๋ฐœ์ƒ: {str(e)}\n\n{traceback.format_exc()}"
504
+
505
+ # Gradio ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌ์„ฑ
506
+ def create_gradio_interface():
507
+ try:
508
+ logger.info("Creating Gradio interface")
509
+ with gr.Blocks(title="AI ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„ ") as app:
510
+ gr.Markdown("# AI ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ๋„๊ตฌ")
511
+
512
+ # ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ ํ•„๋“œ
513
+ password_box = gr.Textbox(
514
+ label="๋น„๋ฐ€๋ฒˆํ˜ธ",
515
+ type="password",
516
+ placeholder="์‚ฌ์šฉํ•˜๋ ค๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”",
517
+ interactive=True
518
+ )
519
+
520
+ # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ์ธํ„ฐํŽ˜์ด์Šค
521
+ with gr.Row():
522
+ with gr.Column():
523
+ # ์ƒํ’ˆ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ
524
+ image = gr.Image(label="์ƒํ’ˆ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ", type="pil")
525
+
526
+ with gr.Row():
527
+ with gr.Column():
528
+ background_type = gr.Radio(
529
+ choices=["์‹ฌํ”Œ ๋ฐฐ๊ฒฝ", "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ", "์ž์—ฐ ํ™˜๊ฒฝ", "์‹ค๋‚ด ํ™˜๊ฒฝ", "ํŠน์ˆ˜๋ฐฐ๊ฒฝ", "์ฃผ์–ผ๋ฆฌ", "ํŠน์ˆ˜ํšจ๊ณผ"],
530
+ label="๋ฐฐ๊ฒฝ ์œ ํ˜•",
531
+ value="์‹ฌํ”Œ ๋ฐฐ๊ฒฝ"
532
+ )
533
+
534
+ # ๋“œ๋กญ๋‹ค์šด ์ปดํฌ๋„ŒํŠธ๋“ค
535
+ simple_dropdown = gr.Dropdown(
536
+ choices=list(SIMPLE_BACKGROUNDS.keys()),
537
+ value=list(SIMPLE_BACKGROUNDS.keys())[0] if SIMPLE_BACKGROUNDS else None,
538
+ label="์‹ฌํ”Œ ๋ฐฐ๊ฒฝ ์„ ํƒ",
539
+ visible=True,
540
+ interactive=True
541
+ )
542
+
543
+ studio_dropdown = gr.Dropdown(
544
+ choices=list(STUDIO_BACKGROUNDS.keys()),
545
+ value=list(STUDIO_BACKGROUNDS.keys())[0] if STUDIO_BACKGROUNDS else None,
546
+ label="์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ ์„ ํƒ",
547
+ visible=False,
548
+ interactive=True
549
+ )
550
+
551
+ nature_dropdown = gr.Dropdown(
552
+ choices=list(NATURE_BACKGROUNDS.keys()),
553
+ value=list(NATURE_BACKGROUNDS.keys())[0] if NATURE_BACKGROUNDS else None,
554
+ label="์ž์—ฐ ํ™˜๊ฒฝ ์„ ํƒ",
555
+ visible=False,
556
+ interactive=True
557
+ )
558
+
559
+ indoor_dropdown = gr.Dropdown(
560
+ choices=list(INDOOR_BACKGROUNDS.keys()),
561
+ value=list(INDOOR_BACKGROUNDS.keys())[0] if INDOOR_BACKGROUNDS else None,
562
+ label="์‹ค๋‚ด ํ™˜๊ฒฝ ์„ ํƒ",
563
+ visible=False,
564
+ interactive=True
565
+ )
566
+
567
+ special_dropdown = gr.Dropdown(
568
+ choices=list(SPECIAL_BACKGROUNDS.keys()),
569
+ value=list(SPECIAL_BACKGROUNDS.keys())[0] if SPECIAL_BACKGROUNDS else None,
570
+ label="ํŠน์ˆ˜๋ฐฐ๊ฒฝ ์„ ํƒ",
571
+ visible=False,
572
+ interactive=True
573
+ )
574
+
575
+ jewelry_dropdown = gr.Dropdown(
576
+ choices=list(JEWELRY_BACKGROUNDS.keys()),
577
+ value=list(JEWELRY_BACKGROUNDS.keys())[0] if JEWELRY_BACKGROUNDS else None,
578
+ label="์ฃผ์–ผ๋ฆฌ ๋ฐฐ๊ฒฝ ์„ ํƒ",
579
+ visible=False,
580
+ interactive=True
581
+ )
582
+
583
+ special_effects_dropdown = gr.Dropdown(
584
+ choices=list(SPECIAL_EFFECTS_BACKGROUNDS.keys()),
585
+ value=list(SPECIAL_EFFECTS_BACKGROUNDS.keys())[0] if SPECIAL_EFFECTS_BACKGROUNDS else None,
586
+ label="ํŠน์ˆ˜ํšจ๊ณผ ๋ฐฐ๊ฒฝ ์„ ํƒ",
587
+ visible=False,
588
+ interactive=True
589
+ )
590
+
591
+ # ๋“œ๋กญ๋‹ค์šด ๋ณ€๊ฒฝ ํ•จ์ˆ˜
592
+ def update_dropdowns(bg_type):
593
+ return {
594
+ simple_dropdown: gr.update(visible=(bg_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ")),
595
+ studio_dropdown: gr.update(visible=(bg_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ")),
596
+ nature_dropdown: gr.update(visible=(bg_type == "์ž์—ฐ ํ™˜๊ฒฝ")),
597
+ indoor_dropdown: gr.update(visible=(bg_type == "์‹ค๋‚ด ํ™˜๊ฒฝ")),
598
+ special_dropdown: gr.update(visible=(bg_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ")),
599
+ jewelry_dropdown: gr.update(visible=(bg_type == "์ฃผ์–ผ๋ฆฌ")),
600
+ special_effects_dropdown: gr.update(visible=(bg_type == "ํŠน์ˆ˜ํšจ๊ณผ"))
601
+ }
602
+
603
+ background_type.change(
604
+ fn=update_dropdowns,
605
+ inputs=[background_type],
606
+ outputs=[simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown, jewelry_dropdown, special_effects_dropdown]
607
+ )
608
+
609
+ # ์š”์ฒญ์‚ฌํ•ญ ์ž…๋ ฅ
610
+ request_text = gr.Textbox(
611
+ label="์š”์ฒญ์‚ฌํ•ญ",
612
+ placeholder="์ƒํ’ˆ ์ด๋ฏธ์ง€์— ์ ์šฉํ•  ์Šคํƒ€์ผ, ๋ถ„์œ„๊ธฐ, ํŠน๋ณ„ ์š”์ฒญ๏ฟฝ๏ฟฝ๏ฟฝํ•ญ ๋“ฑ์„ ์ž…๋ ฅํ•˜์„ธ์š”.",
613
+ lines=3
614
+ )
615
+
616
+ # ์ƒˆ๋กœ์šด ์˜ต์…˜๋“ค
617
+ quality_level = gr.Radio(
618
+ label="ํ’ˆ์งˆ ๋ ˆ๋ฒจ",
619
+ choices=["gpt", "flux"],
620
+ value="flux",
621
+ info="GPT: GPT ๋ชจ๋ธ (๊ณ ํ’ˆ์งˆ), ์ผ๋ฐ˜: Flux ๋ชจ๋ธ (๋น ๋ฅธ ์ฒ˜๋ฆฌ + ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„ )"
622
+ )
623
+
624
+ aspect_ratio = gr.Dropdown(
625
+ label="์ข…ํšก๋น„",
626
+ choices=["1:1", "3:2", "2:3"],
627
+ value="1:1"
628
+ )
629
+
630
+ output_format = gr.Dropdown(
631
+ label="์ด๋ฏธ์ง€ ํ˜•์‹",
632
+ choices=["jpg", "png"],
633
+ value="jpg"
634
+ )
635
+
636
+ # ํ™”์งˆ ๊ฐœ์„  ์˜ต์…˜
637
+ enable_enhancement = gr.Checkbox(
638
+ label="์ถ”๊ฐ€ ํ™”์งˆ ๊ฐœ์„ ",
639
+ value=False,
640
+ info="GPT: 1ํšŒ ํ™”์งˆ๊ฐœ์„ , Flux: 2์ฐจ ํ™”์งˆ๊ฐœ์„  (๊ธฐ๋ณธ 1ํšŒ + ์ถ”๊ฐ€ 1ํšŒ)"
641
+ )
642
+ enhancement_level = gr.Slider(label="ํ™”์งˆ ๊ฐœ์„  ๋ ˆ๋ฒจ", minimum=1, maximum=4, value=2, step=1, visible=False)
643
+
644
+ # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ๋ฒ„ํŠผ
645
+ generate_prompt_btn = gr.Button("ํ”„๋กฌํ”„ํŠธ๋งŒ ์ƒ์„ฑ")
646
+
647
+ # ํŽธ์ง‘ ๋ฒ„ํŠผ
648
+ edit_btn = gr.Button("์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„ ")
649
+
650
+ with gr.Column():
651
+ with gr.Row():
652
+ with gr.Column():
653
+ gr.Markdown("## ํŽธ์ง‘๋œ ์ด๋ฏธ์ง€")
654
+ original_output = gr.Gallery(label="ํŽธ์ง‘ ๊ฒฐ๊ณผ", preview=True)
655
+ original_download = gr.File(label="ํŽธ์ง‘ ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ", interactive=False)
656
+
657
+ with gr.Column():
658
+ gr.Markdown("## ํ™”์งˆ ๊ฐœ์„ ๋œ ์ด๋ฏธ์ง€")
659
+ enhanced_output = gr.Gallery(label="ํ™”์งˆ ๊ฐœ์„  ๊ฒฐ๊ณผ", preview=True)
660
+ enhanced_download = gr.File(label="๊ฐœ์„  ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ", interactive=False)
661
+
662
+ # ํ”„๋กฌํ”„ํŠธ ์ถœ๋ ฅ
663
+ prompt_output = gr.Textbox(label="์ƒ์„ฑ๋œ ํ”„๋กฌํ”„ํŠธ", lines=10, interactive=False)
664
+ info = gr.Textbox(label="์ฒ˜๋ฆฌ ์ •๋ณด", interactive=False)
665
+ error = gr.Textbox(label="์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€", interactive=False, visible=True)
666
+
667
+ # ํ”„๋กฌํ”„ํŠธ๋งŒ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜ (๋น„๋ฐ€๋ฒˆํ˜ธ ์ฒดํฌ ํฌํ•จ)
668
+ def generate_prompt_with_password_check(password, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, aspect_ratio):
669
+ # ๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ
670
+ if password != APP_PASSWORD:
671
+ return "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค. ์˜ฌ๋ฐ”๋ฅธ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
672
+
673
+ # ๋ฐฐ๊ฒฝ ์„ ํƒ
674
+ background_name = ""
675
+ if bg_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ":
676
+ background_name = simple
677
+ elif bg_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ":
678
+ background_name = studio
679
+ elif bg_type == "์ž์—ฐ ํ™˜๊ฒฝ":
680
+ background_name = nature
681
+ elif bg_type == "์‹ค๋‚ด ํ™˜๊ฒฝ":
682
+ background_name = indoor
683
+ elif bg_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ":
684
+ background_name = special
685
+ elif bg_type == "์ฃผ์–ผ๋ฆฌ":
686
+ background_name = jewelry
687
+ elif bg_type == "ํŠน์ˆ˜ํšจ๊ณผ":
688
+ background_name = special_effects
689
+
690
+ # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ (์ข…ํšก๋น„ ํฌํ•จ)
691
+ prompt = generate_prompt(bg_type, background_name, request_text, aspect_ratio)
692
+ return prompt
693
+
694
+ # ๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ ํ•จ์ˆ˜
695
+ def check_password(password, *args):
696
+ if password != APP_PASSWORD:
697
+ return (
698
+ [], # original_output
699
+ None, # original_download
700
+ [], # enhanced_output
701
+ None, # enhanced_download
702
+ "", # prompt_output
703
+ "", # info
704
+ "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค. ์˜ฌ๋ฐ”๋ฅธ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”." # error
705
+ )
706
+
707
+ # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ์š”์ฒญ ์ฒ˜๋ฆฌ
708
+ image, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, quality_level, aspect_ratio, output_format, enable_enhancement = args
709
+
710
+ # ๋ฐฐ๊ฒฝ ์„ ํƒ
711
+ background_name = ""
712
+ if bg_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ":
713
+ background_name = simple
714
+ elif bg_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ":
715
+ background_name = studio
716
+ elif bg_type == "์ž์—ฐ ํ™˜๊ฒฝ":
717
+ background_name = nature
718
+ elif bg_type == "์‹ค๋‚ด ํ™˜๊ฒฝ":
719
+ background_name = indoor
720
+ elif bg_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ":
721
+ background_name = special
722
+ elif bg_type == "์ฃผ์–ผ๋ฆฌ":
723
+ background_name = jewelry
724
+ elif bg_type == "ํŠน์ˆ˜ํšจ๊ณผ":
725
+ background_name = special_effects
726
+
727
+ # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
728
+ prompt = generate_prompt(bg_type, background_name, request_text, aspect_ratio)
729
+
730
+ # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ์‹คํ–‰
731
+ original_images, enhanced_images, usage_info, error_msg = edit_and_enhance_image(
732
+ prompt, image, quality_level, aspect_ratio, output_format, enable_enhancement, 2
733
+ )
734
+
735
+ # ์ด๋ฏธ์ง€ ์ €์žฅ ๋ฐ ๋‹ค์šด๋กœ๋“œ ํŒŒ์ผ ์ค€๋น„
736
+ original_path = None
737
+ enhanced_path = None
738
+
739
+ if error_msg:
740
+ logger.error(f"Error returned from edit_and_enhance_image: {error_msg}")
741
+ return (
742
+ [], # original_output
743
+ None, # original_download
744
+ [], # enhanced_output
745
+ None, # enhanced_download
746
+ prompt, # prompt_output
747
+ "", # info
748
+ error_msg # error
749
+ )
750
+ else:
751
+ # ์›๋ณธ ํŽธ์ง‘ ์ด๋ฏธ์ง€ ์ €์žฅ
752
+ if original_images and len(original_images) > 0:
753
+ try:
754
+ original_path = f"original_image.{output_format}"
755
+ original_images[0].save(original_path)
756
+ logger.info(f"Saved original image to {original_path}")
757
+ except Exception as e:
758
+ logger.error(f"Error saving original image: {e}")
759
+
760
+ # ํ™”์งˆ ๊ฐœ์„  ์ด๋ฏธ์ง€ ์ €์žฅ
761
+ if enhanced_images and len(enhanced_images) > 0:
762
+ try:
763
+ enhanced_path = f"enhanced_image.{output_format}"
764
+ enhanced_images[0].save(enhanced_path)
765
+ logger.info(f"Saved enhanced image to {enhanced_path}")
766
+ except Exception as e:
767
+ logger.error(f"Error saving enhanced image: {e}")
768
+
769
+ # ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
770
+ return (
771
+ original_images if original_images else [], # original_output
772
+ original_path, # original_download
773
+ enhanced_images if enhanced_images else [], # enhanced_output
774
+ enhanced_path, # enhanced_download
775
+ prompt, # prompt_output
776
+ usage_info, # info
777
+ "" # error (๋นˆ ๋ฌธ์ž์—ด๋กœ ์„ค์ •)
778
+ )
779
+
780
+ # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ
781
+ generate_prompt_btn.click(
782
+ fn=generate_prompt_with_password_check,
783
+ inputs=[
784
+ password_box,
785
+ background_type,
786
+ simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown,
787
+ jewelry_dropdown, special_effects_dropdown,
788
+ request_text, aspect_ratio
789
+ ],
790
+ outputs=[prompt_output]
791
+ )
792
+
793
+ # ํŽธ์ง‘ ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ
794
+ edit_btn.click(
795
+ fn=check_password,
796
+ inputs=[
797
+ password_box,
798
+ image, background_type,
799
+ simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown,
800
+ jewelry_dropdown, special_effects_dropdown,
801
+ request_text, quality_level, aspect_ratio, output_format, enable_enhancement
802
+ ],
803
+ outputs=[
804
+ original_output, original_download,
805
+ enhanced_output, enhanced_download,
806
+ prompt_output, info, error
807
+ ]
808
+ )
809
+
810
+ logger.info("Gradio interface created successfully")
811
+ return app
812
+ except Exception as e:
813
+ logger.error(f"Error creating Gradio interface: {e}")
814
+ logger.error(traceback.format_exc())
815
+ raise
816
+
817
+ # ์•ฑ ๏ฟฝ๏ฟฝํ–‰
818
+ if __name__ == "__main__":
819
+ try:
820
+ logger.info("Starting application")
821
+
822
+ # imgs ๋””๋ ‰ํ† ๋ฆฌ ํ™•์ธ/์ƒ์„ฑ
823
+ os.makedirs("imgs", exist_ok=True)
824
+ logger.info("์ด๋ฏธ์ง€ ๋””๋ ‰ํ† ๋ฆฌ ์ค€๋น„ ์™„๋ฃŒ")
825
+
826
+ app = create_gradio_interface()
827
+ logger.info("Launching Gradio app")
828
+ app.launch(share=True)
829
+ except Exception as e:
830
+ logger.error(f"Error running app: {e}")
831
+ logger.error(traceback.format_exc())