File size: 30,591 Bytes
28d939c
 
 
 
 
 
 
 
 
 
 
6cc746a
28d939c
 
 
 
 
6cc746a
c89d1c8
 
 
6cc746a
 
 
 
c89d1c8
 
6cc746a
 
 
c89d1c8
 
6cc746a
 
 
c89d1c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cc746a
 
 
 
 
 
 
 
 
 
 
c89d1c8
6cc746a
 
c89d1c8
 
 
 
 
 
 
 
 
 
 
 
 
6cc746a
28d939c
b4a6522
28d939c
 
 
 
 
4e5b950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d939c
4e5b950
 
 
 
 
28d939c
 
4e5b950
28d939c
 
4e5b950
 
 
 
 
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1c7049
4e5b950
 
 
 
 
90f8865
 
b1c7049
28d939c
 
bdfff19
 
b1c7049
28d939c
b1c7049
28d939c
 
 
 
b1c7049
28d939c
 
 
 
b1c7049
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdfff19
 
 
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed26eb0
28d939c
bdfff19
 
 
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e5b950
 
 
 
 
28d939c
 
 
 
 
 
 
4e5b950
 
 
28d939c
 
 
 
 
 
 
 
 
 
 
 
ed26eb0
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed26eb0
28d939c
bdfff19
 
 
28d939c
 
 
 
ed26eb0
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
bdfff19
 
 
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1c7049
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e5b950
ed26eb0
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdfff19
28d939c
 
 
 
 
 
 
59cbe26
28d939c
 
ed26eb0
 
28d939c
 
 
 
 
 
 
 
 
4e5b950
bdfff19
 
3e87cf7
4e5b950
 
 
 
 
 
 
 
 
 
 
b1c7049
3e87cf7
28d939c
 
 
b1c7049
28d939c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed26eb0
28d939c
 
 
 
 
ed26eb0
28d939c
 
 
ed26eb0
 
 
 
 
 
 
 
 
 
 
 
28d939c
 
 
 
 
 
b1c7049
 
28d939c
 
 
 
 
 
3e87cf7
 
6cc746a
3e87cf7
 
6cc746a
3e87cf7
 
 
 
 
 
 
 
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
import os
import cv2
import tempfile
import spaces
import gradio as gr
import numpy as np
import torch
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image, ImageDraw
import inspect
from transformers import (
    Sam3Model, Sam3Processor,
    Sam3TrackerModel, Sam3TrackerProcessor
)

# ============ GRADIO CLIENT COMPAT PATCH ============
# Some gradio_client versions crash when encountering boolean JSON Schema nodes
# (e.g., additionalProperties: false/true) while generating /info API schema.
# Patch defensively to prevent startup failures on HF Spaces.
try:
    import gradio_client.utils as _grc_utils

    if not getattr(_grc_utils, "_BOOL_SCHEMA_PATCHED", False):
        # 1) get_type() sometimes assumes schema is a dict
        _orig_get_type = getattr(_grc_utils, "get_type", None)

        def _safe_get_type(schema):  # noqa: ANN001
            if isinstance(schema, bool) or not isinstance(schema, dict):
                return "any"
            if _orig_get_type is None:
                return "any"
            return _orig_get_type(schema)

        if _orig_get_type is not None:
            _grc_utils.get_type = _safe_get_type

        # 2) _json_schema_to_python_type() may raise on schema == True/False
        _orig_js2pt = getattr(_grc_utils, "_json_schema_to_python_type", None)

        def _safe_json_schema_to_python_type(schema, defs=None):  # noqa: ANN001
            if isinstance(schema, bool):
                # boolean JSON Schema: True means "any", False means "no value".
                # For API-info rendering, treating both as Any avoids crashes.
                return "Any"
            if _orig_js2pt is None:
                return "Any"
            return _orig_js2pt(schema, defs)

        if _orig_js2pt is not None:
            _grc_utils._json_schema_to_python_type = _safe_json_schema_to_python_type

        _grc_utils._BOOL_SCHEMA_PATCHED = True
except Exception as _e:
    # If gradio_client is unavailable or API changes, ignore and proceed.
    print(f"[warn] gradio_client schema patch skipped: {_e}")

