File size: 26,599 Bytes
97d75c9
 
 
 
 
 
 
 
fa60eff
97d75c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import gradio as gr
import replicate
from PIL import Image
from google import genai
from google.genai import types
import io
import base64
import tempfile
import os
import uuid
import requests
from io import BytesIO
import time
import json
import datetime

# ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ API ํ† ํฐ๊ณผ ๋น„๋ฐ€๋ฒˆํ˜ธ ๊ฐ€์ ธ์˜ค๊ธฐ
REPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
PASSWORD = os.getenv("APP_PASSWORD")  # ๊ธฐ๋ณธ๊ฐ’ ์„ค์ •

# API ํ‚ค ๊ฒ€์ฆ
def validate_api_keys():
    """API ํ‚ค๋“ค์ด ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์„ค์ •๋˜์—ˆ๋Š”์ง€ ํ™•์ธ"""
    missing_keys = []
    
    if not REPLICATE_API_TOKEN:
        missing_keys.append("REPLICATE_API_TOKEN")
    
    if not GEMINI_API_KEY:
        missing_keys.append("GEMINI_API_KEY")
    
    if missing_keys:
        error_msg = f"๋‹ค์Œ ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค: {', '.join(missing_keys)}"
        raise ValueError(error_msg)
    
    return True

def log_message(message, log_list=None):
    """๋กœ๊ทธ ๋ฉ”์‹œ์ง€๋ฅผ ํƒ€์ž„์Šคํƒฌํ”„์™€ ํ•จ๊ป˜ ๊ธฐ๋ก"""
    timestamp = datetime.datetime.now().strftime("%H:%M:%S")
    formatted_message = f"[{timestamp}] {message}"
    print(formatted_message)  # ์ฝ˜์†”์—๋„ ์ถœ๋ ฅ
    if log_list is not None:
        log_list.append(formatted_message)
    return formatted_message

