File size: 26,951 Bytes
38dd8f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
729e7f1
e6920c4
3a47996
e6920c4
ec0ff5f
 
 
deb56c6
3a47996
 
cad5d49
3a47996
 
 
cad5d49
 
 
 
 
3a47996
 
 
3bee602
c0f2e23
3bee602
ec0ff5f
 
 
 
3bee602
 
96169f0
3bee602
7ee5f70
 
3bee602
 
19f37ea
d5cff80
 
7ee5f70
 
 
 
d5cff80
7ee5f70
 
 
 
 
38dd8f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad5d49
38dd8f0
 
3bee602
c0f2e23
38dd8f0
105afff
cad5d49
 
 
 
 
 
 
 
 
105afff
cad5d49
105afff
cad5d49
 
 
 
 
 
 
 
105afff
deb56c6
c0f2e23
38dd8f0
 
 
 
 
 
 
 
3cee212
3bee602
 
 
ec0ff5f
 
 
2a729b9
38dd8f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852ded9
d30fa97
 
105afff
d30fa97
9d4caea
d30fa97
105afff
d30fa97
105afff
d30fa97
105afff
d922f5e
9d4caea
 
105afff
 
 
 
9d4caea
d30fa97
 
38dd8f0
9d4caea
d30fa97
852ded9
d922f5e
 
 
 
105afff
d922f5e
 
 
105afff
 
d922f5e
9d4caea
d922f5e
105afff
 
 
 
9d4caea
105afff
d922f5e
 
105afff
 
d922f5e
38dd8f0
96169f0
d922f5e
96169f0
105afff
9d4caea
 
 
 
 
 
ecb47d1
 
36fc032
5902bc6
 
 
 
 
 
 
 
 
ecb47d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38dd8f0
ecb47d1
 
 
 
 
 
 
 
 
 
 
 
38dd8f0
7daf15f
38dd8f0
9701537
7daf15f
7ae084c
 
 
 
 
 
 
 
 
9701537
 
 
7daf15f
 
38dd8f0
d30fa97
10c000d
deb56c6
 
 
 
 
 
 
f7cc5a8
 
 
 
 
 
deb56c6
 
10c000d
 
d30fa97
deb56c6
10c000d
 
38dd8f0
a3055a6
38dd8f0
27c735f
 
 
10c000d
deb56c6
a3055a6
10c000d
38dd8f0
 
 
 
 
 
 
 
d5cff80
e6920c4
36fc032
 
 
d819968
7ae084c
d819968
 
541adaa
 
7ae084c
 
 
 
 
d5cff80
7ae084c
 
 
d819968
7ae084c
 
 
 
 
 
 
 
 
 
541adaa
7ae084c
 
 
 
 
 
 
 
d819968
7ae084c
d819968
e6920c4
3bee602
e6920c4
1160b91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38dd8f0
4af64e1
2dfb3f5
4af64e1
2dfb3f5
 
 
4af64e1
2dfb3f5
 
 
 
 
4af64e1
 
2dfb3f5
4af64e1
d819968
 
ecb47d1
9bf26ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecb47d1
 
 
 
 
 
 
 
 
 
9bf26ec
d6f5e9d
7ae084c
3a47996
 
 
7ae084c
3a47996
 
 
 
 
 
 
 
7ae084c
3a47996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cd26
3a47996
ecb47d1
da47978
015ec9d
 
3a109ed
 
015ec9d
 
 
3a47996
 
34af73e
df5b718
 
 
 
 
 
 
 
 
 
 
 
d30fa97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fc032
ecb47d1
 
d648867
 
 
 
 
 
 
 
 
 
 
 
 
ecb47d1
 
 
 
541adaa
4eb00b3
ecb47d1
 
228ea98
9a6cd26
 
 
 
 
 
 
d648867
 
 
 
 
 
 
 
 
 
 
 
228ea98
df5b718
d6f5e9d
df5b718
 
 
 
 
 
d6f5e9d
df5b718
 
 
 
 
 
da47978
e87b1f0
2447d97
d6f5e9d
2447d97
49cf663
 
2447d97
49cf663
2447d97
d6f5e9d
2447d97
49cf663
 