# ============ GRADIO LAUNCH COMPAT ============
def _launch_compat(demo, **kwargs):
    """

    Gradio ๋ฒ„์ „๋ณ„๋กœ Blocks.launch() ์‹œ๊ทธ๋‹ˆ์ฒ˜๊ฐ€ ๋‹ฌ๋ผ์„œ(์˜ˆ: ssr ์ง€์› ์—ฌ๋ถ€),

    ํ˜„์žฌ ์„ค์น˜๋œ Gradio๊ฐ€ ์ง€์›ํ•˜๋Š” ํ‚ค๋งŒ ๊ณจ๋ผ launch()๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

    """
    # ๋จผ์ € ์›ํ•˜๋Š” ์˜ต์…˜์œผ๋กœ ๊ทธ๋Œ€๋กœ ํ˜ธ์ถœํ•˜๊ณ , "unexpected keyword"๊ฐ€ ๋‚˜๋ฉด ํ•ด๋‹น ํ‚ค๋งŒ ์ œ๊ฑฐ ํ›„ ์žฌ์‹œ๋„
    try:
        return demo.launch(**kwargs)
    except TypeError as e:
        msg = str(e)
        if "unexpected keyword argument 'ssr'" in msg or 'unexpected keyword argument "ssr"' in msg:
            kwargs.pop("ssr", None)
            return demo.launch(**kwargs)
        # ๊ทธ ์™ธ ์ผ€์ด์Šค๋Š” ์‹œ๊ทธ๋‹ˆ์ฒ˜ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•œ ๋ฒˆ ๋” ๋ณด์ˆ˜์ ์œผ๋กœ ํ•„ํ„ฐ๋ง
        try:
            sig = inspect.signature(demo.launch)
            supported = set(sig.parameters.keys())
            filtered = {k: v for k, v in kwargs.items() if k in supported}
            return demo.launch(**filtered)
        except Exception:
            raise

# ============ THEME SETUP ============
# Theme disabled to avoid API schema issues on HF Spaces

# ============ GLOBAL SETUP ============
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"๐Ÿ–ฅ๏ธ Using compute device: {device}")

# Models will be loaded lazily in functions to avoid build timeouts
IMG_MODEL = None
IMG_PROCESSOR = None
TRK_MODEL = None
TRK_PROCESSOR = None

@spaces.GPU
def load_models():
    """Lazy load models when needed"""
    global IMG_MODEL, IMG_PROCESSOR, TRK_MODEL, TRK_PROCESSOR

    if IMG_MODEL is not None:
        return True

    print("โณ Loading SAM3 Models...")
    try:
        # GPU๊ฐ€ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋ฉด GPU๋กœ ๋กœ๋“œ
        device = "cuda" if torch.cuda.is_available() else "cpu"
        dtype = torch.float16 if device == "cuda" else torch.float32

        IMG_MODEL = Sam3Model.from_pretrained("DiffusionWave/sam3", device_map=device, torch_dtype=dtype)
        IMG_PROCESSOR = Sam3Processor.from_pretrained("DiffusionWave/sam3")

        TRK_MODEL = Sam3TrackerModel.from_pretrained("DiffusionWave/sam3", device_map=device, torch_dtype=dtype)
        TRK_PROCESSOR = Sam3TrackerProcessor.from_pretrained("DiffusionWave/sam3")

        print(f"โœ… All Models loaded successfully on {device}!")
        return True
    except Exception as e:
        print(f"โŒ Model loading failed: {e}")
        return False

