File size: 55,672 Bytes
5b349d3
f33cb93
 
5b349d3
 
 
f33cb93
f34d9b8
f33cb93
5b349d3
1413c13
 
 
 
5b349d3
1413c13
f33cb93
 
 
 
 
 
 
 
c3395f1
8b8ac8e
1413c13
 
644a519
1413c13
 
 
 
 
 
 
 
 
 
 
 
644a519
f34d9b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1413c13
644a519
 
 
 
 
 
 
5b349d3
f33cb93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b86b06a
f34d9b8
1413c13
f34d9b8
1413c13
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
f34d9b8
1413c13
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
f34d9b8
1413c13
 
 
f34d9b8
1413c13
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
1413c13
 
 
 
 
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b349d3
 
f33cb93
 
5b349d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f33cb93
5b349d3
 
 
 
f34d9b8
 
 
 
 
 
 
 
 
 
 
 
 
5b349d3
f34d9b8
 
5b349d3
 
 
 
 
 
f34d9b8
 
5b349d3
 
 
 
 
 
f34d9b8
 
5b349d3
 
 
 
 
 
f34d9b8
 
5b349d3
 
 
 
 
 
f34d9b8
 
5b349d3
 
 
 
 
 
f34d9b8
 
5b349d3
 
 
 
 
 
f34d9b8
 
5b349d3
 
 
 
f33cb93
1413c13
f33cb93
f34d9b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1413c13
f34d9b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1413c13
f33cb93
 
 
 
1413c13
f33cb93
5b349d3
 
 
 
 
 
 
 
 
 
 
 
 
f34d9b8
5b349d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f33cb93
5b349d3
 
f33cb93
5b349d3
 
f33cb93
5b349d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1413c13
b2ce728
f34d9b8
 
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f33cb93
1413c13
c3395f1
f34d9b8
1413c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d2a59a
1413c13
 
 
 
 
 
 
 
0d2a59a
1413c13
 
 
 
 
 
 
 
 
 
8b8ac8e
c3395f1
5b349d3
b2ce728
5b349d3
 
 
 
 
 
 
1413c13
5b349d3
 
c3395f1
5b349d3
b2ce728
5b349d3
 
 
 
 
 
 
 
 
 
 
1413c13
5b349d3
 
f33cb93
5b349d3
 
f33cb93
5b349d3
 
 
 
 
 
f34d9b8
5b349d3
 
 
 
 
f34d9b8
 
 
 
 
 
 
 
 
 
 
 
 
5b349d3
f34d9b8
 
f33cb93
f34d9b8
f33cb93
f34d9b8
644a519
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
import sys
import base64
import io
import logging
import tempfile
import traceback
import requests
import json
from PIL import Image
import gradio as gr
from openai import OpenAI
import replicate
from google import genai
from google.genai import types

# ๋กœ๊น… ์„ค์ •
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("app.log"),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger("image-enhancer-app")

# API ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” (์•ˆ์ „ํ•˜๊ฒŒ)
openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", ""))

# Gemini ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” - API ํ‚ค๊ฐ€ ์žˆ์„ ๋•Œ๋งŒ
gemini_api_key = os.environ.get("GEMINI_API_KEY")
if gemini_api_key and gemini_api_key.strip():
    try:
        gemini_client = genai.Client(api_key=gemini_api_key)
        logger.info("Gemini client initialized successfully")
    except Exception as e:
        logger.error(f"Failed to initialize Gemini client: {e}")
        gemini_client = None
else:
    logger.warning("GEMINI_API_KEY not found or empty, Gemini client not initialized")
    gemini_client = None

# ์„ค์ •๊ฐ’๋“ค์„ ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋กœ๋“œํ•˜๋Š” ํ•จ์ˆ˜๋“ค
def get_app_password():
    """ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ์•ฑ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค."""
    password = os.environ.get("APP_PASSWORD")
    if password:
        logger.info("App password loaded from environment variable")
        return password
    else:
        logger.warning("APP_PASSWORD environment variable not found, using default password")
        return "1089"  # ๊ธฐ๋ณธ ๋น„๋ฐ€๋ฒˆํ˜ธ

# ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ๋ฅผ ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋กœ๋“œํ•˜๋Š” ํ•จ์ˆ˜
def load_backgrounds_from_env():
    """ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค."""
    try:
        # ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ JSON ๋ฌธ์ž์—ด๋กœ ์ €์žฅ๋œ ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
        backgrounds_data = os.environ.get("BACKGROUNDS_DATA")
        if backgrounds_data:
            logger.info("Loading backgrounds data from environment variable")
            return json.loads(backgrounds_data)
        else:
            logger.warning("BACKGROUNDS_DATA environment variable not found, using default backgrounds")
            return get_default_backgrounds()
    except Exception as e:
        logger.error(f"Error loading backgrounds from environment: {e}")
        logger.info("Falling back to default backgrounds")
        return get_default_backgrounds()