2447d97
e87b1f0
ecb47d1
 
 
dff9eba
ecb47d1
 
dff9eba
 
d30fa97
 
ecb47d1
d30fa97
ecb47d1
d30fa97
 
 
2447d97
da47978
ecb47d1
 
 
 
 
 
 
 
df5b718
49cf663
da47978
2dfb3f5
a06e214
7ae084c
e6920c4
 
 
27c735f
e0db541
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
import tempfile
import time
from collections.abc import Sequence
from typing import Any, cast
import os
from huggingface_hub import login, hf_hub_download

import gradio as gr
import numpy as np
import pillow_heif
import spaces
import torch
from gradio_image_annotation import image_annotator
from gradio_imageslider import ImageSlider
from PIL import Image
from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
from refiners.fluxion.utils import no_grad
from refiners.solutions import BoxSegmenter
from transformers import GroundingDinoForObjectDetection, GroundingDinoProcessor
from diffusers import FluxPipeline
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
import gc
import base64


# GPU ์„ค์ •
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")  # ๋ช…์‹œ์ ์œผ๋กœ cuda:0 ์ง€์ •

###--------------ZERO GPU ํ•„์ˆ˜/ ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ ๊ณตํ†ต --------------------###
def clear_memory():
    """๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ํ•จ์ˆ˜"""
    gc.collect()
    if torch.cuda.is_available():
        try:
            with torch.cuda.device('cuda:0'):
                torch.cuda.empty_cache()
                torch.cuda.synchronize()
        except Exception as e:
            print(f"Warning: Could not clear CUDA memory: {e}")

###---------------------------------------------------------------

# GPU ์„ค์ •์„ try-except๋กœ ๊ฐ์‹ธ๊ธฐ
if torch.cuda.is_available():
    try:
        with torch.cuda.device(0):
            torch.cuda.empty_cache()
            torch.backends.cudnn.benchmark = True
            torch.backends.cuda.matmul.allow_tf32 = True
    except:
        print("Warning: Could not configure CUDA settings")

# ๋ฒˆ์—ญ ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
model_name = "Helsinki-NLP/opus-mt-ko-en"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name).to('cpu')
translator = pipeline("translation", model=model, tokenizer=tokenizer, device=-1)

def translate_to_english(text: str) -> str:
    """ํ•œ๊ธ€ ํ…์ŠคํŠธ๋ฅผ ์˜์–ด๋กœ ๋ฒˆ์—ญ"""
    try:
        if any(ord('๊ฐ€') <= ord(char) <= ord('ํžฃ') for char in text):
            translated = translator(text, max_length=128)[0]['translation_text']
            print(f"Translated '{text}' to '{translated}'")
            return translated
        return text
    except Exception as e:
        print(f"Translation error: {str(e)}")
        return text

BoundingBox = tuple[int, int, int, int]

pillow_heif.register_heif_opener()
pillow_heif.register_avif_opener()

# HF ํ† ํฐ ์„ค์ •
HF_TOKEN = os.getenv("HF_TOKEN")
if HF_TOKEN is None:
    raise ValueError("Please set the HF_TOKEN environment variable")

try:
    login(token=HF_TOKEN)
except Exception as e:
    raise ValueError(f"Failed to login to Hugging Face: {str(e)}")

# ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
segmenter = BoxSegmenter(device="cpu")
segmenter.device = device
segmenter.model = segmenter.model.to(device=segmenter.device)

gd_model_path = "IDEA-Research/grounding-dino-base"
gd_processor = GroundingDinoProcessor.from_pretrained(gd_model_path)
gd_model = GroundingDinoForObjectDetection.from_pretrained(gd_model_path, torch_dtype=torch.float32)
gd_model = gd_model.to(device=device)
assert isinstance(gd_model, GroundingDinoForObjectDetection)

# ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” ๋ฐ ์ตœ์ ํ™” ์„ค์ •
pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    torch_dtype=torch.float16,
    use_auth_token=HF_TOKEN
)

# ๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™” ์„ค์ • - FluxPipeline์—์„œ ์ง€์›ํ•˜๋Š” ๋ฉ”์„œ๋“œ๋งŒ ์‚ฌ์šฉ
pipe.enable_attention_slicing(slice_size="auto")

# xformers ์ตœ์ ํ™” (์„ค์น˜๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ์—๋งŒ)
try:
    import xformers
    pipe.enable_xformers_memory_efficient_attention()
except ImportError:
    print("xformers is not installed. Skipping memory efficient attention.")

# GPU ์„ค์ •
if torch.cuda.is_available():
    try:
        pipe = pipe.to("cuda:0")
        # CPU ์˜คํ”„๋กœ๋”ฉ์ด ์ง€์›๋˜๋Š” ๊ฒฝ์šฐ์—๋งŒ ํ™œ์„ฑํ™”
        if hasattr(pipe, 'enable_model_cpu_offload'):
            pipe.enable_model_cpu_offload()
    except Exception as e:
        print(f"Warning: Could not move pipeline to CUDA: {str(e)}")

    

# LoRA ๊ฐ€์ค‘์น˜ ๋กœ๋“œ
pipe.load_lora_weights(
    hf_hub_download(
        "ByteDance/Hyper-SD",
        "Hyper-FLUX.1-dev-8steps-lora.safetensors",
        use_auth_token=HF_TOKEN
    )
)
pipe.fuse_lora(lora_scale=0.125)

# GPU ์„ค์ •์„ try-except๋กœ ๊ฐ์‹ธ๊ธฐ
try:
    if torch.cuda.is_available():
        pipe = pipe.to("cuda:0")  # ๋ช…์‹œ์ ์œผ๋กœ cuda:0 ์ง€์ •
except Exception as e:
    print(f"Warning: Could not move pipeline to CUDA: {str(e)}")

class timer:
    def __init__(self, method_name="timed process"):
        self.method = method_name
    def __enter__(self):
        self.start = time.time()
        print(f"{self.method} starts")
    def __exit__(self, exc_type, exc_val, exc_tb):
        end = time.time()
        print(f"{self.method} took {str(round(end - self.start, 2))}s")

def bbox_union(bboxes: Sequence[list[int]]) -> BoundingBox | None:
    if not bboxes:
        return None
    for bbox in bboxes:
        assert len(bbox) == 4
        assert all(isinstance(x, int) for x in bbox)
    return (
        min(bbox[0] for bbox in bboxes),
        min(bbox[1] for bbox in bboxes),
        max(bbox[2] for bbox in bboxes),
        max(bbox[3] for bbox in bboxes),
    )