# ============ LAYER MANAGEMENT ============
class LayerManager:
    """๋ ˆ์ด์–ด ๊ธฐ๋ฐ˜ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜ ๊ด€๋ฆฌ ํด๋ž˜์Šค"""
    def __init__(self):
        self.layers = {}  # layer_id -> {'name': str, 'color': tuple, 'points': list, 'point_labels': list, 'masks': list, 'area': float}
        self.current_layer_id = None
        self.layer_counter = 0

    def create_layer(self, name, color=None):
        """์ƒˆ ๋ ˆ์ด์–ด ์ƒ์„ฑ"""
        if color is None:
            # ๋ฌด์ž‘์œ„ ์ƒ‰์ƒ ์ƒ์„ฑ
            import random
            color = (random.randint(50, 200), random.randint(50, 200), random.randint(50, 200))

        layer_id = f"layer_{self.layer_counter}"
        self.layers[layer_id] = {
            'name': name,
            'color': color,
            'points': [],
            'point_labels': [],  # 1: positive, 0: negative
            'masks': [],
            'area': 0.0
        }
        self.layer_counter += 1
        return layer_id

    def add_point_to_layer(self, layer_id, point, label=1):
        """๋ ˆ์ด์–ด์— ํฌ์ธํŠธ ์ถ”๊ฐ€"""
        if layer_id in self.layers:
            self.layers[layer_id]['points'].append(point)
            self.layers[layer_id]['point_labels'].append(label)
            print(f"[add_point_to_layer] Added point to '{self.layers[layer_id]['name']}': {point}, label={label}")
            print(f"[add_point_to_layer] Total points in '{self.layers[layer_id]['name']}': {len(self.layers[layer_id]['points'])}")

    def add_mask_to_layer(self, layer_id, mask):
        """๋ ˆ์ด์–ด์— ๋งˆ์Šคํฌ ์ถ”๊ฐ€"""
        if layer_id in self.layers:
            # ๊ธฐ์กด ๋งˆ์Šคํฌ๋ฅผ ๊ต์ฒด (๊ฐ™์€ ๋ ˆ์ด์–ด์— ์žฌ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜ ์‹œ)
            self.layers[layer_id]['masks'] = [mask]
            
            # ๋ฉด์  ๊ณ„์‚ฐ - mask๋ฅผ numpy array๋กœ ๋ณ€ํ™˜
            if isinstance(mask, torch.Tensor):
                mask_np = mask.cpu().numpy()
            else:
                mask_np = mask
            
            # ๋ฉด์  ๊ณ„์‚ฐ
            area = np.sum(mask_np > 0)
            self.layers[layer_id]['area'] = area
            
            # ๋””๋ฒ„๊น…: ๋งˆ์Šคํฌ ์ •๋ณด ์ถœ๋ ฅ
            print(f"[add_mask_to_layer] Layer: {self.layers[layer_id]['name']}, Mask shape: {mask_np.shape}, Area: {area}")

    def get_current_layer(self):
        """ํ˜„์žฌ ์„ ํƒ๋œ ๋ ˆ์ด์–ด ๋ฐ˜ํ™˜"""
        if self.current_layer_id and self.current_layer_id in self.layers:
            return self.layers[self.current_layer_id]
        return None

    def set_current_layer(self, layer_id):
        """ํ˜„์žฌ ๋ ˆ์ด์–ด ์„ค์ •"""
        self.current_layer_id = layer_id

    def clear_current_layer(self):
        """ํ˜„์žฌ ๋ ˆ์ด์–ด ์ดˆ๊ธฐํ™”"""
        if self.current_layer_id and self.current_layer_id in self.layers:
            self.layers[self.current_layer_id]['points'] = []
            self.layers[self.current_layer_id]['point_labels'] = []
            self.layers[self.current_layer_id]['masks'] = []
            self.layers[self.current_layer_id]['area'] = 0.0

def calculate_total_area_ratio(layer_manager, total_pixels):
    """์ „์ฒด ์ด๋ฏธ์ง€ ๋Œ€๋น„ ๊ฐ ๋ ˆ์ด์–ด์˜ ๋ฉด์  ๋น„์œจ ๊ณ„์‚ฐ"""
    ratios = []
    for layer_id, layer in layer_manager.layers.items():
        area = layer['area']
        ratio = (area / total_pixels) * 100 if total_pixels > 0 and area > 0 else 0
        has_mask = len(layer['masks']) > 0
        
        # ๋””๋ฒ„๊น…: ๋ ˆ์ด์–ด ์ •๋ณด ์ถœ๋ ฅ
        print(f"[calculate_total_area_ratio] Layer: {layer['name']}, Area: {area}, Ratio: {ratio}%, Masks: {len(layer['masks'])}, Has mask: {has_mask}")
        
        ratios.append({
            'layer_name': layer['name'],
            'area_pixels': int(area),
            'ratio_percent': round(ratio, 2)
        })
    return ratios

def create_area_chart_data(ratios):
    """๋ฉด์  ๋ฐ์ดํ„ฐ๋ฅผ ํ…Œ์ด๋ธ” ํฌ๋งท์œผ๋กœ ๋ณ€ํ™˜"""
    if not ratios:
        return pd.DataFrame(columns=["Layer", "Area (pixels)", "Ratio(%)"])

    data = []
    for ratio in ratios:
        data.append({
            "Layer": ratio['layer_name'],
            "Area (pixels)": f"{ratio['area_pixels']:,}",
            "Ratio(%)": f"{ratio['ratio_percent']}%"
        })

    return pd.DataFrame(data)