def translate_to_english(korean_prompt, log_list):
    """ํ•œ๊ตญ์–ด ํ”„๋กฌํ”„ํŠธ๋ฅผ FLUX ์ด๋ฏธ์ง€ ์ƒ์„ฑ์— ์ตœ์ ํ™”๋œ ์˜์–ด๋กœ ๋ฒˆ์—ญ"""
    log_message("=== ๋ฒˆ์—ญ ํ”„๋กœ์„ธ์Šค ์‹œ์ž‘ ===", log_list)
    log_message(f"์ž…๋ ฅ๋œ ํ•œ๊ตญ์–ด ํ”„๋กฌํ”„ํŠธ: '{korean_prompt}'", log_list)
    
    try:
        log_message("Gemini API ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์‹œ์ž‘...", log_list)
        client = genai.Client(api_key=GEMINI_API_KEY)
        log_message("Gemini API ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ", log_list)
        
        system_instruction = """You are a professional prompt translator for FLUX image generation models. 
        Translate Korean image editing prompts to optimized English prompts that work best with FLUX models.
        Keep the translation:
        - Clear and specific
        - Descriptive but concise
        - Focused on visual elements
        - Suitable for AI image generation
        
        Only return the translated English prompt, nothing else."""
        
        log_message("๋ฒˆ์—ญ ์š”์ฒญ ์ค€๋น„ ์™„๋ฃŒ", log_list)
        log_message("Gemini API ํ˜ธ์ถœ ์‹œ์ž‘...", log_list)
        
        start_time = time.time()
        response = client.models.generate_content(
            model="gemini-2.0-flash",
            config=types.GenerateContentConfig(
                system_instruction=system_instruction,
                temperature=0.3
            ),
            contents=[f"Translate this Korean prompt to English for FLUX image editing: {korean_prompt}"]
        )
        end_time = time.time()
        
        log_message(f"Gemini API ์‘๋‹ต ์ˆ˜์‹  ์™„๋ฃŒ (์†Œ์š”์‹œ๊ฐ„: {end_time - start_time:.2f}์ดˆ)", log_list)
        
        translated_text = response.text.strip()
        log_message(f"๋ฒˆ์—ญ ๊ฒฐ๊ณผ: '{translated_text}'", log_list)
        log_message("=== ๋ฒˆ์—ญ ํ”„๋กœ์„ธ์Šค ์™„๋ฃŒ ===", log_list)
        
        return translated_text
        
    except Exception as e:
        error_msg = f"๋ฒˆ์—ญ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
        log_message(error_msg, log_list)
        log_message("์›๋ณธ ํ•œ๊ตญ์–ด ํ”„๋กฌํ”„ํŠธ๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค", log_list)
        log_message("=== ๋ฒˆ์—ญ ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
        return korean_prompt

def upscale_image(image_path, output_format, english_prompt, log_list):
    """Clarity Upscaler๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฏธ์ง€ ์—…์Šค์ผ€์ผ๋ง (๋ชจ๋“  ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ณ ์ •)"""
    log_message("=== ํ™”์งˆ ๊ฐœ์„ (์—…์Šค์ผ€์ผ๋ง) ํ”„๋กœ์„ธ์Šค ์‹œ์ž‘ ===", log_list)
    log_message(f"์ž…๋ ฅ ์ด๋ฏธ์ง€ ๊ฒฝ๋กœ: {image_path}", log_list)
    log_message(f"์ถœ๋ ฅ ํฌ๋งท: {output_format}", log_list)
    log_message(f"์‚ฌ์šฉํ•  ํ”„๋กฌํ”„ํŠธ: '{english_prompt}'", log_list)
    
    try:
        # ํŒŒ์ผ ์กด์žฌ ํ™•์ธ
        if not os.path.exists(image_path):
            error_msg = f"์ž…๋ ฅ ์ด๋ฏธ์ง€ ํŒŒ์ผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค: {image_path}"
            log_message(error_msg, log_list)
            return None
            
        # ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
        file_size = os.path.getsize(image_path)
        log_message(f"์ž…๋ ฅ ํŒŒ์ผ ํฌ๊ธฐ: {file_size} bytes ({file_size/1024/1024:.2f} MB)", log_list)
        
        log_message("Replicate API ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์‹œ์ž‘...", log_list)
        client = replicate.Client(api_token=REPLICATE_API_TOKEN)
        log_message("Replicate API ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ", log_list)
        
        log_message("์ด๋ฏธ์ง€ ํŒŒ์ผ ์ฝ๊ธฐ ์‹œ์ž‘...", log_list)
        with open(image_path, "rb") as file:
            log_message("์ด๋ฏธ์ง€ ํŒŒ์ผ ์ฝ๊ธฐ ์™„๋ฃŒ", log_list)
            
            # ์—…์Šค์ผ€์ผ ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •
            input_data = {
                "image": file,
                "scale_factor": 2,  # ๊ณ ์ •: 2๋ฐฐ ํ™•๋Œ€
                "resemblance": 0.8,  # ๊ณ ์ •: ๋†’์€ ์›๋ณธ ์œ ์‚ฌ๋„
                "creativity": 0.2,   # ๊ณ ์ •: ๋‚ฎ์€ ์ฐฝ์˜์„ฑ
                "output_format": output_format.lower(),
                "prompt": english_prompt,
                "negative_prompt": "(worst quality, low quality, normal quality:2)"
            }
            
            log_message("์—…์Šค์ผ€์ผ ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •:", log_list)
            log_message(f"  - scale_factor: 2", log_list)
            log_message(f"  - resemblance: 0.8", log_list)
            log_message(f"  - creativity: 0.2", log_list)
            log_message(f"  - output_format: {output_format.lower()}", log_list)
            log_message(f"  - negative_prompt: (worst quality, low quality, normal quality:2)", log_list)
            
            log_message("Clarity Upscaler API ํ˜ธ์ถœ ์‹œ์ž‘...", log_list)
            log_message("๋ชจ๋ธ: philz1337x/clarity-upscaler", log_list)
            
            start_time = time.time()
            try:
                output = client.run(
                    "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
                    input=input_data
                )
                end_time = time.time()
                log_message(f"Clarity Upscaler API ์‘๋‹ต ์ˆ˜์‹  ์™„๋ฃŒ (์†Œ์š”์‹œ๊ฐ„: {end_time - start_time:.2f}์ดˆ)", log_list)
                
            except Exception as api_error:
                error_msg = f"Clarity Upscaler API ํ˜ธ์ถœ ์‹คํŒจ: {str(api_error)}"
                log_message(error_msg, log_list)
                log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
                return None
        
        # API ์‘๋‹ต ๊ฒ€์ฆ
        log_message(f"API ์‘๋‹ต ํƒ€์ž…: {type(output)}", log_list)
        log_message(f"API ์‘๋‹ต ๋‚ด์šฉ: {output}", log_list)
        
        # ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ
        if output and isinstance(output, list) and len(output) > 0:
            result_url = output[0]
            log_message(f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ URL: {result_url}", log_list)
            log_message("๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์‹œ์ž‘...", log_list)
            
            try:
                download_start = time.time()
                response = requests.get(result_url, timeout=30)
                download_end = time.time()
                
                log_message(f"๋‹ค์šด๋กœ๋“œ ์‘๋‹ต ์ƒํƒœ: {response.status_code}", log_list)
                log_message(f"๋‹ค์šด๋กœ๋“œ ์†Œ์š”์‹œ๊ฐ„: {download_end - download_start:.2f}์ดˆ", log_list)
                log_message(f"๋‹ค์šด๋กœ๋“œ๋œ ๋ฐ์ดํ„ฐ ํฌ๊ธฐ: {len(response.content)} bytes ({len(response.content)/1024/1024:.2f} MB)", log_list)
                
                if response.status_code == 200:
                    log_message("์ด๋ฏธ์ง€ ๋ฐ์ดํ„ฐ๋ฅผ PIL Image๋กœ ๋ณ€ํ™˜ ์ค‘...", log_list)
                    result_image = Image.open(BytesIO(response.content))
                    log_message(f"๋ณ€ํ™˜๋œ ์ด๋ฏธ์ง€ ํฌ๊ธฐ: {result_image.size}", log_list)
                    log_message(f"๋ณ€ํ™˜๋œ ์ด๋ฏธ์ง€ ๋ชจ๋“œ: {result_image.mode}", log_list)
                    
                    # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ
                    ext = output_format.lower()
                    upscaled_filename = f"upscaled_temp_{uuid.uuid4()}.{ext}"
                    log_message(f"์—…์Šค์ผ€์ผ๋œ ์ด๋ฏธ์ง€ ์ €์žฅ ํŒŒ์ผ๋ช…: {upscaled_filename}", log_list)
                    
                    # RGBA ๋ชจ๋“œ ์ฒ˜๋ฆฌ
                    if ext == 'jpg' and result_image.mode == 'RGBA':
                        log_message("RGBA ๋ชจ๋“œ๋ฅผ RGB๋กœ ๋ณ€ํ™˜ ์ค‘ (JPG ์ €์žฅ์„ ์œ„ํ•ด)...", log_list)
                        result_image = result_image.convert('RGB')
                    
                    # ์ด๋ฏธ์ง€ ์ €์žฅ
                    save_start = time.time()
                    if ext == 'jpg':
                        result_image.save(upscaled_filename, format='JPEG', quality=95)
                    else:
                        result_image.save(upscaled_filename, format='PNG')
                    save_end = time.time()
                    
                    log_message(f"์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ (์†Œ์š”์‹œ๊ฐ„: {save_end - save_start:.2f}์ดˆ)", log_list)
                    
                    # ์ €์žฅ๋œ ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
                    saved_size = os.path.getsize(upscaled_filename)
                    log_message(f"์ €์žฅ๋œ ํŒŒ์ผ ํฌ๊ธฐ: {saved_size} bytes ({saved_size/1024/1024:.2f} MB)", log_list)
                    
                    log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์™„๋ฃŒ ===", log_list)
                    return upscaled_filename
                else:
                    error_msg = f"์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์‹คํŒจ - HTTP ์ƒํƒœ: {response.status_code}"
                    log_message(error_msg, log_list)
                    log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
                    return None
                    
            except requests.exceptions.Timeout:
                log_message("์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ํƒ€์ž„์•„์›ƒ (30์ดˆ)", log_list)
                log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
                return None
            except Exception as download_error:
                error_msg = f"์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜: {str(download_error)}"
                log_message(error_msg, log_list)
                log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
                return None
        else:
            log_message("API ์‘๋‹ต์ด ๋น„์–ด์žˆ๊ฑฐ๋‚˜ ์˜ˆ์ƒ ํ˜•์‹๊ณผ ๋‹ค๋ฆ…๋‹ˆ๋‹ค", log_list)
            if output:
                log_message(f"์‹ค์ œ ์‘๋‹ต: {json.dumps(output, indent=2) if isinstance(output, dict) else str(output)}", log_list)
            log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
            return None
        
    except Exception as e:
        error_msg = f"์—…์Šค์ผ€์ผ๋ง ํ”„๋กœ์„ธ์Šค ์ค‘ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜: {str(e)}"
        log_message(error_msg, log_list)
        log_message("=== ํ™”์งˆ ๊ฐœ์„  ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
        return None

def edit_image(input_image, password, korean_prompt, output_format, aspect_ratio, upscale_option, current_images, current_downloads):
    log_list = []
    log_message("=" * 60, log_list)
    log_message("์ƒˆ๋กœ์šด ์ด๋ฏธ์ง€ ํŽธ์ง‘ ์ž‘์—… ์‹œ์ž‘", log_list)
    log_message("=" * 60, log_list)
    
    # API ํ‚ค ๊ฒ€์ฆ
    try:
        validate_api_keys()
        log_message("API ํ‚ค ๊ฒ€์ฆ ์™„๋ฃŒ", log_list)
    except ValueError as e:
        error_msg = str(e)
        log_message(f"API ํ‚ค ๊ฒ€์ฆ ์‹คํŒจ: {error_msg}", log_list)
        return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
    
    # ์ž…๋ ฅ ๊ฒ€์ฆ
    log_message("=== ์ž…๋ ฅ ๊ฒ€์ฆ ๋‹จ๊ณ„ ===", log_list)
    
    if not password:
        error_msg = "๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."
        log_message(f"๊ฒ€์ฆ ์‹คํŒจ: {error_msg}", log_list)
        return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
    
    if password != PASSWORD:
        error_msg = "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."
        log_message(f"๊ฒ€์ฆ ์‹คํŒจ: {error_msg}", log_list)
        return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
    
    log_message("๋น„๋ฐ€๋ฒˆํ˜ธ ๊ฒ€์ฆ ํ†ต๊ณผ", log_list)
    
    if input_image is None:
        error_msg = "์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•˜์„ธ์š”."
        log_message(f"๊ฒ€์ฆ ์‹คํŒจ: {error_msg}", log_list)
        return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
    
    log_message(f"์ž…๋ ฅ ์ด๋ฏธ์ง€ ๊ฒฝ๋กœ: {input_image}", log_list)
    
    if not korean_prompt.strip():
        error_msg = "ํŽธ์ง‘ ์ง€์‹œ์‚ฌํ•ญ์„ ์ž…๋ ฅํ•˜์„ธ์š”."
        log_message(f"๊ฒ€์ฆ ์‹คํŒจ: {error_msg}", log_list)
        return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
    
    log_message(f"ํŽธ์ง‘ ์ง€์‹œ์‚ฌํ•ญ: '{korean_prompt.strip()}'", log_list)
    log_message(f"์ถœ๋ ฅ ํฌ๋งท: {output_format}", log_list)
    log_message(f"ํ™”๋ฉด ๋น„์œจ: {aspect_ratio}", log_list)
    log_message(f"ํ™”์งˆ ๊ฐœ์„  ์˜ต์…˜: {upscale_option}", log_list)
    log_message("๋ชจ๋“  ์ž…๋ ฅ ๊ฒ€์ฆ ํ†ต๊ณผ", log_list)
    
    try:
        # Replicate ํด๋ผ์ด์–ธํŠธ ์„ค์ •
        log_message("=== Replicate ์„ค์ • ๋‹จ๊ณ„ ===", log_list)
        log_message("Replicate ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์‹œ์ž‘...", log_list)
        client = replicate.Client(api_token=REPLICATE_API_TOKEN)
        log_message("Replicate ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ", log_list)
        
        # ํ•œ๊ตญ์–ด ํ”„๋กฌํ”„ํŠธ๋ฅผ ์˜์–ด๋กœ ๋ฒˆ์—ญ
        english_prompt = translate_to_english(korean_prompt, log_list)
        
        # ์ž…๋ ฅ ์ด๋ฏธ์ง€ ์ •๋ณด ํ™•์ธ
        log_message("=== ์ž…๋ ฅ ์ด๋ฏธ์ง€ ๋ถ„์„ ===", log_list)
        try:
            with Image.open(input_image) as img:
                log_message(f"์ด๋ฏธ์ง€ ํฌ๊ธฐ: {img.size}", log_list)
                log_message(f"์ด๋ฏธ์ง€ ๋ชจ๋“œ: {img.mode}", log_list)
                log_message(f"์ด๋ฏธ์ง€ ํฌ๋งท: {img.format}", log_list)
        except Exception as img_error:
            log_message(f"์ด๋ฏธ์ง€ ์ •๋ณด ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(img_error)}", log_list)
        
        # ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
        file_size = os.path.getsize(input_image)
        log_message(f"์ž…๋ ฅ ํŒŒ์ผ ํฌ๊ธฐ: {file_size} bytes ({file_size/1024/1024:.2f} MB)", log_list)
        
        # FLUX ์ด๋ฏธ์ง€ ํŽธ์ง‘ ์‹œ์ž‘
        log_message("=== FLUX ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋‹จ๊ณ„ ===", log_list)
        log_message("์ด๋ฏธ์ง€ ํŒŒ์ผ ์ฝ๊ธฐ ์‹œ์ž‘...", log_list)
        
        with open(input_image, "rb") as file:
            input_file = file
            log_message("ํŒŒ์ผ ์ฝ๊ธฐ ์™„๋ฃŒ", log_list)
            
            # Replicate API ํ˜ธ์ถœ ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •
            input_data = {
                "prompt": english_prompt,
                "input_image": input_file,
                "output_format": output_format.lower(),
                "aspect_ratio": aspect_ratio
            }
            
            
            flux_start_time = time.time()
            try:
                output = client.run(
                    "black-forest-labs/flux-kontext-pro",
                    input=input_data
                )
                flux_end_time = time.time()
                log_message(f"FLUX API ์‘๋‹ต ์ˆ˜์‹  ์™„๋ฃŒ (์†Œ์š”์‹œ๊ฐ„: {flux_end_time - flux_start_time:.2f}์ดˆ)", log_list)
                
            except Exception as flux_error:
                error_msg = f"FLUX API ํ˜ธ์ถœ ์‹คํŒจ: {str(flux_error)}"
                log_message(error_msg, log_list)
                return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
        
        log_message(f"FLUX API ์‘๋‹ต ํƒ€์ž…: {type(output)}", log_list)
        
        # ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ
        log_message("=== ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ ๋‹จ๊ณ„ ===", log_list)
        temp_filename = f"temp_output_{uuid.uuid4()}.{output_format.lower()}"
        log_message(f"์ž„์‹œ ํŒŒ์ผ๋ช…: {temp_filename}", log_list)
        
        try:
            log_message("๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ €์žฅ ์‹œ์ž‘...", log_list)
            with open(temp_filename, "wb") as file:
                file.write(output.read())
            
            # ์ €์žฅ๋œ ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
            saved_size = os.path.getsize(temp_filename)
            log_message(f"FLUX ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ", log_list)
            log_message(f"์ €์žฅ๋œ ํŒŒ์ผ ํฌ๊ธฐ: {saved_size} bytes ({saved_size/1024/1024:.2f} MB)", log_list)
            
        except Exception as save_error:
            error_msg = f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ €์žฅ ์‹คํŒจ: {str(save_error)}"
            log_message(error_msg, log_list)
            return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
        
        # ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ๋กœ๋“œ
        try:
            log_message("๊ฒฐ๊ณผ ์ด๋ฏธ์ง€๋ฅผ PIL Image๋กœ ๋กœ๋“œ ์ค‘...", log_list)
            result_image = Image.open(temp_filename)
            log_message(f"๋กœ๋“œ๋œ ์ด๋ฏธ์ง€ ํฌ๊ธฐ: {result_image.size}", log_list)
            log_message(f"๋กœ๋“œ๋œ ์ด๋ฏธ์ง€ ๋ชจ๋“œ: {result_image.mode}", log_list)
            
        except Exception as load_error:
            error_msg = f"๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ๋กœ๋“œ ์‹คํŒจ: {str(load_error)}"
            log_message(error_msg, log_list)
            return None, None, "\n".join(log_list) + f"\n์˜ค๋ฅ˜: {error_msg}", current_images, current_downloads
        
        # ์—…์Šค์ผ€์ผ๋ง ์ ์šฉ (์„ ํƒ์‚ฌํ•ญ)
        final_image = result_image
        if upscale_option == "์ ์šฉ":
            upscaled_path = upscale_image(temp_filename, output_format, english_prompt, log_list)
            
            if upscaled_path:
                try:
                    log_message("์—…์Šค์ผ€์ผ๋œ ์ด๋ฏธ์ง€ ๋กœ๋“œ ์ค‘...", log_list)
                    final_image = Image.open(upscaled_path)
                    log_message(f"์ตœ์ข… ์ด๋ฏธ์ง€ ํฌ๊ธฐ: {final_image.size}", log_list)
                    log_message("ํ™”์งˆ ๊ฐœ์„ ์ด ์„ฑ๊ณต์ ์œผ๋กœ ์ ์šฉ๋˜์—ˆ์Šต๋‹ˆ๋‹ค", log_list)
                    
                    # ์—…์Šค์ผ€์ผ ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
                    try:
                        os.remove(upscaled_path)
                        log_message("์—…์Šค์ผ€์ผ ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ ์™„๋ฃŒ", log_list)
                    except:
                        pass
                        
                except Exception as upscale_load_error:
                    log_message(f"์—…์Šค์ผ€์ผ๋œ ์ด๋ฏธ์ง€ ๋กœ๋“œ ์‹คํŒจ: {str(upscale_load_error)}", log_list)
                    log_message("์›๋ณธ FLUX ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค", log_list)
            else:
                log_message("ํ™”์งˆ ๊ฐœ์„  ์‹คํŒจ - ์›๋ณธ FLUX ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค", log_list)
        else:
            log_message("ํ™”์งˆ ๊ฐœ์„  ์˜ต์…˜์ด ์„ ํƒ๋˜์ง€ ์•Š์Œ - ์›๋ณธ FLUX ๊ฒฐ๊ณผ ์‚ฌ์šฉ", log_list)
        
        # ์ž๋™ ์ €์žฅ ์ฒ˜๋ฆฌ
        log_message("=== ๊ฒฐ๊ณผ ์ €์žฅ ๋‹จ๊ณ„ ===", log_list)
        
        if current_images is None:
            current_images = []
        if current_downloads is None:
            current_downloads = []
        
        # ๊ฐค๋Ÿฌ๋ฆฌ์šฉ ์ž„์‹œ ํŒŒ์ผ ์ƒ์„ฑ
        gallery_temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
        final_image.save(gallery_temp_file.name, 'png')
        current_images.append(gallery_temp_file.name)
        log_message(f"๊ฐค๋Ÿฌ๋ฆฌ์šฉ ์ด๋ฏธ์ง€ ์ €์žฅ: {gallery_temp_file.name}", log_list)
        
        # ๋‹ค์šด๋กœ๋“œ์šฉ ํŒŒ์ผ ์ƒ์„ฑ
        download_filename = f"edited_image_{len(current_downloads) + 1}.{output_format.lower()}"
        final_image.save(download_filename)
        current_downloads.append(download_filename)
        log_message(f"๋‹ค์šด๋กœ๋“œ์šฉ ์ด๋ฏธ์ง€ ์ €์žฅ: {download_filename}", log_list)
        
        # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        try:
            os.remove(temp_filename)
            log_message("FLUX ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ ์™„๋ฃŒ", log_list)
        except:
            pass
        
        log_message("=" * 60, log_list)
        log_message("์ด๋ฏธ์ง€ ํŽธ์ง‘ ์ž‘์—… ์„ฑ๊ณต์ ์œผ๋กœ ์™„๋ฃŒ!", log_list)
        log_message("=" * 60, log_list)
        
        return final_image, current_downloads, "\n".join(log_list), current_images, current_downloads
        
    except Exception as e:
        error_msg = f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
        log_message(error_msg, log_list)
        log_message("=" * 60, log_list)
        log_message("์ด๋ฏธ์ง€ ํŽธ์ง‘ ์ž‘์—… ์‹คํŒจ", log_list)
        log_message("=" * 60, log_list)
        return None, current_downloads, "\n".join(log_list), current_images, current_downloads

def save_output_as_input(output_image, current_images, current_downloads):
    """์ถœ๋ ฅ ์ด๋ฏธ์ง€๋ฅผ ์ž…๋ ฅ์œผ๋กœ ์ €์žฅ"""
    log_list = []
    log_message("=== ์ถœ๋ ฅ ์ด๋ฏธ์ง€๋ฅผ ์ž…๋ ฅ์œผ๋กœ ์ €์žฅ ์‹œ์ž‘ ===", log_list)
    
    if output_image is None:
        log_message("์ €์žฅํ•  ์ถœ๋ ฅ ์ด๋ฏธ์ง€๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค", log_list)
        return None, current_images, current_downloads
    
    try:
        log_message(f"์ถœ๋ ฅ ์ด๋ฏธ์ง€ ํƒ€์ž…: {type(output_image)}", log_list)
        
        # numpy array๋ฅผ PIL Image๋กœ ๋ณ€ํ™˜
        if hasattr(output_image, 'shape'):  # numpy array์ธ ๊ฒฝ์šฐ
            log_message("numpy array๋ฅผ PIL Image๋กœ ๋ณ€ํ™˜ ์ค‘...", log_list)
            output_image = Image.fromarray(output_image)
        
        log_message(f"๋ณ€ํ™˜๋œ ์ด๋ฏธ์ง€ ํฌ๊ธฐ: {output_image.size}", log_list)
        log_message(f"๋ณ€ํ™˜๋œ ์ด๋ฏธ์ง€ ๋ชจ๋“œ: {output_image.mode}", log_list)
        
        # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ (์ž…๋ ฅ์šฉ)
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
        output_image.save(temp_file.name, 'png')
        
        file_size = os.path.getsize(temp_file.name)
        log_message(f"์ž…๋ ฅ์šฉ ์ด๋ฏธ์ง€ ์ €์žฅ ์™„๋ฃŒ: {temp_file.name}", log_list)
        log_message(f"์ €์žฅ๋œ ํŒŒ์ผ ํฌ๊ธฐ: {file_size} bytes ({file_size/1024/1024:.2f} MB)", log_list)
        log_message("=== ์ €์žฅ ํ”„๋กœ์„ธ์Šค ์™„๋ฃŒ ===", log_list)
        
        print("\n".join(log_list))  # ์ฝ˜์†”์— ๋กœ๊ทธ ์ถœ๋ ฅ
        return temp_file.name, current_images, current_downloads
        
    except Exception as e:
        error_msg = f"์ด๋ฏธ์ง€ ์ €์žฅ ์ค‘ ์˜ค๋ฅ˜: {str(e)}"
        log_message(error_msg, log_list)
        log_message("=== ์ €์žฅ ํ”„๋กœ์„ธ์Šค ์‹คํŒจ ===", log_list)
        print("\n".join(log_list))  # ์ฝ˜์†”์— ๋กœ๊ทธ ์ถœ๋ ฅ
        return None, current_images, current_downloads

# ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‹œ์ž‘ ์‹œ API ํ‚ค ํ™•์ธ
try:
    validate_api_keys()
    print("โœ… ๋ชจ๋“  API ํ‚ค๊ฐ€ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์„ค์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
except ValueError as e:
    print(f"โŒ {e}")

# Gradio ์ธํ„ฐํŽ˜์ด์Šค
with gr.Blocks(title="์ด๋ฏธ์ง€ ํŽธ์ง‘๊ธฐ (๋ณด์•ˆ ๊ฐ•ํ™” ๋ฒ„์ „)") as demo:
    # ์ƒํƒœ ๋ณ€์ˆ˜๋“ค
    saved_images = gr.State([])
    saved_downloads = gr.State([])
    
    gr.Markdown("# ๐ŸŽจ AI ์ด๋ฏธ์ง€ ํŽธ์ง‘๊ธฐ (๋ณด์•ˆ ๊ฐ•ํ™” ๋ฒ„์ „)")
    
    with gr.Row():
        with gr.Column():
            input_image = gr.Image(type="filepath", label="๐Ÿ“ค ์ž…๋ ฅ ์ด๋ฏธ์ง€")
            password = gr.Textbox(
                label="๐Ÿ” ๋น„๋ฐ€๋ฒˆํ˜ธ", 
                type="password",
                placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”"
            )
            korean_prompt = gr.Textbox(
                label="โœ๏ธ ํŽธ์ง‘ ์ง€์‹œ์‚ฌํ•ญ (ํ•œ๊ตญ์–ด)",
                placeholder="์˜ˆ: ์ด ์‚ฌ๋žŒ์„ ๋งŒํ™” ์บ๋ฆญํ„ฐ๋กœ ๋ฐ”๊ฟ”์ค˜",
                lines=3
            )
            
            with gr.Row():
                output_format = gr.Radio(
                    choices=["jpg", "png"],
                    value="jpg",
                    label="๐Ÿ“ ์ถœ๋ ฅ ํฌ๋งท"
                )
                aspect_ratio = gr.Dropdown(
                    choices=["match_input_image", "1:1", "3:2", "2:3"],
                    value="match_input_image",
                    label="๐Ÿ“ ํ™”๋ฉด ๋น„์œจ"
                )
            
            upscale_option = gr.Radio(
                choices=["์—†์Œ", "์ ์šฉ"],
                value="์—†์Œ",
                label="๐Ÿ” ํ™”์งˆ ๊ฐœ์„  (2๋ฐฐ ํ™•๋Œ€)"
            )
            
            edit_btn = gr.Button("๐Ÿš€ ์ด๋ฏธ์ง€ ํŽธ์ง‘", variant="primary", size="lg")
        
        with gr.Column():
            output_image = gr.Image(label="โœจ ํŽธ์ง‘๋œ ์ด๋ฏธ์ง€")
            log_output = gr.Textbox(
                label="๐Ÿ“‹ ์ƒ์„ธ ๋กœ๊ทธ", 
                lines=15, 
                max_lines=20,
                show_copy_button=True
            )
            download_files = gr.File(label="๐Ÿ’พ ๋‹ค์šด๋กœ๋“œ", file_count="multiple")
            
            save_btn = gr.Button("๐Ÿ”„ ์ถœ๋ ฅ ์ด๋ฏธ์ง€๋ฅผ ์ž…๋ ฅ์œผ๋กœ ์ €์žฅ", variant="secondary")
    
    # ์ €์žฅ๋œ ์ด๋ฏธ์ง€๋“ค์„ ํ‘œ์‹œํ•˜๋Š” ๊ฐค๋Ÿฌ๋ฆฌ
    with gr.Row():
        output_gallery = gr.Gallery(
            label="๐Ÿ“ธ ํŽธ์ง‘ ๊ธฐ๋ก", 
            show_label=True, 
            elem_id="gallery",
            columns=3,
            rows=2,
            height="auto"
        )
    
    # ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ
    edit_btn.click(
        fn=edit_image,
        inputs=[input_image, password, korean_prompt, output_format, aspect_ratio, upscale_option, saved_images, saved_downloads],
        outputs=[output_image, download_files, log_output, saved_images, saved_downloads]
    )
    
    save_btn.click(
        fn=save_output_as_input,
        inputs=[output_image, saved_images, saved_downloads],
        outputs=[input_image, saved_images, saved_downloads]
    )
    
    # ๊ฐค๋Ÿฌ๋ฆฌ ์—…๋ฐ์ดํŠธ
    saved_images.change(
        fn=lambda images: images if images else [],
        inputs=[saved_images],
        outputs=[output_gallery]
    )

if __name__ == "__main__":
    print("๐Ÿš€ ์ด๋ฏธ์ง€ ํŽธ์ง‘ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‹œ์ž‘ ์ค‘...")

    # API ํ‚ค ์ƒํƒœ ํ™•์ธ
    try:
        validate_api_keys()
        print("โœ… ๋ชจ๋“  API ํ‚ค๊ฐ€ ์„ค์ •๋˜์–ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.")
    except ValueError as e:
        print(f"โš ๏ธ  ๊ฒฝ๊ณ : {e}")
        print("์ผ๋ถ€ ๊ธฐ๋Šฅ์ด ์ œํ•œ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
    
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=True
    )