def corners_to_pixels_format(bboxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
    x1, y1, x2, y2 = bboxes.round().to(torch.int32).unbind(-1)
    return torch.stack((x1.clamp_(0, width), y1.clamp_(0, height), x2.clamp_(0, width), y2.clamp_(0, height)), dim=-1)

def gd_detect(img: Image.Image, prompt: str) -> BoundingBox | None:
    inputs = gd_processor(images=img, text=f"{prompt}.", return_tensors="pt").to(device=device)
    with no_grad():
        outputs = gd_model(**inputs)
    width, height = img.size
    results: dict[str, Any] = gd_processor.post_process_grounded_object_detection(
        outputs,
        inputs["input_ids"],
        target_sizes=[(height, width)],
    )[0]
    assert "boxes" in results and isinstance(results["boxes"], torch.Tensor)
    bboxes = corners_to_pixels_format(results["boxes"].cpu(), width, height)
    return bbox_union(bboxes.numpy().tolist())

def apply_mask(img: Image.Image, mask_img: Image.Image, defringe: bool = True) -> Image.Image:
    assert img.size == mask_img.size
    img = img.convert("RGB")
    mask_img = mask_img.convert("L")
    if defringe:
        rgb, alpha = np.asarray(img) / 255.0, np.asarray(mask_img) / 255.0
        foreground = cast(np.ndarray[Any, np.dtype[np.uint8]], estimate_foreground_ml(rgb, alpha))
        img = Image.fromarray((foreground * 255).astype("uint8"))
    result = Image.new("RGBA", img.size)
    result.paste(img, (0, 0), mask_img)
    return result


def calculate_dimensions(aspect_ratio: str, base_size: int = 512) -> tuple[int, int]:
    """์„ ํƒ๋œ ๋น„์œจ์— ๋”ฐ๋ผ ์ด๋ฏธ์ง€ ํฌ๊ธฐ ๊ณ„์‚ฐ"""
    # FLUX ํŒŒ์ดํ”„๋ผ์ธ์ด ์ง€์›ํ•˜๋Š” ์•ˆ์ „ํ•œ ํฌ๊ธฐ ์‚ฌ์šฉ
    if aspect_ratio == "1:1":
        width = height = 512
    elif aspect_ratio == "16:9":
        width, height = 576, 320  # 16:9์— ๊ฐ€๊นŒ์šด ์•ˆ์ „ํ•œ ํฌ๊ธฐ
    elif aspect_ratio == "9:16":
        width, height = 320, 576  # 9:16์— ๊ฐ€๊นŒ์šด ์•ˆ์ „ํ•œ ํฌ๊ธฐ
    elif aspect_ratio == "4:3":
        width, height = 512, 384  # 4:3์— ๊ฐ€๊นŒ์šด ์•ˆ์ „ํ•œ ํฌ๊ธฐ
    else:
        width = height = 512
    
    # 8์˜ ๋ฐฐ์ˆ˜๋กœ ์กฐ์ •
    width = (width // 8) * 8
    height = (height // 8) * 8
    
    return width, height

def generate_background(prompt: str, aspect_ratio: str) -> Image.Image:
    try:
        # ์•ˆ์ „ํ•œ ํฌ๊ธฐ ๊ณ„์‚ฐ
        width, height = calculate_dimensions(aspect_ratio)
        
        print(f"Generating background with size: {width}x{height}")
        
        with timer("Background generation"):
            try:
                # ๋จผ์ € 512x512๋กœ ์ƒ์„ฑ
                with torch.inference_mode():
                    image = pipe(
                        prompt=prompt,
                        width=512,
                        height=512,
                        num_inference_steps=8,
                        guidance_scale=4.0,
                    ).images[0]
                
                # ์›ํ•˜๋Š” ํฌ๊ธฐ๋กœ ๋ฆฌ์‚ฌ์ด์ฆˆ
                if width != 512 or height != 512:
                    image = image.resize((width, height), Image.LANCZOS)
                return image
                
            except Exception as e:
                print(f"Pipeline error: {str(e)}")
                # ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ ํฐ์ƒ‰ ๋ฐฐ๊ฒฝ ๋ฐ˜ํ™˜
                return Image.new('RGB', (width, height), 'white')
                
    except Exception as e:
        print(f"Background generation error: {str(e)}")
        return Image.new('RGB', (512, 512), 'white')


def adjust_size_to_multiple_of_8(width: int, height: int) -> tuple[int, int]:
    """์ด๋ฏธ์ง€ ํฌ๊ธฐ๋ฅผ 8์˜ ๋ฐฐ์ˆ˜๋กœ ์กฐ์ •"""
    new_width = max(8, ((width + 7) // 8) * 8)  # ์ตœ์†Œ 8ํ”ฝ์…€ ๋ณด์žฅ
    new_height = max(8, ((height + 7) // 8) * 8)  # ์ตœ์†Œ 8ํ”ฝ์…€ ๋ณด์žฅ
    return new_width, new_height

def create_position_grid():
    return """
    <div class="position-grid" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; width: 150px; margin: auto;">
        <button class="position-btn" data-pos="top-left">โ†–</button>
        <button class="position-btn" data-pos="top-center">โ†‘</button>
        <button class="position-btn" data-pos="top-right">โ†—</button>
        <button class="position-btn" data-pos="middle-left">โ†</button>
        <button class="position-btn" data-pos="middle-center">โ€ข</button>
        <button class="position-btn" data-pos="middle-right">โ†’</button>
        <button class="position-btn" data-pos="bottom-left">โ†™</button>
        <button class="position-btn" data-pos="bottom-center" data-default="true">โ†“</button>
        <button class="position-btn" data-pos="bottom-right">โ†˜</button>
    </div>
    """

def calculate_object_position(position: str, bg_size: tuple[int, int], obj_size: tuple[int, int]) -> tuple[int, int]:
    """์˜ค๋ธŒ์ ํŠธ์˜ ์œ„์น˜ ๊ณ„์‚ฐ"""
    bg_width, bg_height = bg_size
    obj_width, obj_height = obj_size
    
    positions = {
        "top-left": (0, 0),
        "top-center": ((bg_width - obj_width) // 2, 0),
        "top-right": (bg_width - obj_width, 0),
        "middle-left": (0, (bg_height - obj_height) // 2),
        "middle-center": ((bg_width - obj_width) // 2, (bg_height - obj_height) // 2),
        "middle-right": (bg_width - obj_width, (bg_height - obj_height) // 2),
        "bottom-left": (0, bg_height - obj_height),
        "bottom-center": ((bg_width - obj_width) // 2, bg_height - obj_height),
        "bottom-right": (bg_width - obj_width, bg_height - obj_height)
    }
    
    return positions.get(position, positions["bottom-center"])

def resize_object(image: Image.Image, scale_percent: float) -> Image.Image:
    """์˜ค๋ธŒ์ ํŠธ ํฌ๊ธฐ ์กฐ์ •"""
    width = int(image.width * scale_percent / 100)
    height = int(image.height * scale_percent / 100)
    return image.resize((width, height), Image.Resampling.LANCZOS)

def combine_with_background(foreground: Image.Image, background: Image.Image, 
                          position: str = "bottom-center", scale_percent: float = 100) -> Image.Image:
    """์ „๊ฒฝ๊ณผ ๋ฐฐ๊ฒฝ ํ•ฉ์„ฑ ํ•จ์ˆ˜"""
    # ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ค€๋น„
    result = background.convert('RGBA')
    
    # ์˜ค๋ธŒ์ ํŠธ ํฌ๊ธฐ ์กฐ์ •
    scaled_foreground = resize_object(foreground, scale_percent)
    
    # ์˜ค๋ธŒ์ ํŠธ ์œ„์น˜ ๊ณ„์‚ฐ
    x, y = calculate_object_position(position, result.size, scaled_foreground.size)
    
    # ํ•ฉ์„ฑ
    result.paste(scaled_foreground, (x, y), scaled_foreground)
    return result

@spaces.GPU(duration=20)  # 30์ดˆ์—์„œ 20์ดˆ๋กœ ๊ฐ์†Œ
def _gpu_process(img: Image.Image, prompt: str | BoundingBox | None) -> tuple[Image.Image, BoundingBox | None, list[str]]:
    try:
        with torch.inference_mode(), torch.amp.autocast('cuda', enabled=torch.cuda.is_available()):
            if isinstance(prompt, str):
                bbox = gd_detect(img, prompt)
                if not bbox:
                    raise gr.Error("No object detected in image")
            else:
                bbox = prompt
                
            mask = segmenter(img, bbox)
            return mask, bbox, []
    except Exception as e:
        print(f"GPU process error: {str(e)}")
        raise
    finally:
        clear_memory()

def _process(img: Image.Image, prompt: str | BoundingBox | None, bg_prompt: str | None = None, aspect_ratio: str = "1:1") -> tuple[tuple[Image.Image, Image.Image, Image.Image], gr.DownloadButton]:
    try:
        # ์ž…๋ ฅ ์ด๋ฏธ์ง€ ํฌ๊ธฐ ์ œํ•œ
        max_size = 1024
        if img.width > max_size or img.height > max_size:
            ratio = max_size / max(img.width, img.height)
            new_size = (int(img.width * ratio), int(img.height * ratio))
            img = img.resize(new_size, Image.LANCZOS)

        # CUDA ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

        # ์ƒˆ๋กœ์šด autocast ๊ตฌ๋ฌธ ์‚ฌ์šฉ
        with torch.amp.autocast('cuda', enabled=torch.cuda.is_available()):
            mask, bbox, time_log = _gpu_process(img, prompt)
            masked_alpha = apply_mask(img, mask, defringe=True)

        if bg_prompt:
            background = generate_background(bg_prompt, aspect_ratio)
            combined = background
        else:
            combined = Image.alpha_composite(Image.new("RGBA", masked_alpha.size, "white"), masked_alpha)

        clear_memory()

        with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp:
            combined.save(temp.name)
            return (img, combined, masked_alpha), gr.DownloadButton(value=temp.name, interactive=True)
    except Exception as e:
        clear_memory()
        print(f"Processing error: {str(e)}")
        raise gr.Error(f"Processing failed: {str(e)}")

def on_change_bbox(prompts: dict[str, Any] | None):
    return gr.update(interactive=prompts is not None)


def on_change_prompt(img: Image.Image | None, prompt: str | None, bg_prompt: str | None = None):
    return gr.update(interactive=bool(img and prompt))


        
def process_prompt(img: Image.Image, prompt: str, bg_prompt: str | None = None, 
                  aspect_ratio: str = "1:1", position: str = "bottom-center", 
                  scale_percent: float = 100) -> tuple[Image.Image, Image.Image]:
    try:
        if img is None or not prompt or prompt.isspace():
            raise gr.Error("Please provide both image and prompt")
        
        print(f"Processing with position: {position}, scale: {scale_percent}")  # ๋””๋ฒ„๊น…์šฉ
        
        # ์ž…๋ ฅ ์ด๋ฏธ์ง€ ํฌ๊ธฐ ์ œํ•œ
        max_size = 1024
        if img.width > max_size or img.height > max_size:
            ratio = max_size / max(img.width, img.height)
            img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
        
        # ๋ฒˆ์—ญ ์ฒ˜๋ฆฌ
        translated_prompt = translate_to_english(prompt)
        translated_bg_prompt = translate_to_english(bg_prompt) if bg_prompt else None
        
        # ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ
        with torch.inference_mode():
            results, _ = _process(img, translated_prompt, translated_bg_prompt, aspect_ratio)
            
            if translated_bg_prompt:
                try:
                    combined = combine_with_background(
                        foreground=results[2],
                        background=results[1],
                        position=position,
                        scale_percent=scale_percent  # scale_slider๊ฐ€ ์•„๋‹Œ scale_percent ์‚ฌ์šฉ
                    )
                    return combined, results[2]
                except Exception as e:
                    print(f"Background combination error: {e}")
                    return results[1], results[2]
            
            return results[1], results[2]
            
    except Exception as e:
        print(f"Process error: {str(e)}")
        raise gr.Error(str(e))
    finally:
        clear_memory()
        
def process_bbox(img: Image.Image, box_input: str) -> tuple[Image.Image, Image.Image]:
    try:
        if img is None or box_input.strip() == "":
            raise gr.Error("Please provide both image and bounding box coordinates")
        
        try:
            coords = eval(box_input)
            if not isinstance(coords, list) or len(coords) != 4:
                raise ValueError("Invalid box format")
            bbox = tuple(int(x) for x in coords)
        except:
            raise gr.Error("Invalid box format. Please provide [xmin, ymin, xmax, ymax]")
        
        # Process the image
        results, _ = _process(img, bbox)
        
        # ํ•ฉ์„ฑ๋œ ์ด๋ฏธ์ง€์™€ ์ถ”์ถœ๋œ ์ด๋ฏธ์ง€๋งŒ ๋ฐ˜ํ™˜
        return results[1], results[2]
    except Exception as e:
        raise gr.Error(str(e))

# Event handler functions ์ˆ˜์ •
def update_process_button(img, prompt):
    return gr.update(
        interactive=bool(img and prompt),
        variant="primary" if bool(img and prompt) else "secondary"
    )

def update_box_button(img, box_input):
    try:
        if img and box_input:
            coords = eval(box_input)
            if isinstance(coords, list) and len(coords) == 4:
                return gr.update(interactive=True, variant="primary")
        return gr.update(interactive=False, variant="secondary")
    except:
        return gr.update(interactive=False, variant="secondary")


# CSS ์ •์˜
css = """
footer {display: none}
.main-title {
    text-align: center;
    margin: 2em 0;
    padding: 1em;
    background: #f7f7f7;
    border-radius: 10px;
}
.main-title h1 {
    color: #2196F3;
    font-size: 2.5em;
    margin-bottom: 0.5em;
}
.main-title p {
    color: #666;
    font-size: 1.2em;
}
.container {
    max-width: 1200px;
    margin: auto;
    padding: 20px;
}
.tabs {
    margin-top: 1em;
}
.input-group {
    background: white;
    padding: 1em;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.output-group {
    background: white;
    padding: 1em;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
button.primary {
    background: #2196F3;
    border: none;
    color: white;
    padding: 0.5em 1em;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s ease;
}
button.primary:hover {
    background: #1976D2;
}
.position-btn {
    transition: all 0.3s ease;
}
.position-btn:hover {
    background-color: #e3f2fd;
}
.position-btn.selected {
    background-color: #2196F3;
    color: white;
}
"""


def get_image_base64(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode()

# ์ด๋ฏธ์ง€๋ฅผ Base64๋กœ ๋ณ€ํ™˜
try:
    example_img1 = get_image_base64("aa1.png")
    example_img2 = get_image_base64("aa2.png")
    example_img3 = get_image_base64("aa3.png")
except Exception as e:
    print(f"Error loading example images: {e}")
    example_img1 = example_img2 = example_img3 = ""

# HTML ํ…œํ”Œ๋ฆฟ ์ˆ˜์ •
example_html = f"""
<div style="margin-top: 50px; padding: 20px; background-color: #f8f9fa; border-radius: 10px;">
    <h2 style="text-align: center; color: #2196F3; margin-bottom: 30px;">How It Works: Step by Step Guide</h2>
    
    <div style="display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; gap: 20px;">
        <div style="text-align: center; flex: 1; min-width: 250px; max-width: 300px;">
            <img src="data:image/png;base64,{example_img1}" 
                 style="width: 100%; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            <h3 style="color: #333; margin: 15px 0;">Step 1: Original Image</h3>
            <p style="color: #666;">Upload your original image containing the object you want to extract.</p>
        </div>
        
        <div style="text-align: center; flex: 1; min-width: 250px; max-width: 300px;">
            <img src="data:image/png;base64,{example_img2}" 
                 style="width: 100%; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            <h3 style="color: #333; margin: 15px 0;">Step 2: Object Extraction</h3>
            <p style="color: #666;">AI automatically detects and extracts the specified object.</p>
        </div>
        
        <div style="text-align: center; flex: 1; min-width: 250px; max-width: 300px;">
            <img src="data:image/png;base64,{example_img3}" 
                 style="width: 100%; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            <h3 style="color: #333; margin: 15px 0;">Step 3: Final Result</h3>
            <p style="color: #666;">The extracted object is placed on an AI-generated background.</p>
        </div>
    </div>

    <div style="margin-top: 30px; text-align: center; padding: 20px; background-color: #e3f2fd; border-radius: 8px;">
        <h4 style="color: #1976D2; margin-bottom: 10px;">Key Features:</h4>
        <ul style="list-style: none; padding: 0;">
            <li style="margin: 5px 0;">โœจ Advanced AI-powered object detection and extraction</li>
            <li style="margin: 5px 0;">๐ŸŽจ Custom background generation with text prompts</li>
            <li style="margin: 5px 0;">๐Ÿ”„ Flexible object positioning and sizing options</li>
            <li style="margin: 5px 0;">๐Ÿ“ Multiple aspect ratio support for various use cases</li>
        </ul>
    </div>
</div>
"""

    
# UI ๊ตฌ์„ฑ
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
    gr.HTML("""
        <div class="main-title">
            <h1>๐ŸŽจGiniGen Canvas</h1>
            <p>AI Integrated Image Creator: Extract objects, generate backgrounds, and adjust ratios and positions to create complete images with AI.</p>
        </div>
    """)

    # ์˜ˆ์ œ ์„น์…˜ ์ถ”๊ฐ€
    gr.HTML(example_html)
    
    with gr.Row():
        with gr.Column(scale=1):
            input_image = gr.Image(
                type="pil",
                label="Upload Image",
                interactive=True
            )
            text_prompt = gr.Textbox(
                label="Object to Extract",
                placeholder="Enter what you want to extract...",
                interactive=True
            )
            with gr.Row():
                bg_prompt = gr.Textbox(
                    label="Background Prompt (optional)",
                    placeholder="Describe the background...",
                    interactive=True,
                    scale=3
                )
                aspect_ratio = gr.Dropdown(
                    choices=["1:1", "16:9", "9:16", "4:3"],
                    value="1:1",
                    label="Aspect Ratio",
                    interactive=True,
                    visible=True,
                    scale=1
                )

            with gr.Row(visible=False) as object_controls:
                with gr.Column(scale=1):
                    with gr.Row():
                        position = gr.State(value="bottom-center")
                        btn_top_left = gr.Button("โ†–")
                        btn_top_center = gr.Button("โ†‘")
                        btn_top_right = gr.Button("โ†—")
                    with gr.Row():
                        btn_middle_left = gr.Button("โ†")
                        btn_middle_center = gr.Button("โ€ข")
                        btn_middle_right = gr.Button("โ†’")
                    with gr.Row():
                        btn_bottom_left = gr.Button("โ†™")
                        btn_bottom_center = gr.Button("โ†“")
                        btn_bottom_right = gr.Button("โ†˜")
                with gr.Column(scale=1):
                    scale_slider = gr.Slider(
                        minimum=10,
                        maximum=200,
                        value=100,
                        step=5,
                        label="Object Size (%)"
                    )

            process_btn = gr.Button(
                "Process",
                variant="primary",
                interactive=False
            )

            # ๊ฐ ๋ฒ„ํŠผ์— ๋Œ€ํ•œ ํด๋ฆญ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ
            def update_position(new_position):
                return new_position

            btn_top_left.click(fn=lambda: update_position("top-left"), outputs=position)
            btn_top_center.click(fn=lambda: update_position("top-center"), outputs=position)
            btn_top_right.click(fn=lambda: update_position("top-right"), outputs=position)
            btn_middle_left.click(fn=lambda: update_position("middle-left"), outputs=position)
            btn_middle_center.click(fn=lambda: update_position("middle-center"), outputs=position)
            btn_middle_right.click(fn=lambda: update_position("middle-right"), outputs=position)
            btn_bottom_left.click(fn=lambda: update_position("bottom-left"), outputs=position)
            btn_bottom_center.click(fn=lambda: update_position("bottom-center"), outputs=position)
            btn_bottom_right.click(fn=lambda: update_position("bottom-right"), outputs=position)

        with gr.Column(scale=1):
            with gr.Row():
                combined_image = gr.Image(
                    label="Combined Result",
                    show_download_button=True,
                    type="pil",
                    height=512
                )
            with gr.Row():
                extracted_image = gr.Image(
                    label="Extracted Object",
                    show_download_button=True,
                    type="pil",
                    height=256
                )

    # Event bindings
    input_image.change(
        fn=update_process_button,
        inputs=[input_image, text_prompt],
        outputs=process_btn,
        queue=False
    )
    
    text_prompt.change(
        fn=update_process_button,
        inputs=[input_image, text_prompt],
        outputs=process_btn,
        queue=False
    )

    def update_controls(bg_prompt):
        is_visible = bool(bg_prompt)
        return [
            gr.update(visible=is_visible, interactive=is_visible),  # aspect_ratio
            gr.update(visible=is_visible),  # object_controls
        ]
    


    bg_prompt.change(
        fn=update_controls,
        inputs=bg_prompt,
        outputs=[aspect_ratio, object_controls],
        queue=False
    )

    process_btn.click(
        fn=process_prompt,
        inputs=[
            input_image,
            text_prompt,
            bg_prompt,
            aspect_ratio,
            position,
            scale_slider
        ],
        outputs=[combined_image, extracted_image],
        queue=True
    )


demo.queue(max_size=5)  # ํ ํฌ๊ธฐ ์ œํ•œ
demo.launch(
    server_name="0.0.0.0",
    server_port=7860,
    share=False,
    max_threads=2)  # ์Šค๋ ˆ๋“œ ์ˆ˜ ์ œํ•œ