# ============ UTILITY FUNCTIONS ============
def compose_all_layers(base_image, layer_manager, opacity=0.5, border_width=2):
    """๋ชจ๋“  ๋ ˆ์ด์–ด๋ฅผ ํ•ฉ์„ฑํ•˜์—ฌ ์ตœ์ข… ์ด๋ฏธ์ง€ ์ƒ์„ฑ"""
    if isinstance(base_image, np.ndarray):
        base_image = Image.fromarray(base_image)
    base_image = base_image.convert("RGBA")

    if not layer_manager.layers:
        return base_image.convert("RGB")

    composite_layer = Image.new("RGBA", base_image.size, (0, 0, 0, 0))

    for layer_id, layer in layer_manager.layers.items():
        if not layer['masks']:
            continue

        layer_color = layer['color']

        for mask in layer['masks']:
            if isinstance(mask, torch.Tensor):
                mask = mask.cpu().numpy()
            mask = mask.astype(np.uint8)

            if mask.ndim == 3: mask = mask[0]
            if mask.ndim == 2 and mask.shape[0] == 1: mask = mask[0]

            # ๋งˆ์Šคํฌ๋ฅผ PIL ์ด๋ฏธ์ง€๋กœ ๋ณ€ํ™˜
            mask_img = Image.fromarray((mask * 255).astype(np.uint8))

            # ์ƒ‰์ƒ ๋ ˆ์ด์–ด ์ƒ์„ฑ
            color_layer = Image.new("RGBA", base_image.size, layer_color + (0,))
            mask_alpha = mask_img.point(lambda v: int(v * opacity * 255) if v > 0 else 0)
            color_layer.putalpha(mask_alpha)

            # ํ…Œ๋‘๋ฆฌ ์ถ”๊ฐ€
            if border_width > 0:
                try:
                    # ๋งˆ์Šคํฌ์˜ ํ…Œ๋‘๋ฆฌ ์ฐพ๊ธฐ
                    mask_np = np.array(mask_img)
                    kernel_size = border_width * 2 + 1
                    dilated = cv2.dilate(mask_np, np.ones((kernel_size, kernel_size), np.uint8))
                    border = dilated - mask_np
                    border_img = Image.fromarray(border)

                    border_layer = Image.new("RGBA", base_image.size, (255, 255, 255, 255))  # ํฐ์ƒ‰ ํ…Œ๋‘๋ฆฌ
                    border_alpha = border_img.point(lambda v: 255 if v > 0 else 0)
                    border_layer.putalpha(border_alpha)

                    # ํ…Œ๋‘๋ฆฌ๋ฅผ ๋จผ์ € ํ•ฉ์„ฑ
                    composite_layer = Image.alpha_composite(composite_layer, border_layer)
                except Exception as e:
                    print(f"Border creation error: {e}")

            # ๋งˆ์Šคํฌ ๋ ˆ์ด์–ด ํ•ฉ์„ฑ
            composite_layer = Image.alpha_composite(composite_layer, color_layer)

    # ์ตœ์ข… ํ•ฉ์„ฑ
    final_result = Image.alpha_composite(base_image, composite_layer)
    return final_result.convert("RGB")

def draw_points_on_image(image, layer_manager):
    """์ด๋ฏธ์ง€์— ๋ชจ๋“  ๋ ˆ์ด์–ด์˜ ํฌ์ธํŠธ๋“ค์„ ํ‘œ์‹œ"""
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)

    draw_img = image.copy()
    draw = ImageDraw.Draw(draw_img)

    for layer_id, layer in layer_manager.layers.items():
        is_current = (layer_id == layer_manager.current_layer_id)
        
        for i, point in enumerate(layer['points']):
            x, y = point
            label = layer['point_labels'][i]
            
            # ํฌ์ง€ํ‹ฐ๋ธŒ: ๋นจ๊ฐ„์ƒ‰ ์›, ๋„ค๊ฑฐํ‹ฐ๋ธŒ: ํŒŒ๋ž€์ƒ‰ Xํ‘œ์‹œ
            if label == 1:  # Positive
                # ํฐ ๋นจ๊ฐ„์ƒ‰ ์›
                r = 15 if is_current else 10
                draw.ellipse((x-r, y-r, x+r, y+r), fill="red", outline="white", width=3)
                # ์ž‘์€ ํฐ์ƒ‰ ์› (์ค‘์•™)
                draw.ellipse((x-3, y-3, x+3, y+3), fill="white")
            else:  # Negative (0)
                # ํฐ ํŒŒ๋ž€์ƒ‰ ์›
                r = 15 if is_current else 10
                draw.ellipse((x-r, y-r, x+r, y+r), fill="blue", outline="white", width=3)
                # X ํ‘œ์‹œ
                line_length = 8
                draw.line([(x-line_length, y-line_length), (x+line_length, y+line_length)], fill="white", width=3)
                draw.line([(x-line_length, y+line_length), (x+line_length, y-line_length)], fill="white", width=3)

    return draw_img