def get_default_backgrounds():
    """๊ธฐ๋ณธ ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค."""
    return {
        "SIMPLE_BACKGROUNDS": {
            "ํ™”์ดํŠธ ๊ธฐ๋ณธ": "A clean, minimalistic digital background scene featuring a seamless pure white backdrop and a smooth white surface. The lighting is bright and evenly diffused from above, eliminating harsh shadows and creating a crisp, studio-lit environment. There are no products or objects present โ€” only the empty background remains. The composition is ultra-clean and modern, ideal for overlaying lifestyle or hydration-related products. The mood is fresh, light, and professional. Ultra-sharp, studio-quality, high resolution, photo-realistic",
            "ํšŒ์ƒ‰ ํˆฌํ†ค": "A clean and minimal product photography background featuring a seamless, near-white light gray tone across both the backdrop and surface. The entire scene is evenly lit with bright, diffused lighting from above, eliminating harsh shadows and producing a calm, sophisticated atmosphere. The composition remains empty โ€” with no products or objects present โ€” offering a soft and airy visual ideal for modern lifestyle, wellness, or eco-friendly branding. The lighting gently enhances spatial depth without creating reflections. Ultra-clear, studio-quality, photo-realistic"
        },
        "STUDIO_BACKGROUNDS": {
            "์—ฐ๋…น์ƒ‰ ์žฅ๋ฏธ ์ •์›": "A high-resolution, commercial-style digital photograph of a sophisticated background setup designed for a luxury product shoot. The scene features soft green tones with lush fern leaves and creamy pastel roses (white, peach, blush pink) artfully arranged. The flowers are placed on a white polished marble platform with soft veining, surrounded by elegant foliage. The lighting is natural and diffused from the top left, producing soft shadows and a serene mood. There is no product in the scene โ€” only the floral arrangement and surface remain, creating a refined, editorial-quality backdrop suitable for overlaying product photography. No object should be centered; the composition should remain balanced and inviting. ultra-detailed, 8K quality, photo-realistic studio setting."
        },
        "NATURE_BACKGROUNDS": {
            "์ž‘์€ ํŒŒ๋„๊ฐ€ ์žˆ๋Š” ํ•ด๋ณ€": "A serene and natural beach-themed product photography scene. The background features warm golden sand and gentle turquoise waves softly rolling onto the shore, with white foam catching the golden light of a late afternoon sun. Around the edges of the frame โ€” but not overlapping the center foreground โ€” small natural elements like seashells, conch shells, and bits of coral are randomly scattered with varied sizes, positions, and quantities to evoke a natural, organic arrangement. The product area remains clean and visually unobstructed to maintain focus. Lighting is soft and ambient with subtle natural shadows to highlight the uploaded product. The overall atmosphere is peaceful, sunlit, and summer-inspired. Ultra photo-realistic, studio-quality"
        },
        "INDOOR_BACKGROUNDS": {
            "๊ธฐ๋ณธ ์ฑ…์ƒ": "A bright, Scandinavian-inspired home office featuring a matte white desk with crisp edges placed against a soft sage green wall. Natural daylight gently enters from the side, casting diffused shadows across the surface and enhancing the calm, focused atmosphere. On the desk are neatly arranged everyday essentials like a few colorful pens, a potted plant, and an open notebook. A neutral-toned ergonomic chair is tucked under the desk, and the surrounding area is intentionally minimal to emphasize clarity and productivity. The entire setting evokes a modern, clutter-free work environment., photo-realistic, high-resolution."
        },
        "SPECIAL_BACKGROUNDS": {
            "๋„ค์ด๋น„ ๋นˆํ‹ฐ์ง€ ํ”Œ๋กœ๋Ÿด ๋ฒฝ์ง€": "A richly detailed studio photography background featuring an ornate, vintage-inspired floral wallpaper design. The backdrop showcases vibrant red, pink, yellow, and green botanical motifs intricately woven across a deep navy blue base. The floral pattern is symmetrical and bold, giving the composition an artistic, maximalist aesthetic. The floor is a clean, solid blue surface, providing visual contrast and modern balance. Lighting is bright and evenly diffused, emphasizing both the product and the intricate details of the wallpaper. Ideal for showcasing creative, lifestyle, or design-forward products. Ultra-detailed, high-resolution, ."
        },
        "JEWELRY_BACKGROUNDS": {
            "ํ™”์ดํŠธ ๋ฏธ๋Ÿฌ ์ŠคํŒŸ ๋ผ์ดํŠธ": "A luxury jewelry product photoshoot featuring a soft white backdrop and a polished white mirrored surface. A single focused overhead light beam softly illuminates the center of the scene, fading smoothly toward the edges with a clean gradient. The glossy white surface reflects the jewelry item with crystal clarity โ€” capturing the shape, facets, and symmetry of the design in perfect mirror-like detail. The reflection appears sharp, clean, and vertically aligned beneath the product, enhancing the sense of luxury and balance. The atmosphere is premium, minimal, and luminous โ€” ideal for high-end diamond earrings or bridal jewelry. Ultra-detailed, studio-quality, photo-realistic"
        },
        "SPECIAL_EFFECTS_BACKGROUNDS": {
            "๋ธ”๋ฃจ๋ธ”๋ž™ ํฐ ๋ฌผ๋ฐฉ์šธ ํšจ๊ณผ": "A deep black and vivid cobalt blue gradient backdrop with a reflective surface splashed by crystalline water droplets frozen mid-air. Backlighting enhances shimmer and motion, creating a sense of waterproof resilience. High-impact, ultra-detailed."
        }
    }

# ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
backgrounds_data = load_backgrounds_from_env()
SIMPLE_BACKGROUNDS = backgrounds_data.get("SIMPLE_BACKGROUNDS", {})
STUDIO_BACKGROUNDS = backgrounds_data.get("STUDIO_BACKGROUNDS", {})
NATURE_BACKGROUNDS = backgrounds_data.get("NATURE_BACKGROUNDS", {})
INDOOR_BACKGROUNDS = backgrounds_data.get("INDOOR_BACKGROUNDS", {})
SPECIAL_BACKGROUNDS = backgrounds_data.get("SPECIAL_BACKGROUNDS", {})
JEWELRY_BACKGROUNDS = backgrounds_data.get("JEWELRY_BACKGROUNDS", {})
SPECIAL_EFFECTS_BACKGROUNDS = backgrounds_data.get("SPECIAL_EFFECTS_BACKGROUNDS", {})

# ์•ฑ ๋น„๋ฐ€๋ฒˆํ˜ธ ๋กœ๋“œ
APP_PASSWORD = get_app_password()

# ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฒ€์ฆ ํ•จ์ˆ˜
def validate_environment_variables():
    """ํ•„์ˆ˜ ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์—ˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค."""
    logger.info("=== ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฒ€์ฆ ์‹œ์ž‘ ===")
    
    # ๋น„๋ฐ€๋ฒˆํ˜ธ ๊ฒ€์ฆ
    logger.info(f"APP_PASSWORD: {'์„ค์ •๋จ' if os.environ.get('APP_PASSWORD') else '๊ธฐ๋ณธ๊ฐ’ ์‚ฌ์šฉ (1089)'}")
    
    # API ํ‚ค ๊ฒ€์ฆ
    openai_key = os.environ.get("OPENAI_API_KEY")
    replicate_token = os.environ.get("REPLICATE_API_TOKEN") 
    gemini_key = os.environ.get("GEMINI_API_KEY")
    
    logger.info(f"OPENAI_API_KEY: {'์„ค์ •๋จ' if openai_key else '์„ค์ •๋˜์ง€ ์•Š์Œ'}")
    logger.info(f"REPLICATE_API_TOKEN: {'์„ค์ •๋จ' if replicate_token else '์„ค์ •๋˜์ง€ ์•Š์Œ'}")
    logger.info(f"GEMINI_API_KEY: {'์„ค์ •๋จ' if gemini_key else '์„ค์ •๋˜์ง€ ์•Š์Œ'}")
    
    # ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ๊ฒ€์ฆ
    backgrounds_data_env = os.environ.get("BACKGROUNDS_DATA")
    if backgrounds_data_env:
        logger.info("BACKGROUNDS_DATA: ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ์„ค์ •๋จ")
        try:
            parsed_data = json.loads(backgrounds_data_env)
            bg_counts = {
                category: len(backgrounds) 
                for category, backgrounds in parsed_data.items()
            }
            logger.info(f"๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์„ฑ๊ณต: {bg_counts}")
            
            # ๊ฐ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ์ƒ์„ธ ์ •๋ณด
            for category, backgrounds in parsed_data.items():
                if backgrounds:
                    sample_keys = list(backgrounds.keys())[:3]  # ์ฒ˜์Œ 3๊ฐœ๋งŒ ํ‘œ์‹œ
                    logger.info(f"  {category}: {len(backgrounds)}๊ฐœ - ์˜ˆ์‹œ: {sample_keys}")
                else:
                    logger.warning(f"  {category}: ๋น„์–ด์žˆ์Œ")
                    
        except Exception as e:
            logger.error(f"BACKGROUNDS_DATA JSON ํŒŒ์‹ฑ ์˜ค๋ฅ˜: {e}")
            logger.error("๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”.")
    else:
        logger.info("BACKGROUNDS_DATA: ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์—†์Œ (๊ธฐ๋ณธ๊ฐ’ ์‚ฌ์šฉ)")
        
    # ์‹ค์ œ ๋กœ๋“œ๋œ ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ ํ™•์ธ
    actual_bg_counts = {
        "SIMPLE_BACKGROUNDS": len(SIMPLE_BACKGROUNDS),
        "STUDIO_BACKGROUNDS": len(STUDIO_BACKGROUNDS),
        "NATURE_BACKGROUNDS": len(NATURE_BACKGROUNDS),
        "INDOOR_BACKGROUNDS": len(INDOOR_BACKGROUNDS),
        "SPECIAL_BACKGROUNDS": len(SPECIAL_BACKGROUNDS),
        "JEWELRY_BACKGROUNDS": len(JEWELRY_BACKGROUNDS),
        "SPECIAL_EFFECTS_BACKGROUNDS": len(SPECIAL_EFFECTS_BACKGROUNDS)
    }
    logger.info(f"์‹ค์ œ ๋กœ๋“œ๋œ ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ: {actual_bg_counts}")
    
    # ๊ฒฝ๊ณ  ๋ฉ”์‹œ์ง€
    missing_apis = []
    if not openai_key:
        missing_apis.append("OpenAI (GPT ๋ชจ๋ธ ์‚ฌ์šฉ ๋ถˆ๊ฐ€)")
    if not replicate_token:
        missing_apis.append("Replicate (Flux ๋ชจ๋ธ ๋ฐ ํ™”์งˆ๊ฐœ์„  ์‚ฌ์šฉ ๋ถˆ๊ฐ€)")
    if not gemini_key:
        missing_apis.append("Gemini (๋ฒˆ์—ญ ๊ธฐ๋Šฅ ์‚ฌ์šฉ ๋ถˆ๊ฐ€)")
    
    if missing_apis:
        logger.warning(f"๋ˆ„๋ฝ๋œ API ํ‚ค๋กœ ์ธํ•ด ๋‹ค์Œ ๊ธฐ๋Šฅ์ด ์ œํ•œ๋ฉ๋‹ˆ๋‹ค: {', '.join(missing_apis)}")
    else:
        logger.info("๋ชจ๋“  API ํ‚ค๊ฐ€ ์„ค์ •๋˜์–ด ์ „์ฒด ๊ธฐ๋Šฅ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.")
    
    logger.info("=== ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฒ€์ฆ ์™„๋ฃŒ ===")

# ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฒ€์ฆ ์‹คํ–‰
validate_environment_variables()

# ์ž„์‹œ ํŒŒ์ผ ์ €์žฅ ํ•จ์ˆ˜
def save_uploaded_file(uploaded_file, suffix='.png'):
    try:
        logger.info(f"Processing uploaded file: {type(uploaded_file)}")
        
        if uploaded_file is None:
            logger.warning("Uploaded file is None")
            return None
        
        with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
            temp_filename = temp_file.name
            logger.info(f"Created temporary file: {temp_filename}")
        
        # Gradio ์—…๋กœ๋“œ ํŒŒ์ผ ์ฒ˜๋ฆฌ
        if isinstance(uploaded_file, str):  # ์ด๋ฏธ ํŒŒ์ผ ๊ฒฝ๋กœ์ธ ๊ฒฝ์šฐ
            logger.info(f"Uploaded file is already a path: {uploaded_file}")
            return uploaded_file
        
        # PIL Image ์ฒ˜๋ฆฌ
        if isinstance(uploaded_file, Image.Image):
            logger.info("Uploaded file is a PIL Image")
            uploaded_file.save(temp_filename, format="PNG")
            return temp_filename
        
        # ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
        with open(temp_filename, "wb") as f:
            if hasattr(uploaded_file, "read"):  # ํŒŒ์ผ ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ
                logger.info("Processing file object")
                content = uploaded_file.read()
                f.write(content)
                logger.info(f"Wrote {len(content)} bytes to {temp_filename}")
            else:  # ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ์ธ ๊ฒฝ์šฐ
                logger.info("Processing binary data")
                f.write(uploaded_file)
                logger.info(f"Wrote data to {temp_filename}")
        
        return temp_filename
    except Exception as e:
        logger.error(f"Error saving uploaded file: {e}")
        logger.error(traceback.format_exc())
        return None

# ํ…์ŠคํŠธ ๋ฒˆ์—ญ ํ•จ์ˆ˜ (ํ•œ๊ตญ์–ด โ†’ ์˜์–ด) - Gemini 2.0 Flash ์ „์šฉ
def translate_to_english(text):
    """ํ•œ๊ตญ์–ด ํ…์ŠคํŠธ๋ฅผ ์˜์–ด๋กœ ๋ฒˆ์—ญ (Gemini 2.0 Flash ์‚ฌ์šฉ)"""
    try:
        if not text or not text.strip():
            return ""
        
        # Gemini ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ดˆ๊ธฐํ™”๋˜์—ˆ๋Š”์ง€ ํ™•์ธ
        if gemini_client is None:
            logger.warning("Gemini client not available, returning original text")
            return text
        
        # Gemini 2.0 Flash๋ฅผ ์‚ฌ์šฉํ•œ ๋ฒˆ์—ญ
        try:
            response = gemini_client.models.generate_content(
                model="gemini-2.0-flash",
                config=types.GenerateContentConfig(
                    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.",
                    max_output_tokens=200,
                    temperature=0.1
                ),
                contents=[f"Translate this to English: {text}"]
            )
            
            translated = response.text.strip()
            logger.info(f"Translated '{text}' to '{translated}' using Gemini 2.0 Flash")
            return translated
            
        except Exception as e:
            logger.error(f"Gemini translation error: {e}")
            logger.warning("Translation failed, returning original text")
            return text
            
    except Exception as e:
        logger.error(f"Translation error: {e}")
        return text

# ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ํ•จ์ˆ˜ (์ข…ํšก๋น„์™€ ์š”์ฒญ์‚ฌํ•ญ ํ†ตํ•ฉ)
def generate_prompt(background_type, background_name, user_request, aspect_ratio="1:1"):
    # ๊ธฐ๋ณธ ๊ณ ์ • ํ”„๋กฌํ”„ํŠธ (์ข…ํšก๋น„ ์ •๋ณด ํฌํ•จ) - ์˜์–ด๋กœ ๋ณ€๊ฒฝ
    fixed_prompt = f"""
## Fixed Prompt (Required)
[Aspect Ratio: {aspect_ratio}]
[Foreground: all uploaded product images, preserve their original proportions and clarity]
[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]
[Product sizing: ensure product images maintain at least 50% of their height relative to the background]
[Composition: products must be naturally composited with the background, maintain proper shadows aligned with lighting]
[Product placement: if products already exist in the background prompt, follow their exact arrangement and positioning]
"""
    
    # ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ ์„ ํƒ
    if background_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ":
        background_prompt = SIMPLE_BACKGROUNDS.get(background_name, "")
    elif background_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ":
        background_prompt = STUDIO_BACKGROUNDS.get(background_name, "")
    elif background_type == "์ž์—ฐ ํ™˜๊ฒฝ":
        background_prompt = NATURE_BACKGROUNDS.get(background_name, "")
    elif background_type == "์‹ค๋‚ด ํ™˜๊ฒฝ":
        background_prompt = INDOOR_BACKGROUNDS.get(background_name, "")
    elif background_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ":
        background_prompt = SPECIAL_BACKGROUNDS.get(background_name, "")
    elif background_type == "์ฃผ์–ผ๋ฆฌ":
        background_prompt = JEWELRY_BACKGROUNDS.get(background_name, "")
    elif background_type == "ํŠน์ˆ˜ํšจ๊ณผ":
        background_prompt = SPECIAL_EFFECTS_BACKGROUNDS.get(background_name, "")
    else:
        background_prompt = "clean white background with soft even lighting"
    
    # ์‚ฌ์šฉ์ž ์š”์ฒญ์‚ฌํ•ญ ์ฒ˜๋ฆฌ
    if user_request and user_request.strip():
        # ํ•œ๊ตญ์–ด ์š”์ฒญ์‚ฌํ•ญ์„ ์˜์–ด๋กœ ๋ฒˆ์—ญ (Gemini 2.0 Flash ์‚ฌ์šฉ)
        translated_request = translate_to_english(user_request)
        
        # ๋ฒˆ์—ญ๋œ ์š”์ฒญ์‚ฌํ•ญ์„ ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ์— ํ†ตํ•ฉ
        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."
        
        # ์š”์ฒญ ํ”„๋กฌํ”„ํŠธ ์„น์…˜ (๋ฒˆ์—ญ๋œ ๋‚ด์šฉ ์‚ฌ์šฉ)
        request_prompt = f"""
## Request Prompt
{translated_request}
"""
        
        # ๋ฐฐ๊ฒฝ ํ”„๋กฌํ”„ํŠธ ์„น์…˜
        background_section = f"""
## Background Prompt (Background Settings)
{integrated_background}
"""
    else:
        # ์š”์ฒญ์‚ฌํ•ญ์ด ์—†๋Š” ๊ฒฝ์šฐ
        request_prompt = f"""
## Request Prompt
No specific request
"""
        
        # ์š”์ฒญ์‚ฌํ•ญ์ด ์—†๋Š” ๊ฒฝ์šฐ ๊ธฐ๋ณธ ๋ฐฐ๊ฒฝ๋งŒ ์‚ฌ์šฉ
        background_section = f"""
## Background Prompt (Background Settings)
{background_prompt}
"""
    
    # ์ตœ์ข… ํ”„๋กฌํ”„ํŠธ ์กฐํ•ฉ
    final_prompt = fixed_prompt + request_prompt + background_section
    
    return final_prompt

# ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ํ•จ์ˆ˜
def edit_and_enhance_image(
    prompt, 
    image,
    quality_level="gpt",
    aspect_ratio="1:1",
    output_format="jpg",
    enable_enhancement=True,
    enhancement_level=2
):
    try:
        logger.info(f"Editing image with prompt: '{prompt[:50]}...' (truncated)")
        logger.info(f"Parameters: quality_level={quality_level}, aspect_ratio={aspect_ratio}, output_format={output_format}")
        logger.info(f"Enhancement requested: {enable_enhancement}, level: {enhancement_level}")
        
        if image is None:
            logger.error("No image provided")
            return None, None, None, "์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."
        
        # ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ
        processed_image = None
        temp_paths = []  # ๋‚˜์ค‘์— ์ •๋ฆฌํ•  ๊ฒฝ๋กœ ์ถ”์ 
        
        img_path = save_uploaded_file(image)
        if img_path:
            logger.info(f"Saved image to temp path: {img_path}")
            processed_image = open(img_path, "rb")
            temp_paths.append(img_path)
        else:
            logger.error("Failed to save image")
            return None, None, None, "์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•ด ๋ณด์„ธ์š”."
        
        # ๋ชจ๋ธ ์„ ํƒ์— ๋”ฐ๋ฅธ ์ฒ˜๋ฆฌ
        edited_images = []
        usage_info = ""
        error_msg = None
        
        try:
            if quality_level == "gpt":
                # GPT ๋ชจ๋ธ ์‚ฌ์šฉ
                if not openai_client.api_key:
                    logger.error("OpenAI API key is not set")
                    return None, None, None, "OpenAI API ํ‚ค๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. API ํ‚ค๋ฅผ ์„ค์ •ํ•ด์ฃผ์„ธ์š”."
                
                # ์ข…ํšก๋น„๋ฅผ ํฌ๊ธฐ๋กœ ๋ณ€ํ™˜
                size_mapping = {
                    "1:1": "1024x1024",
                    "3:2": "1536x1024", 
                    "2:3": "1024x1536"
                }
                size = size_mapping.get(aspect_ratio, "1024x1024")
                
                params = {
                    "prompt": prompt,
                    "model": "gpt-image-1",
                    "n": 1,
                    "size": size,
                    "image": processed_image
                }
                
                logger.info(f"Calling OpenAI API for image editing")
                response = openai_client.images.edit(**params)
                logger.info("OpenAI API call successful")
                
                # ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ
                for i, data in enumerate(response.data):
                    logger.info(f"Processing result image {i+1}/{len(response.data)}")
                    
                    if hasattr(data, 'b64_json') and data.b64_json:
                        image_data = base64.b64decode(data.b64_json)
                        image = Image.open(io.BytesIO(image_data))
                    elif hasattr(data, 'url') and data.url:
                        response_url = requests.get(data.url)
                        image = Image.open(io.BytesIO(response_url.content))
                    else:
                        logger.warning(f"No image data found in response item {i+1}")
                        continue
                    
                    # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
                    if output_format.lower() != "png" and image.mode == "RGBA":
                        background = Image.new("RGB", image.size, (255, 255, 255))
                        background.paste(image, mask=image.split()[3])
                        image = background
                    
                    edited_images.append(image)
                
                usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (GPT ๋ชจ๋ธ ์‚ฌ์šฉ)"
                
            else:  # quality_level == "flux"
                # Flux ๋ชจ๋ธ ์‚ฌ์šฉ (ํ•ญ์ƒ ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  1ํšŒ ์ ์šฉ)
                if not os.environ.get("REPLICATE_API_TOKEN"):
                    logger.error("Replicate API token is not set")
                    return None, None, None, "Replicate API ํ† ํฐ์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. API ํ† ํฐ์„ ์„ค์ •ํ•ด์ฃผ์„ธ์š”."
                
                logger.info(f"Using Flux model for image editing")
                
                # Flux ๋ชจ๋ธ๋กœ ์ด๋ฏธ์ง€ ์ƒ์„ฑ
                output = replicate.run(
                    "black-forest-labs/flux-kontext-pro",
                    input={
                        "prompt": prompt,
                        "input_image": processed_image,
                        "output_format": output_format.lower(),
                        "aspect_ratio": aspect_ratio,
                        "safety_tolerance": 2
                    }
                )
                
                logger.info(f"Flux API response received")
                
                # Flux API ์‘๋‹ต ์ฒ˜๋ฆฌ
                flux_image = None
                if output:
                    # output์ด ๋ฐ”์ดํŠธ ์ŠคํŠธ๋ฆผ์ธ ๊ฒฝ์šฐ
                    if hasattr(output, 'read'):
                        image_data = output.read()
                        flux_image = Image.open(io.BytesIO(image_data))
                    # output์ด URL์ธ ๊ฒฝ์šฐ  
                    elif isinstance(output, str) and output.startswith('http'):
                        response_url = requests.get(output)
                        flux_image = Image.open(io.BytesIO(response_url.content))
                    # output์ด ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐ์ดํ„ฐ์ธ ๊ฒฝ์šฐ
                    else:
                        flux_image = Image.open(io.BytesIO(output))
                    
                    # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
                    if output_format.lower() != "png" and flux_image.mode == "RGBA":
                        background = Image.new("RGB", flux_image.size, (255, 255, 255))
                        background.paste(flux_image, mask=flux_image.split()[3])
                        flux_image = background
                    
                    # Flux ๋ชจ๋ธ์€ ํ•ญ์ƒ ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ ๊ฐœ์„ ์„ ์ž๋™ ์ ์šฉ
                    try:
                        logger.info("Applying automatic first enhancement for Flux model")
                        
                        # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ
                        temp_flux_path = tempfile.mktemp(suffix='.png')
                        flux_image.save(temp_flux_path)
                        temp_paths.append(temp_flux_path)
                        
                        # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ ํ–ฅ์ƒ (Flux ๋ชจ๋ธ ๊ธฐ๋ณธ ์ ์šฉ)
                        first_enhanced_output = replicate.run(
                            "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
                            input={
                                "image": open(temp_flux_path, "rb"),
                                "scale_factor": 2,
                                "resemblance": 0.8,
                                "creativity": 0.2,
                                "output_format": output_format.lower(),
                                "prompt": prompt,
                                "negative_prompt": "(worst quality, low quality, normal quality:2)"
                            }
                        )
                        
                        if first_enhanced_output and isinstance(first_enhanced_output, list) and len(first_enhanced_output) > 0:
                            first_enhanced_url = first_enhanced_output[0]
                            first_enhanced_response = requests.get(first_enhanced_url)
                            
                            if first_enhanced_response.status_code == 200:
                                first_enhanced_image = Image.open(io.BytesIO(first_enhanced_response.content))
                                
                                # ์ด๋ฏธ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
                                if output_format.lower() != "png" and first_enhanced_image.mode == "RGBA":
                                    background = Image.new("RGB", first_enhanced_image.size, (255, 255, 255))
                                    background.paste(first_enhanced_image, mask=first_enhanced_image.split()[3])
                                    first_enhanced_image = background
                                
                                edited_images.append(first_enhanced_image)
                                usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ + ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์ ์šฉ)"
                                logger.info("First enhancement completed for Flux model")
                            else:
                                # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ ์‹œ ์›๋ณธ ์‚ฌ์šฉ
                                edited_images.append(flux_image)
                                usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ ์‚ฌ์šฉ, ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ)"
                        else:
                            # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ ์‹œ ์›๋ณธ ์‚ฌ์šฉ
                            edited_images.append(flux_image)
                            usage_info = "์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ ์‚ฌ์šฉ, ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ)"
                            
                    except Exception as e:
                        logger.error(f"Error in first enhancement for Flux: {e}")
                        # ์ฒซ ๋ฒˆ์งธ ํ™”์งˆ๊ฐœ์„  ์‹คํŒจ ์‹œ ์›๋ณธ ์‚ฌ์šฉ
                        edited_images.append(flux_image)
                        usage_info = f"์ด๋ฏธ์ง€ ํŽธ์ง‘ ์™„๋ฃŒ (Flux ๋ชจ๋ธ ์‚ฌ์šฉ, ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„  ์˜ค๋ฅ˜: {str(e)})"
                        
                else:
                    logger.error("No output from Flux API")
                    error_msg = "Flux API์—์„œ ์‘๋‹ต์„ ๋ฐ›์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."
        
        except Exception as e:
            if quality_level == "gpt":
                logger.error(f"OpenAI API call error: {e}")
                error_msg = f"OpenAI API ํ˜ธ์ถœ ์˜ค๋ฅ˜: {str(e)}"
            else:
                logger.error(f"Flux API call error: {e}")
                error_msg = f"Flux API ํ˜ธ์ถœ ์˜ค๋ฅ˜: {str(e)}"
        
        finally:
            # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
            if processed_image and hasattr(processed_image, 'close'):
                processed_image.close()
        
        # ํ™”์งˆ ํ–ฅ์ƒ ์ฒ˜๋ฆฌ (GPT ๋ชจ๋ธ์€ ์ผ๋ฐ˜์ ์ธ ํ™”์งˆ๊ฐœ์„ , Flux ๋ชจ๋ธ์€ 2์ฐจ ํ™”์งˆ๊ฐœ์„ )
        enhanced_image = None
        temp_image_path = None
        
        if enable_enhancement and edited_images and not error_msg:
            try:
                if quality_level == "gpt":
                    # GPT ๋ชจ๋ธ: ์ผ๋ฐ˜์ ์ธ ํ™”์งˆ ๊ฐœ์„ 
                    logger.info(f"Enhancing GPT image with Replicate API, enhancement level: {enhancement_level}")
                    enhancement_info = "ํ™”์งˆ ๊ฐœ์„ "
                else:
                    # Flux ๋ชจ๋ธ: 2์ฐจ ํ™”์งˆ ๊ฐœ์„  (์ด๋ฏธ 1์ฐจ๋Š” ์ ์šฉ๋จ)
                    logger.info(f"Applying second enhancement for Flux image, enhancement level: {enhancement_level}")
                    enhancement_info = "2์ฐจ ํ™”์งˆ ๊ฐœ์„ "
                
                if not os.environ.get("REPLICATE_API_TOKEN"):
                    logger.error("Replicate API token is not set")
                    usage_info += f" | {enhancement_info} ์‹คํŒจ: Replicate API ํ† ํฐ์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."
                else:
                    # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ
                    temp_image_path = tempfile.mktemp(suffix='.png')
                    edited_images[0].save(temp_image_path)
                    temp_paths.append(temp_image_path)
                    
                    # Replicate API๋กœ ํ™”์งˆ ํ–ฅ์ƒ
                    output = replicate.run(
                        "philz1337x/clarity-upscaler:dfad41707589d68ecdccd1dfa600d55a208f9310748e44bfe35b4a6291453d5e",
                        input={
                            "image": open(temp_image_path, "rb"),
                            "scale_factor": enhancement_level,
                            "resemblance": 0.8,
                            "creativity": 0.2,
                            "output_format": output_format.lower(),
                            "prompt": prompt,
                            "negative_prompt": "(worst quality, low quality, normal quality:2)"
                        }
                    )
                    
                    logger.info(f"Replicate API response: {output}")
                    
                    if output and isinstance(output, list) and len(output) > 0:
                        enhanced_url = output[0]
                        enhanced_response = requests.get(enhanced_url)
                        if enhanced_response.status_code == 200:
                            enhanced_image = Image.open(io.BytesIO(enhanced_response.content))
                            
                            if output_format.lower() != "png" and enhanced_image.mode == "RGBA":
                                background = Image.new("RGB", enhanced_image.size, (255, 255, 255))
                                background.paste(enhanced_image, mask=enhanced_image.split()[3])
                                enhanced_image = background
                            
                            if quality_level == "gpt":
                                usage_info += f" | {enhancement_info} ์™„๋ฃŒ: Replicate Clarity Upscaler ์‚ฌ์šฉ"
                            else:
                                usage_info += f" | {enhancement_info} ์™„๋ฃŒ: ์ด 2ํšŒ ํ™”์งˆ๊ฐœ์„  ์ ์šฉ"
                        else:
                            usage_info += f" | {enhancement_info} ์‹คํŒจ: ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์˜ค๋ฅ˜"
                    else:
                        usage_info += f" | {enhancement_info} ์‹คํŒจ: Replicate API ์‘๋‹ต ์—†์Œ"
                
            except Exception as e:
                logger.error(f"Error enhancing image: {e}")
                if quality_level == "gpt":
                    usage_info += f" | ํ™”์งˆ ๊ฐœ์„  ์‹คํŒจ: {str(e)}"
                else:
                    usage_info += f" | 2์ฐจ ํ™”์งˆ ๊ฐœ์„  ์‹คํŒจ: {str(e)}"
        
        # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        for path in temp_paths:
            if os.path.exists(path):
                try:
                    os.remove(path)
                    logger.info(f"Removed temp file: {path}")
                except Exception as e:
                    logger.error(f"Error removing temp file {path}: {e}")
        
        # ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
        if error_msg:
            return None, None, None, error_msg
        elif edited_images:
            if enable_enhancement and enhanced_image:
                return edited_images, [enhanced_image], usage_info, None
            else:
                return edited_images, None, usage_info, None
        else:
            return None, None, None, "์ด๋ฏธ์ง€ ํŽธ์ง‘์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."
            
    except Exception as e:
        logger.error(f"Error in edit_and_enhance_image function: {e}")
        logger.error(traceback.format_exc())
        return None, None, None, f"์—๋Ÿฌ ๋ฐœ์ƒ: {str(e)}\n\n{traceback.format_exc()}"

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌ์„ฑ
def create_gradio_interface():
    try:
        logger.info("Creating Gradio interface")
        with gr.Blocks(title="AI ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„ ") as app:
            gr.Markdown("# AI ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ๋„๊ตฌ")
            
            # ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ ํ•„๋“œ
            password_box = gr.Textbox(
                label="๋น„๋ฐ€๋ฒˆํ˜ธ", 
                type="password", 
                placeholder="์‚ฌ์šฉํ•˜๋ ค๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”",
                interactive=True
            )
            
            # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ์ธํ„ฐํŽ˜์ด์Šค
            with gr.Row():
                with gr.Column():
                    # ์ƒํ’ˆ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ
                    image = gr.Image(label="์ƒํ’ˆ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ", type="pil")
                    
                    with gr.Row():
                        with gr.Column():
                            background_type = gr.Radio(
                                choices=["์‹ฌํ”Œ ๋ฐฐ๊ฒฝ", "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ", "์ž์—ฐ ํ™˜๊ฒฝ", "์‹ค๋‚ด ํ™˜๊ฒฝ", "ํŠน์ˆ˜๋ฐฐ๊ฒฝ", "์ฃผ์–ผ๋ฆฌ", "ํŠน์ˆ˜ํšจ๊ณผ"],
                                label="๋ฐฐ๊ฒฝ ์œ ํ˜•",
                                value="์‹ฌํ”Œ ๋ฐฐ๊ฒฝ"
                            )
                            
                            # ๋“œ๋กญ๋‹ค์šด ์ปดํฌ๋„ŒํŠธ๋“ค - ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๋กœ๋“œ๋œ ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ
                            simple_choices = list(SIMPLE_BACKGROUNDS.keys()) if SIMPLE_BACKGROUNDS else []
                            studio_choices = list(STUDIO_BACKGROUNDS.keys()) if STUDIO_BACKGROUNDS else []
                            nature_choices = list(NATURE_BACKGROUNDS.keys()) if NATURE_BACKGROUNDS else []
                            indoor_choices = list(INDOOR_BACKGROUNDS.keys()) if INDOOR_BACKGROUNDS else []
                            special_choices = list(SPECIAL_BACKGROUNDS.keys()) if SPECIAL_BACKGROUNDS else []
                            jewelry_choices = list(JEWELRY_BACKGROUNDS.keys()) if JEWELRY_BACKGROUNDS else []
                            special_effects_choices = list(SPECIAL_EFFECTS_BACKGROUNDS.keys()) if SPECIAL_EFFECTS_BACKGROUNDS else []
                            
                            # ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์—†์–ด์„œ ๋ฐฐ๊ฒฝ ๋ฐ์ดํ„ฐ๊ฐ€ ๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ ๊ฒฝ๊ณ 
                            if not any([simple_choices, studio_choices, nature_choices, indoor_choices, special_choices, jewelry_choices, special_effects_choices]):
                                logger.error("๋ชจ๋“  ๋ฐฐ๊ฒฝ ์นดํ…Œ๊ณ ๋ฆฌ๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค. BACKGROUNDS_DATA ํ™˜๊ฒฝ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•ด์ฃผ์„ธ์š”.")
                            
                            simple_dropdown = gr.Dropdown(
                                choices=simple_choices,
                                value=simple_choices[0] if simple_choices else None,
                                label="์‹ฌํ”Œ ๋ฐฐ๊ฒฝ ์„ ํƒ",
                                visible=True,
                                interactive=True
                            )
                            
                            studio_dropdown = gr.Dropdown(
                                choices=studio_choices,
                                value=studio_choices[0] if studio_choices else None,
                                label="์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ ์„ ํƒ",
                                visible=False,
                                interactive=True
                            )
                            
                            nature_dropdown = gr.Dropdown(
                                choices=nature_choices,
                                value=nature_choices[0] if nature_choices else None,
                                label="์ž์—ฐ ํ™˜๊ฒฝ ์„ ํƒ",
                                visible=False,
                                interactive=True
                            )
                            
                            indoor_dropdown = gr.Dropdown(
                                choices=indoor_choices,
                                value=indoor_choices[0] if indoor_choices else None,
                                label="์‹ค๋‚ด ํ™˜๊ฒฝ ์„ ํƒ",
                                visible=False,
                                interactive=True
                            )
                            
                            special_dropdown = gr.Dropdown(
                                choices=special_choices,
                                value=special_choices[0] if special_choices else None,
                                label="ํŠน์ˆ˜๋ฐฐ๊ฒฝ ์„ ํƒ",
                                visible=False,
                                interactive=True
                            )
                            
                            jewelry_dropdown = gr.Dropdown(
                                choices=jewelry_choices,
                                value=jewelry_choices[0] if jewelry_choices else None,
                                label="์ฃผ์–ผ๋ฆฌ ๋ฐฐ๊ฒฝ ์„ ํƒ",
                                visible=False,
                                interactive=True
                            )
                            
                            special_effects_dropdown = gr.Dropdown(
                                choices=special_effects_choices,
                                value=special_effects_choices[0] if special_effects_choices else None,
                                label="ํŠน์ˆ˜ํšจ๊ณผ ๋ฐฐ๊ฒฝ ์„ ํƒ",
                                visible=False,
                                interactive=True
                            )
                            
                            # ๋“œ๋กญ๋‹ค์šด ๋ณ€๊ฒฝ ํ•จ์ˆ˜
                            def update_dropdowns(bg_type):
                                """๋ฐฐ๊ฒฝ ์œ ํ˜•์— ๋”ฐ๋ผ ๋“œ๋กญ๋‹ค์šด์„ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค."""
                                logger.info(f"Updating dropdowns for background type: {bg_type}")
                                
                                # ๊ฐ ๋ฐฐ๊ฒฝ ์นดํ…Œ๊ณ ๋ฆฌ์˜ ํ‚ค ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ
                                simple_choices = list(SIMPLE_BACKGROUNDS.keys()) if SIMPLE_BACKGROUNDS else []
                                studio_choices = list(STUDIO_BACKGROUNDS.keys()) if STUDIO_BACKGROUNDS else []
                                nature_choices = list(NATURE_BACKGROUNDS.keys()) if NATURE_BACKGROUNDS else []
                                indoor_choices = list(INDOOR_BACKGROUNDS.keys()) if INDOOR_BACKGROUNDS else []
                                special_choices = list(SPECIAL_BACKGROUNDS.keys()) if SPECIAL_BACKGROUNDS else []
                                jewelry_choices = list(JEWELRY_BACKGROUNDS.keys()) if JEWELRY_BACKGROUNDS else []
                                special_effects_choices = list(SPECIAL_EFFECTS_BACKGROUNDS.keys()) if SPECIAL_EFFECTS_BACKGROUNDS else []
                                
                                # ๋””๋ฒ„๊น… ์ •๋ณด ๋กœ๊น…
                                logger.info(f"Available choices - Simple: {len(simple_choices)}, Studio: {len(studio_choices)}, Nature: {len(nature_choices)}")
                                logger.info(f"Indoor: {len(indoor_choices)}, Special: {len(special_choices)}, Jewelry: {len(jewelry_choices)}, Effects: {len(special_effects_choices)}")
                                
                                return {
                                    simple_dropdown: gr.update(
                                        visible=(bg_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ"), 
                                        choices=simple_choices,
                                        value=simple_choices[0] if simple_choices else None
                                    ),
                                    studio_dropdown: gr.update(
                                        visible=(bg_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ"),
                                        choices=studio_choices,
                                        value=studio_choices[0] if studio_choices else None
                                    ),
                                    nature_dropdown: gr.update(
                                        visible=(bg_type == "์ž์—ฐ ํ™˜๊ฒฝ"),
                                        choices=nature_choices,
                                        value=nature_choices[0] if nature_choices else None
                                    ),
                                    indoor_dropdown: gr.update(
                                        visible=(bg_type == "์‹ค๋‚ด ํ™˜๊ฒฝ"),
                                        choices=indoor_choices,
                                        value=indoor_choices[0] if indoor_choices else None
                                    ),
                                    special_dropdown: gr.update(
                                        visible=(bg_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ"),
                                        choices=special_choices,
                                        value=special_choices[0] if special_choices else None
                                    ),
                                    jewelry_dropdown: gr.update(
                                        visible=(bg_type == "์ฃผ์–ผ๋ฆฌ"),
                                        choices=jewelry_choices,
                                        value=jewelry_choices[0] if jewelry_choices else None
                                    ),
                                    special_effects_dropdown: gr.update(
                                        visible=(bg_type == "ํŠน์ˆ˜ํšจ๊ณผ"),
                                        choices=special_effects_choices,
                                        value=special_effects_choices[0] if special_effects_choices else None
                                    )
                                }
                            
                            background_type.change(
                                fn=update_dropdowns,
                                inputs=[background_type],
                                outputs=[simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown, jewelry_dropdown, special_effects_dropdown]
                            )
                    
                    # ์š”์ฒญ์‚ฌํ•ญ ์ž…๋ ฅ
                    request_text = gr.Textbox(
                        label="์š”์ฒญ์‚ฌํ•ญ", 
                        placeholder="์ƒํ’ˆ ์ด๋ฏธ์ง€์— ์ ์šฉํ•  ์Šคํƒ€์ผ, ๋ถ„์œ„๊ธฐ, ํŠน๋ณ„ ์š”์ฒญ์‚ฌํ•ญ ๋“ฑ์„ ์ž…๋ ฅํ•˜์„ธ์š”.", 
                        lines=3
                    )
                    
                    # ์ƒˆ๋กœ์šด ์˜ต์…˜๋“ค
                    quality_level = gr.Radio(
                        label="ํ’ˆ์งˆ ๋ ˆ๋ฒจ", 
                        choices=["gpt", "flux"],
                        value="flux",
                        info="GPT: GPT ๋ชจ๋ธ (๊ณ ํ’ˆ์งˆ), ์ผ๋ฐ˜: Flux ๋ชจ๋ธ (๋น ๋ฅธ ์ฒ˜๋ฆฌ + ๊ธฐ๋ณธ ํ™”์งˆ๊ฐœ์„ )"
                    )
                    
                    aspect_ratio = gr.Dropdown(
                        label="์ข…ํšก๋น„", 
                        choices=["1:1", "3:2", "2:3"],
                        value="1:1"
                    )
                    
                    output_format = gr.Dropdown(
                        label="์ด๋ฏธ์ง€ ํ˜•์‹", 
                        choices=["jpg", "png"],
                        value="jpg"
                    )
                    
                    # ํ™”์งˆ ๊ฐœ์„  ์˜ต์…˜
                    enable_enhancement = gr.Checkbox(
                        label="์ถ”๊ฐ€ ํ™”์งˆ ๊ฐœ์„ ", 
                        value=False,
                        info="GPT: 1ํšŒ ํ™”์งˆ๊ฐœ์„ , Flux: 2์ฐจ ํ™”์งˆ๊ฐœ์„  (๊ธฐ๋ณธ 1ํšŒ + ์ถ”๊ฐ€ 1ํšŒ)"
                    )
                    enhancement_level = gr.Slider(label="ํ™”์งˆ ๊ฐœ์„  ๋ ˆ๋ฒจ", minimum=1, maximum=4, value=2, step=1, visible=False)
                    
                    # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ๋ฒ„ํŠผ
                    generate_prompt_btn = gr.Button("ํ”„๋กฌํ”„ํŠธ๋งŒ ์ƒ์„ฑ")
                    
                    # ํŽธ์ง‘ ๋ฒ„ํŠผ
                    edit_btn = gr.Button("์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„ ")
                
                with gr.Column():
                    with gr.Row():
                        with gr.Column():
                            gr.Markdown("## ํŽธ์ง‘๋œ ์ด๋ฏธ์ง€")
                            original_output = gr.Gallery(label="ํŽธ์ง‘ ๊ฒฐ๊ณผ", preview=True)
                            original_download = gr.File(label="ํŽธ์ง‘ ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ", interactive=False)
                        
                        with gr.Column():
                            gr.Markdown("## ํ™”์งˆ ๊ฐœ์„ ๋œ ์ด๋ฏธ์ง€")
                            enhanced_output = gr.Gallery(label="ํ™”์งˆ ๊ฐœ์„  ๊ฒฐ๊ณผ", preview=True)
                            enhanced_download = gr.File(label="๊ฐœ์„  ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ", interactive=False)
                    
                    # ํ”„๋กฌํ”„ํŠธ ์ถœ๋ ฅ
                    prompt_output = gr.Textbox(label="์ƒ์„ฑ๋œ ํ”„๋กฌํ”„ํŠธ", lines=10, interactive=False)
                    info = gr.Textbox(label="์ฒ˜๋ฆฌ ์ •๋ณด", interactive=False)
                    error = gr.Textbox(label="์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€", interactive=False, visible=True)
            
            # ํ”„๋กฌํ”„ํŠธ๋งŒ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜ (๋น„๋ฐ€๋ฒˆํ˜ธ ์ฒดํฌ ํฌํ•จ)
            def generate_prompt_with_password_check(password, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, aspect_ratio):
                # ๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ - ํ™˜๊ฒฝ๋ณ€์ˆ˜์—์„œ ๊ฐ€์ ธ์˜จ ๋น„๋ฐ€๋ฒˆํ˜ธ์™€ ๋น„๊ต
                if password != APP_PASSWORD:
                    return "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค. ์˜ฌ๋ฐ”๋ฅธ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
                
                # ๋ฐฐ๊ฒฝ ์„ ํƒ
                background_name = ""
                if bg_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ":
                    background_name = simple
                elif bg_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ":
                    background_name = studio
                elif bg_type == "์ž์—ฐ ํ™˜๊ฒฝ":
                    background_name = nature
                elif bg_type == "์‹ค๋‚ด ํ™˜๊ฒฝ":
                    background_name = indoor
                elif bg_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ":
                    background_name = special
                elif bg_type == "์ฃผ์–ผ๋ฆฌ":
                    background_name = jewelry
                elif bg_type == "ํŠน์ˆ˜ํšจ๊ณผ":
                    background_name = special_effects
                
                # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ (์ข…ํšก๋น„ ํฌํ•จ)
                prompt = generate_prompt(bg_type, background_name, request_text, aspect_ratio)
                return prompt
            
            # ๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ ํ•จ์ˆ˜
            def check_password(password, *args):
                if password != APP_PASSWORD:
                    return (
                        [],  # original_output
                        None,  # original_download
                        [],  # enhanced_output
                        None,  # enhanced_download
                        "",  # prompt_output
                        "",  # info
                        "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค. ์˜ฌ๋ฐ”๋ฅธ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."  # error
                    )
                
                # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ์š”์ฒญ ์ฒ˜๋ฆฌ
                image, bg_type, simple, studio, nature, indoor, special, jewelry, special_effects, request_text, quality_level, aspect_ratio, output_format, enable_enhancement = args
                
                # ๋ฐฐ๊ฒฝ ์„ ํƒ
                background_name = ""
                if bg_type == "์‹ฌํ”Œ ๋ฐฐ๊ฒฝ":
                    background_name = simple
                elif bg_type == "์ŠคํŠœ๋””์˜ค ๋ฐฐ๊ฒฝ":
                    background_name = studio
                elif bg_type == "์ž์—ฐ ํ™˜๊ฒฝ":
                    background_name = nature
                elif bg_type == "์‹ค๋‚ด ํ™˜๊ฒฝ":
                    background_name = indoor
                elif bg_type == "ํŠน์ˆ˜๋ฐฐ๊ฒฝ":
                    background_name = special
                elif bg_type == "์ฃผ์–ผ๋ฆฌ":
                    background_name = jewelry
                elif bg_type == "ํŠน์ˆ˜ํšจ๊ณผ":
                    background_name = special_effects
                
                # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
                prompt = generate_prompt(bg_type, background_name, request_text, aspect_ratio)
                
                # ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ์‹คํ–‰
                original_images, enhanced_images, usage_info, error_msg = edit_and_enhance_image(
                    prompt, image, quality_level, aspect_ratio, output_format, enable_enhancement, 2
                )
                
                # ์ด๋ฏธ์ง€ ์ €์žฅ ๋ฐ ๋‹ค์šด๋กœ๋“œ ํŒŒ์ผ ์ค€๋น„
                original_path = None
                enhanced_path = None
                
                if error_msg:
                    logger.error(f"Error returned from edit_and_enhance_image: {error_msg}")
                    return (
                        [],  # original_output
                        None,  # original_download
                        [],  # enhanced_output
                        None,  # enhanced_download
                        prompt,  # prompt_output
                        "",  # info
                        error_msg  # error
                    )
                else:
                    # ์›๋ณธ ํŽธ์ง‘ ์ด๋ฏธ์ง€ ์ €์žฅ
                    if original_images and len(original_images) > 0:
                        try:
                            original_path = f"original_image.{output_format}"
                            original_images[0].save(original_path)
                            logger.info(f"Saved original image to {original_path}")
                        except Exception as e:
                            logger.error(f"Error saving original image: {e}")
                    
                    # ํ™”์งˆ ๊ฐœ์„  ์ด๋ฏธ์ง€ ์ €์žฅ
                    if enhanced_images and len(enhanced_images) > 0:
                        try:
                            enhanced_path = f"enhanced_image.{output_format}"
                            enhanced_images[0].save(enhanced_path)
                            logger.info(f"Saved enhanced image to {enhanced_path}")
                        except Exception as e:
                            logger.error(f"Error saving enhanced image: {e}")
                    
                    # ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
                    return (
                        original_images if original_images else [],  # original_output
                        original_path,  # original_download
                        enhanced_images if enhanced_images else [],  # enhanced_output
                        enhanced_path,  # enhanced_download
                        prompt,  # prompt_output
                        usage_info,  # info
                        ""  # error (๋นˆ ๋ฌธ์ž์—ด๋กœ ์„ค์ •)
                    )
            
            # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ
            generate_prompt_btn.click(
                fn=generate_prompt_with_password_check,
                inputs=[
                    password_box,
                    background_type,
                    simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown,
                    jewelry_dropdown, special_effects_dropdown,
                    request_text, aspect_ratio
                ],
                outputs=[prompt_output]
            )
            
            # ํŽธ์ง‘ ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ
            edit_btn.click(
                fn=check_password,
                inputs=[
                    password_box, 
                    image, background_type, 
                    simple_dropdown, studio_dropdown, nature_dropdown, indoor_dropdown, special_dropdown,
                    jewelry_dropdown, special_effects_dropdown,
                    request_text, quality_level, aspect_ratio, output_format, enable_enhancement
                ],
                outputs=[
                    original_output, original_download, 
                    enhanced_output, enhanced_download,
                    prompt_output, info, error
                ]
            )
        
        logger.info("Gradio interface created successfully")
        return app
    except Exception as e:
        logger.error(f"Error creating Gradio interface: {e}")
        logger.error(traceback.format_exc())
        raise

# ์•ฑ ์‹คํ–‰
if __name__ == "__main__":
    try:
        logger.info("=== AI ์ด๋ฏธ์ง€ ํŽธ์ง‘ ๋ฐ ํ™”์งˆ ๊ฐœ์„  ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‹œ์ž‘ ===")
        
        # imgs ๋””๋ ‰ํ† ๋ฆฌ ํ™•์ธ/์ƒ์„ฑ
        os.makedirs("imgs", exist_ok=True)
        logger.info("์ด๋ฏธ์ง€ ๋””๋ ‰ํ† ๋ฆฌ ์ค€๋น„ ์™„๋ฃŒ")
        
        # ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์žฌ๊ฒ€์ฆ (์•ฑ ์‹œ์ž‘ ์‹œ)
        logger.info("์•ฑ ์‹œ์ž‘ ์ „ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์ตœ์ข… ํ™•์ธ")
        if not APP_PASSWORD:
            logger.warning("๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๊ธฐ๋ณธ ๋น„๋ฐ€๋ฒˆํ˜ธ(1089)๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.")
        
        if not any([
            os.environ.get("OPENAI_API_KEY"),
            os.environ.get("REPLICATE_API_TOKEN"),
            os.environ.get("GEMINI_API_KEY")
        ]):
            logger.warning("API ํ‚ค๊ฐ€ ํ•˜๋‚˜๋„ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๊ธฐ๋Šฅ์ด ์ œํ•œ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
        
        # Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ ๋ฐ ์‹คํ–‰
        app = create_gradio_interface()
        logger.info("Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ ์™„๋ฃŒ")
        logger.info("์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...")
        app.launch(share=True)
        
    except Exception as e:
        logger.error(f"์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‹คํ–‰ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
        logger.error(traceback.format_exc())