# ============ UI FUNCTIONS ============
def update_layer_selector_choices(manager):
    """๋ ˆ์ด์–ด ์„ ํƒ ๋ผ๋””์˜ค ๋ฒ„ํŠผ์˜ choices ์—…๋ฐ์ดํŠธ"""
    choices = [layer['name'] for layer in manager.layers.values()]
    current_value = None
    if manager.current_layer_id and manager.current_layer_id in manager.layers:
        current_value = manager.layers[manager.current_layer_id]['name']
    # ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ƒˆ๋กœ ์ƒ์„ฑํ•ด์„œ ๋ฐ˜ํ™˜ํ•˜์ง€ ๋ง๊ณ , gr.update()๋กœ ๊ธฐ์กด ์ปดํฌ๋„ŒํŠธ๋ฅผ ์—…๋ฐ์ดํŠธํ•ด์•ผ ํ•จ
    return gr.update(choices=choices, value=current_value, interactive=True)

def create_new_layer(name, current_manager):
    """์ƒˆ ๋ ˆ์ด์–ด ์ƒ์„ฑ"""
    if current_manager is None:
        current_manager = LayerManager()

    if not name.strip():
        return current_manager, create_layer_status_html(current_manager), update_layer_selector_choices(current_manager), "Please enter a layer name"

    # ์ค‘๋ณต ์ด๋ฆ„ ์ฒดํฌ
    for layer_id, layer in current_manager.layers.items():
        if layer['name'] == name.strip():
            return current_manager, create_layer_status_html(current_manager), update_layer_selector_choices(current_manager), f"Layer name '{name}' already exists"

    layer_id = current_manager.create_layer(name.strip())
    current_manager.set_current_layer(layer_id)

    return current_manager, create_layer_status_html(current_manager), update_layer_selector_choices(current_manager), f"Layer '{name}' created"

def create_layer_status_html(current_manager):
    """๋ ˆ์ด์–ด ์ƒํƒœ ํ‘œ์‹œ HTML ์ƒ์„ฑ (์‹œ๊ฐ์  ํ‘œ์‹œ๋งŒ)"""
    if not current_manager.layers:
        return "<div style='padding: 10px; text-align: center; color: #888;'>No layers created</div>"
    
    html = "<div style='display: flex; flex-wrap: wrap; gap: 8px; padding: 10px;'>"
    
    for layer_id, layer in current_manager.layers.items():
        is_active = (current_manager.current_layer_id == layer_id)
        
        # ์ƒ‰์ƒ ์ถ”์ถœ
        r, g, b = layer['color']
        color_hex = f"#{r:02x}{g:02x}{b:02x}"
        
        # ํ™œ์„ฑํ™” ์ƒํƒœ์— ๋”ฐ๋ฅธ ์Šคํƒ€์ผ
        if is_active:
            style = f"""

                background: linear-gradient(135deg, {color_hex}, {color_hex}dd);

                color: white;

                border: 3px solid #4682B4;

                box-shadow: 0 4px 12px rgba(70, 130, 180, 0.4);

            """
        else:
            style = f"""

                background: linear-gradient(135deg, {color_hex}aa, {color_hex}77);

                color: white;

                border: 2px solid {color_hex};

                opacity: 0.7;

            """
        
        # ํฌ์ธํŠธ ๊ฐœ์ˆ˜ ๊ณ„์‚ฐ (ํฌ์ง€ํ‹ฐ๋ธŒ/๋„ค๊ฑฐํ‹ฐ๋ธŒ ๊ตฌ๋ถ„)
        positive_points = sum(1 for label in layer['point_labels'] if label == 1)
        negative_points = sum(1 for label in layer['point_labels'] if label == 0)
        masks_count = len(layer['masks'])
        has_mask = masks_count > 0
        
        # ์ƒํƒœ ์•„์ด์ฝ˜
        status_icon = "[OK]" if has_mask else "[ ]"
        
        html += f"""

        <div style="{style}

                    padding: 12px 20px;

                    border-radius: 8px;

                    font-weight: 600;

                    font-size: 14px;

                    min-width: 150px;">

            {status_icon} {layer['name']}<br>

            <small style='font-size: 11px; opacity: 0.9;'>

                <span style='color: #ffcccc;'>+{positive_points}</span> 

                <span style='color: #ccccff;'>-{negative_points}</span> 

                {masks_count}mask

            </small>

        </div>

        """
    
    html += "</div>"
    return html

def click_on_image(current_manager, image, point_mode, evt: gr.SelectData):
    """์ด๋ฏธ์ง€ ํด๋ฆญ ์ฒ˜๋ฆฌ - Include/Exclude ๋ชจ๋“œ์— ๋”ฐ๋ผ ํฌ์ธํŠธ ์ถ”๊ฐ€"""
    if current_manager is None:
        current_manager = LayerManager()
    
    if image is None or current_manager.current_layer_id is None:
        return image, current_manager, create_layer_status_html(current_manager), "Please select image and layer"

    x, y = evt.index
    
    # ํฌ์ธํŠธ ๋ชจ๋“œ์— ๋”ฐ๋ผ ๋ ˆ์ด๋ธ” ๊ฒฐ์ • (positive=1, negative=0)
    label = 1 if point_mode == "positive" else 0
    
    layer_name = current_manager.layers[current_manager.current_layer_id]['name']
    print(f"\n[click_on_image] ================")
    print(f"[click_on_image] Layer: {layer_name}")
    print(f"[click_on_image] Point mode: {point_mode}, Label: {label}, Position: ({x}, {y})")
    
    current_manager.add_point_to_layer(current_manager.current_layer_id, [x, y], label)

    # ํฌ์ธํŠธ ํ‘œ์‹œ๋œ ์ด๋ฏธ์ง€ ์ƒ์„ฑ (์›๋ณธ ์ด๋ฏธ์ง€์— ํฌ์ธํŠธ ํ‘œ์‹œ)
    result_image = draw_points_on_image(image, current_manager)
    
    mode_text = "Include" if label == 1 else "Exclude"
    
    return result_image, current_manager, create_layer_status_html(current_manager), f"{mode_text} point added to '{layer_name}' at ({x}, {y})"

def segment_all_layers(current_manager, image):
    """๋ชจ๋“  ๋ ˆ์ด์–ด๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜ ์‹คํ–‰"""
    if current_manager is None:
        current_manager = LayerManager()
    
    if image is None:
        return None, current_manager, create_layer_status_html(current_manager), "Please upload an image", pd.DataFrame()
    
    if not current_manager.layers:
        return None, current_manager, create_layer_status_html(current_manager), "Please create layers first", pd.DataFrame()

    try:
        print(f"\n[segment_all_layers] Starting segmentation for all layers...")
        segmented_count = 0
        skipped_count = 0
        
        # ๋ชจ๋“  ๋ ˆ์ด์–ด๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜
        for layer_id, layer in current_manager.layers.items():
            layer_name = layer['name']
            
            # ํฌ์ธํŠธ๊ฐ€ ์—†๋Š” ๋ ˆ์ด์–ด๋Š” ๊ฑด๋„ˆ๋›ฐ๊ธฐ
            if not layer['points']:
                print(f"[segment_all_layers] Skipping '{layer_name}' - no points")
                skipped_count += 1
                continue
            
            print(f"\n[segment_all_layers] Processing layer: {layer_name}")
            print(f"[segment_all_layers] Points: {len(layer['points'])}, Labels: {layer['point_labels']}")
            
            # Load models if needed
            if not load_models():
                print(f"[segment_all_layers] Failed to load models for layer: {layer_name}")
                continue

            # SAM3 Tracker๋กœ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜
            points_list = layer['points']
            labels_list = layer['point_labels']

            input_points = [[points_list]]
            input_labels = [[labels_list]]

            # Use the same device as the model
            model_device = next(TRK_MODEL.parameters()).device
            inputs = TRK_PROCESSOR(images=image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model_device)

            with torch.no_grad():
                outputs = TRK_MODEL(**inputs, multimask_output=False)

            masks = TRK_PROCESSOR.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"], binarize=True)[0]

            # ๋ ˆ์ด์–ด์— ๋งˆ์Šคํฌ ์ถ”๊ฐ€
            current_manager.add_mask_to_layer(layer_id, masks[0])
            segmented_count += 1
            print(f"[segment_all_layers] Completed '{layer_name}'")

        # ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์ƒ์„ฑ (ํฌ์ธํŠธ ํฌํ•จ)
        result_image = compose_all_layers(image, current_manager, 0.5, 2)  # ๊ธฐ๋ณธ๊ฐ’ ์‚ฌ์šฉ
        result_image = draw_points_on_image(result_image, current_manager)

        # ๋ฉด์  ๋ถ„์„
        total_pixels = image.size[0] * image.size[1]
        ratios = calculate_total_area_ratio(current_manager, total_pixels)
        chart_data = create_area_chart_data(ratios)
        
        status_msg = f"Segmentation completed! Processed: {segmented_count} layers, Skipped: {skipped_count} layers"
        print(f"\n[segment_all_layers] {status_msg}")

        return result_image, current_manager, create_layer_status_html(current_manager), status_msg, chart_data

    except Exception as e:
        import traceback
        print(f"[segment_all_layers] Error: {str(e)}")
        traceback.print_exc()
        return None, current_manager, create_layer_status_html(current_manager), f"Error: {str(e)}", pd.DataFrame()

def clear_current_layer(current_manager, image):
    """ํ˜„์žฌ ๋ ˆ์ด์–ด ์ดˆ๊ธฐํ™”"""
    if current_manager is None:
        current_manager = LayerManager()
    
    if current_manager.current_layer_id:
        current_manager.clear_current_layer()

        if image:
            result_image = compose_all_layers(image, current_manager, 0.5, 2)  # ๊ธฐ๋ณธ๊ฐ’ ์‚ฌ์šฉ
            result_image = draw_points_on_image(result_image, current_manager)
        else:
            result_image = None

        total_pixels = image.size[0] * image.size[1] if image else 0
        ratios = calculate_total_area_ratio(current_manager, total_pixels)
        chart_data = create_area_chart_data(ratios)

        return result_image, current_manager, create_layer_status_html(current_manager), "Layer cleared", chart_data

    return None, current_manager, create_layer_status_html(current_manager), "Please select a layer", pd.DataFrame()

def refresh_visualization(current_manager, image, opacity, border_width):
    """์‹œ๊ฐํ™” ์ƒˆ๋กœ๊ณ ์นจ"""
    if current_manager is None:
        current_manager = LayerManager()
    
    if image is None:
        return None, "Please upload an image", pd.DataFrame()

    result_image = compose_all_layers(image, current_manager, opacity, border_width)
    result_image = draw_points_on_image(result_image, current_manager)

    total_pixels = image.size[0] * image.size[1]
    ratios = calculate_total_area_ratio(current_manager, total_pixels)
    chart_data = create_area_chart_data(ratios)

    return result_image, "Visualization updated", chart_data


# ============ GRADIO INTERFACE ============
# No custom JavaScript needed anymore
custom_js = ""

with gr.Blocks() as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown("# **SAM3 Layer Segmentation Tool**", elem_id="main-title")
        gr.Markdown("**Layer-based object separation and area analysis tool** | 1. Create layers 2. Select point mode and click 3. Run segmentation (processes all layers)")

        with gr.Row():
            with gr.Column(scale=1):
                img_input = gr.Image(type="pil", label="Upload Image", interactive=True, height=400)

                # ๋ ˆ์ด์–ด ์ƒ์„ฑ
                with gr.Row():
                    layer_name_input = gr.Textbox(label="Layer Name", placeholder="e.g. bench, tree, person")
                    create_layer_btn = gr.Button("Create", variant="primary")

                # ๋ ˆ์ด์–ด ์ƒํƒœ ํ‘œ์‹œ
                gr.Markdown("### Layers Status")
                layer_buttons_html = gr.HTML("<div style='padding: 10px; text-align: center; color: #888;'>No layers created</div>")
                
                # ๋ ˆ์ด์–ด ์„ ํƒ (๋ผ๋””์˜ค ๋ฒ„ํŠผ์œผ๋กœ ๋ณ€๊ฒฝ)
                layer_selector = gr.Radio(label="Select Layer to Add Points", choices=[], interactive=True, value=None)
                
                # ํฌ์ธํŠธ ๋ชจ๋“œ ์„ ํƒ
                gr.Markdown("### Point Mode")
                with gr.Row():
                    include_btn = gr.Button("Include Point", variant="primary", size="sm")
                    exclude_btn = gr.Button("Exclude Point", variant="secondary", size="sm")
                
                point_mode_text = gr.Textbox(label="Current Mode", value="Include Point (Red)", interactive=False)
                
                # ํฌ์ธํŠธ ์•ˆ๋‚ด
                gr.Markdown("""

                **Instructions:**

                - Select a layer from dropdown

                - Choose point mode (Include/Exclude)

                - Click on image to add point

                - **Red circle (โ—)**: Include this area

                - **Blue circle with X**: Exclude this area

                """)

                # ์ปจํŠธ๋กค
                with gr.Row():
                    segment_btn = gr.Button("Run All Segmentation", variant="primary", size="lg")
                    clear_btn = gr.Button("Clear Current Layer", variant="secondary")

                # ์ƒํƒœ
                status_text = gr.Textbox(label="Status", interactive=False)
                st_layer_manager = gr.State(None)  # LayerManager๋Š” ํ•จ์ˆ˜ ๋‚ด์—์„œ ์ƒ์„ฑ
                point_mode_state = gr.State("positive")  # "positive" or "negative"

            with gr.Column(scale=2):
                img_output = gr.Image(type="pil", label="Segmentation Result", height=400, interactive=False)

                # ๋ฉด์  ํ…Œ์ด๋ธ”
                area_table = gr.Dataframe(
                    label="Area Ratio by Layer"
                )

                # ์„ค์ • - ์™„์ „ํžˆ ์ œ๊ฑฐ (API ์Šคํ‚ค๋งˆ ์ถฉ๋Œ ๋ฐฉ์ง€)
                # Visualization settings removed temporarily

        # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
        create_layer_btn.click(
            create_new_layer,
            inputs=[layer_name_input, st_layer_manager],
            outputs=[st_layer_manager, layer_buttons_html, layer_selector, status_text]
        )
        
        # ๋ ˆ์ด์–ด ์„ ํƒ
        def on_layer_select(selected_name, mgr):
            if mgr is None:
                mgr = LayerManager()

            if selected_name:
                # ์ด๋ฆ„์œผ๋กœ layer_id ์ฐพ๊ธฐ
                layer_id = None
                for lid, layer in mgr.layers.items():
                    if layer['name'] == selected_name:
                        layer_id = lid
                        break

                if layer_id:
                    mgr.set_current_layer(layer_id)
                    return mgr, create_layer_status_html(mgr), f"Layer '{selected_name}' selected"
            return mgr, create_layer_status_html(mgr), "Please select a layer"

        layer_selector.change(
            on_layer_select,
            inputs=[layer_selector, st_layer_manager],
            outputs=[st_layer_manager, layer_buttons_html, status_text]
        )
        
        # ํฌ์ธํŠธ ๋ชจ๋“œ ๋ณ€๊ฒฝ
        def set_include_mode():
            return "positive", "Include Point (Red)"
        
        def set_exclude_mode():
            return "negative", "Exclude Point (Blue)"
        
        include_btn.click(
            set_include_mode,
            outputs=[point_mode_state, point_mode_text]
        )
        
        exclude_btn.click(
            set_exclude_mode,
            outputs=[point_mode_state, point_mode_text]
        )

        # ์ด๋ฏธ์ง€ ํด๋ฆญ ์ด๋ฒคํŠธ - img_input๊ณผ img_output ๋ชจ๋‘์—์„œ ํด๋ฆญ ๋ฐ›๊ธฐ
        img_input.select(
            click_on_image,
            inputs=[st_layer_manager, img_input, point_mode_state],
            outputs=[img_output, st_layer_manager, layer_buttons_html, status_text]
        )
        
        img_output.select(
            click_on_image,
            inputs=[st_layer_manager, img_input, point_mode_state],
            outputs=[img_output, st_layer_manager, layer_buttons_html, status_text]
        )

        # ๋ชจ๋“  ๋ ˆ์ด์–ด ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜ ์‹คํ–‰
        segment_btn.click(
            segment_all_layers,
            inputs=[st_layer_manager, img_input],
            outputs=[img_output, st_layer_manager, layer_buttons_html, status_text, area_table]
        )

        clear_btn.click(
            clear_current_layer,
            inputs=[st_layer_manager, img_input],
            outputs=[img_output, st_layer_manager, layer_buttons_html, status_text, area_table]
        )

        # ํˆฌ๋ช…๋„ ๋ฐ ํ…Œ๋‘๋ฆฌ ์Šฌ๋ผ์ด๋” ์‹ค์‹œ๊ฐ„ ์—…๋ฐ์ดํŠธ - ์ผ์‹œ์ ์œผ๋กœ ๋น„ํ™œ์„ฑํ™”
        # opacity_slider.change(
        #     refresh_visualization,
        #     inputs=[st_layer_manager, img_input, opacity_slider, border_slider],
        #     outputs=[img_output, status_text, area_table]
        # )

        # border_slider.change(
        #     refresh_visualization,
        #     inputs=[st_layer_manager, img_input, opacity_slider, border_slider],
        #     outputs=[img_output, status_text, area_table]
        # )

        # ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ์‹œ ์ดˆ๊ธฐํ™”
        def on_image_upload(img):
            new_manager = LayerManager()
            empty_html = "<div style='padding: 10px; text-align: center; color: #888;'>No layers created</div>"
            # ์—…๋กœ๋“œํ•œ ์ด๋ฏธ์ง€๋ฅผ ์ถœ๋ ฅ์—๋„ ํ‘œ์‹œ
            return new_manager, img, pd.DataFrame(), empty_html, update_layer_selector_choices(new_manager), "positive", "Include Point (Red)", "New image uploaded"

        img_input.change(
            on_image_upload,
            inputs=[img_input],
            outputs=[st_layer_manager, img_output, area_table, layer_buttons_html, layer_selector, point_mode_state, point_mode_text, status_text]
        )

@spaces.GPU
def run_spaces():
    _launch_compat(demo, ssr=False)

def run_local():
    _launch_compat(demo, show_error=True, ssr=False)

if __name__ == "__main__":
    # Hugging Spaces ํ™˜๊ฒฝ ๊ฐ์ง€
    import os
    if os.getenv("SPACE_ID"):
        run_spaces()
    else:
        run_local()