File size: 31,217 Bytes
71139a9
f3d3559
71139a9
 
 
 
e312782
71139a9
 
 
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
 
f3d3559
71139a9
f3d3559
 
 
 
ed1b7ea
f3d3559
71139a9
 
ed1b7ea
71139a9
f3d3559
71139a9
f3d3559
 
 
 
71139a9
f3d3559
 
71139a9
 
 
 
 
 
 
 
 
f3d3559
71139a9
 
f3d3559
71139a9
 
f3d3559
71139a9
 
f3d3559
 
 
71139a9
f3d3559
 
 
 
 
71139a9
f3d3559
 
 
 
 
 
 
 
 
 
 
 
71139a9
 
 
 
f3d3559
71139a9
 
f3d3559
ed1b7ea
f3d3559
 
 
 
 
 
71139a9
00f618e
 
f3d3559
 
 
00f618e
71139a9
ed1b7ea
71139a9
 
f3d3559
 
 
71139a9
 
f3d3559
71139a9
 
 
ed1b7ea
71139a9
f3d3559
 
 
71139a9
 
ed1b7ea
 
 
71139a9
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
f3d3559
 
 
 
 
 
 
71139a9
f3d3559
 
 
 
 
 
 
71139a9
 
f3d3559
 
 
 
 
 
 
 
71139a9
ed1b7ea
71139a9
ed1b7ea
71139a9
 
f3d3559
71139a9
 
 
 
 
 
f3d3559
 
 
ed1b7ea
71139a9
f3d3559
 
 
 
 
 
 
 
 
71139a9
 
 
f3d3559
 
 
ed1b7ea
71139a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d3559
 
71139a9
 
ed1b7ea
f3d3559
f91c3fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
f3d3559
f91c3fb
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
f91c3fb
f3d3559
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed1b7ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
6a53904
 
 
 
 
 
71139a9
 
 
f3d3559
 
 
 
 
 
 
 
 
71139a9
 
f3d3559
71139a9
f3d3559
ed1b7ea
f3d3559
 
ed1b7ea
f3d3559
 
 
ed1b7ea
f3d3559
71139a9
f3d3559
 
 
6a53904
 
71139a9
6a53904
71139a9
6a53904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
ed1b7ea
f3d3559
71139a9
f3d3559
 
 
6a53904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d3559
71139a9
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
 
 
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
f3d3559
 
 
 
 
 
 
 
 
 
 
71139a9
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71139a9
f3d3559
71139a9
 
f3d3559
 
 
 
71139a9
f3d3559
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
 
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
 
ed1b7ea
f3d3559
 
 
 
 
 
 
 
 
 
 
ed1b7ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d3559
71139a9
 
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
import gradio
import gradio_image_annotation
import gradio_imageslider
import spaces
import torch

import src.SegmentAnything2Assist.SegmentAnything2Assist as SegmentAnything2Assist

example_image_annotation = {
    "image": "assets/cars.jpg",
    "boxes": [
        {
            "label": "+",
            "color": (0, 255, 0),
            "xmin": 886,
            "ymin": 551,
            "xmax": 886,
            "ymax": 551,
        },
        {
            "label": "-",
            "color": (255, 0, 0),
            "xmin": 1239,
            "ymin": 576,
            "xmax": 1239,
            "ymax": 576,
        },
        {
            "label": "-",
            "color": (255, 0, 0),
            "xmin": 610,
            "ymin": 574,
            "xmax": 610,
            "ymax": 574,
        },
        {
            "label": "",
            "color": (0, 0, 255),
            "xmin": 254,
            "ymin": 466,
            "xmax": 1347,
            "ymax": 1047,
        },
    ],
}


VERBOSE = True
DEBUG = False


segment_anything2assist = SegmentAnything2Assist.SegmentAnything2Assist(
    sam_model_name="sam2_hiera_tiny", device=torch.device("cuda")
)


def change_base_model(model_name, device):
    global segment_anything2assist
    gradio.Info(f"Changing model to {model_name} on {device}", duration=3)
    try:
        segment_anything2assist = SegmentAnything2Assist.SegmentAnything2Assist(
            model_name=model_name, device=torch.device(device)
        )
        gradio.Info(f"Model has been changed to {model_name} on {device}", duration=5)
    except:
        gradio.Error(f"Model could not be changed", duration=5)


def __post_process_annotator_inputs(value):
    if VERBOSE:
        print("SegmentAnything2AssistApp::____post_process_annotator_inputs::Called.")
    __current_mask, __current_segment = None, None
    new_boxes = []
    __image_point_coords = []
    __image_point_labels = []
    __image_box = []

    b_has_box = False
    for box in value["boxes"]:
        if box["label"] == "":
            if not b_has_box:
                new_box = box.copy()
                new_box["color"] = (0, 0, 255)
                new_boxes.append(new_box)
                b_has_box = True
            __image_box = [box["xmin"], box["ymin"], box["xmax"], box["ymax"]]

        elif box["label"] == "+" or box["label"] == "-":
            new_box = box.copy()
            new_box["color"] = (0, 255, 0) if box["label"] == "+" else (255, 0, 0)
            new_box["xmin"] = int((box["xmin"] + box["xmax"]) / 2)
            new_box["ymin"] = int((box["ymin"] + box["ymax"]) / 2)
            new_box["xmax"] = new_box["xmin"]
            new_box["ymax"] = new_box["ymin"]
            new_boxes.append(new_box)

            __image_point_coords.append([new_box["xmin"], new_box["ymin"]])
            __image_point_labels.append(1 if box["label"] == "+" else 0)

    if len(__image_box) == 0:
        __image_box = None

    if len(__image_point_coords) == 0:
        __image_point_coords = None

    if len(__image_point_labels) == 0:
        __image_point_labels = None

    if VERBOSE:
        print("SegmentAnything2AssistApp::____post_process_annotator_inputs::Done.")

    return __image_point_coords, __image_point_labels, __image_box


@spaces.GPU(duration=60)
def generate_image_mask(
    value,
    mask_threshold,
    max_hole_area,
    max_sprinkle_area,
    image_output_mode,
):
    global segment_anything2assist

    # Force post processing of annotated image
    image_point_coords, image_point_labels, image_box = __post_process_annotator_inputs(
        value
    )

    if VERBOSE:
        print("SegmentAnything2AssistApp::generate_image_mask::Called.")
    mask_chw, mask_iou = segment_anything2assist.generate_masks_from_image(
        value["image"],
        image_point_coords,
        image_point_labels,
        image_box,
        mask_threshold,
        max_hole_area,
        max_sprinkle_area,
    )

    if VERBOSE:
        print("SegmentAnything2AssistApp::generate_image_mask::Masks generated.")

    __current_mask, __current_segment = segment_anything2assist.apply_mask_to_image(
        value["image"], mask_chw[0]
    )

    if VERBOSE:
        print(
            "SegmentAnything2AssistApp::generate_image_mask::Masks and Segments created."
        )

    __image_box = gradio.DataFrame(value=[[]])
    __image_point_coords = gradio.DataFrame(value=[[]])
    if DEBUG:
        __image_box = gradio.DataFrame(
            value=[image_box],
            label="Box",
            interactive=False,
            headers=["XMin", "YMin", "XMax", "YMax"],
        )
        x = []
        for i, _ in enumerate(image_point_coords):
            x.append(
                [
                    image_point_labels[i],
                    image_point_coords[i][0],
                    image_point_coords[i][1],
                ]
            )
        __image_point_coords = gradio.DataFrame(
            value=x,
            label="Point Coords",
            interactive=False,
            headers=["Label", "X", "Y"],
        )

    if image_output_mode == "Mask":
        return (
            [value["image"], __current_mask],
            __image_point_coords,
            __image_box,
            __current_mask,
            __current_segment,
        )
    elif image_output_mode == "Segment":
        return (
            [value["image"], __current_segment],
            __image_point_coords,
            __image_box,
            __current_mask,
            __current_segment,
        )
    else:
        gradio.Warning("This is an issue, please report the problem!", duration=5)
        return (
            gradio_imageslider.ImageSlider(render=True),
            __image_point_coords,
            __image_box,
            __current_mask,
            __current_segment,
        )


def on_image_output_mode_change(image_input, radio, __current_mask, __current_segment):
    if VERBOSE:
        print("SegmentAnything2AssistApp::generate_image_mask::Called.")
    if __current_mask is None or __current_segment is None:
        gradio.Warning("Configuration was changed, generate the mask again", duration=5)
        return gradio_imageslider.ImageSlider(render=True)
    if radio == "Mask":
        return [image_input["image"], __current_mask]
    elif radio == "Segment":
        return [image_input["image"], __current_segment]
    else:
        gradio.Warning("This is an issue, please report the problem!", duration=5)
        return gradio_imageslider.ImageSlider(render=True)


def __generate_auto_mask(image, auto_list, auto_mode, auto_bbox_mode, masks, bboxes):
    global segment_anything2assist

    # When value from gallery is called, it is a tuple
    if type(masks[0]) == tuple:
        masks = [mask[0] for mask in masks]

    image_with_bbox, mask, segment = segment_anything2assist.apply_auto_mask_to_image(
        image, [int(i) - 1 for i in auto_list], masks, bboxes
    )

    output_1 = image_with_bbox if auto_bbox_mode else image
    output_2 = mask if auto_mode == "Mask" else segment
    return [output_1, output_2]


@spaces.GPU(duration=60)
def generate_auto_mask(
    image,
    points_per_side,
    points_per_batch,
    pred_iou_thresh,
    stability_score_thresh,
    stability_score_offset,
    mask_threshold,
    box_nms_thresh,
    crop_n_layers,
    crop_nms_thresh,
    crop_overlay_ratio,
    crop_n_points_downscale_factor,
    min_mask_region_area,
    use_m2m,
    multimask_output,
    output_mode,
):
    global segment_anything2assist
    if VERBOSE:
        print("SegmentAnything2AssistApp::generate_auto_mask::Called.")

    masks, bboxes, predicted_iou, stability_score = (
        segment_anything2assist.generate_automatic_masks(
            image,
            points_per_side,
            points_per_batch,
            pred_iou_thresh,
            stability_score_thresh,
            stability_score_offset,
            mask_threshold,
            box_nms_thresh,
            crop_n_layers,
            crop_nms_thresh,
            crop_overlay_ratio,
            crop_n_points_downscale_factor,
            min_mask_region_area,
            use_m2m,
            multimask_output,
        )
    )

    if len(masks) == 0:
        gradio.Warning(
            "No masks generated, please tweak the advanced parameters.", duration=5
        )
        return (
            gradio_imageslider.ImageSlider(),
            gradio.CheckboxGroup([], value=[], label="Mask List", interactive=False),
            gradio.Checkbox(value=False, label="Show Bounding Box", interactive=False),
            gradio.Gallery(
                None, label="Output Gallery", interactive=False, type="numpy"
            ),
            gradio.DataFrame(
                value=[[]],
                label="Box",
                interactive=False,
                headers=["XMin", "YMin", "XMax", "YMax"],
            ),
        )
    else:
        choices = [str(i) for i in range(len(masks))]

        returning_image = __generate_auto_mask(
            image, ["0"], output_mode, False, masks, bboxes
        )
        return (
            returning_image,
            gradio.CheckboxGroup(
                choices, value=["0"], label="Mask List", interactive=True
            ),
            gradio.Checkbox(value=False, label="Show Bounding Box", interactive=True),
            gradio.Gallery(
                masks, label="Output Gallery", interactive=True, type="numpy"
            ),
            gradio.DataFrame(
                value=bboxes,
                label="Box",
                interactive=False,
                headers=["XMin", "YMin", "XMax", "YMax"],
                type="array",
            ),
        )


def __generate_yolo_mask(
    image,
    yolo_mask,
    output_mode,
):
    global segment_anything2assist
    if VERBOSE:
        print("SegmentAnything2AssistApp::generate_yolo_mask::Called.")

    mask = yolo_mask[4]

    if output_mode == "Mask":
        return [image, mask]

    mask, output_image = segment_anything2assist.apply_mask_to_image(image, mask)

    if output_mode == "Segment":
        return [image, output_image]


@spaces.GPU(duration=60)
def generate_yolo_mask(
    image,
    yolo_model_choice,
    mask_threshold,
    max_hole_area,
    max_sprinkle_area,
    output_mode,
):
    global segment_anything2assist
    if VERBOSE:
        print("SegmentAnything2AssistApp::generate_yolo_mask::Called.")

    results = segment_anything2assist.generate_mask_from_image_with_yolo(
        image,
        YOLOv10ModelName=yolo_model_choice,
        mask_threshold=mask_threshold,
        max_hole_area=max_hole_area,
        max_sprinkle_area=max_sprinkle_area,
    )

    if len(results) > 0:
        if VERBOSE:
            print("SegmentAnything2AssistApp::generate_yolo_mask::Masks generated.")

        yolo_masks = []
        for result in results:
            yolo_mask = [
                result["name"],
                result["class"],
                result["confidence"],
                [result["box"]],
                result["mask_chw"],
                result["mask_iou"][0].item(),
            ]
            yolo_masks.append(yolo_mask)

        return __generate_yolo_mask(image, yolo_masks[0], output_mode), gradio.Dataset(
            label="YOLOv10 Assisted Masks", type="values", samples=yolo_masks
        )

    else:
        if VERBOSE:
            print("SegmentAnything2AssistApp::generate_yolo_mask::No masks generated.")

        return gradio.ImageSlider(), gradio.Dataset()


with gradio.Blocks() as base_app:
    gradio.Markdown(
        """
        <h1 style="text-align: center;">Segment Anything 2 Assist πŸš€</h1>
        <p style="text-align: center;">A tool for advanced image segmentation and annotation. πŸ–ΌοΈβœοΈ</p>
        """
    )
    with gradio.Row():
        with gradio.Column():
            base_model_choice = gradio.Dropdown(
                [
                    "sam2_hiera_large",
                    "sam2_hiera_small",
                    "sam2_hiera_base_plus",
                    "sam2_hiera_tiny",
                ],
                value="sam2_hiera_tiny",
                label="Model Choice",
            )
        with gradio.Column():
            base_gpu_choice = gradio.Dropdown(
                ["cpu", "cuda"], value="cuda", label="Device Choice"
            )
    base_model_choice.change(
        change_base_model, inputs=[base_model_choice, base_gpu_choice]
    )
    base_gpu_choice.change(
        change_base_model, inputs=[base_model_choice, base_gpu_choice]
    )

    # Image Segmentation
    with gradio.Tab(label="πŸŒ† Image Segmentation", id="image_tab") as image_tab:
        gradio.Markdown("Image Segmentation", render=True)
        with gradio.Column():
            with gradio.Accordion("Image Annotation Documentation", open=False):
                gradio.Markdown(
                    """
                    ### πŸ–ΌοΈ Image Annotation Documentation

                    Image annotation allows you to mark specific regions of an image with labels. 
                    In this app, you can annotate an image by drawing bounding boxes and/or making points on the image. 
                    The labels can be either '+' or '-'. 

                    **πŸ“ How to Annotate an Image:**
                    - Bounding Box: Click and drag to draw a box around the desired region.
                    - Positive or Negative Points: Draw a small box (note that the center point will be used for the annotation) and add either "+" or "-" as the label respectively.

                    **🎨 Generating Masks:**
                    - Once you have annotated the image, click the 'Generate Mask' button to generate a mask based on the annotations.
                    - The mask can be either a binary mask or a segmented mask, depending on the selected output mode.
                    - You can switch between the output modes using the radio buttons.
                    - If you make any changes to the annotations or the output mode, you need to regenerate the mask by clicking the button again.

                    **βš™οΈ Advanced Options:**
                    - The advanced options allow you to adjust the SAM mask threshold, maximum hole area, and maximum sprinkle area.
                    - These options control the sensitivity and accuracy of the segmentation process.
                    - Experiment with different settings to achieve the desired results.
                    """
                )
            image_input = gradio_image_annotation.image_annotator(
                example_image_annotation
            )
            with gradio.Accordion("Advanced Options", open=False):
                image_generate_SAM_mask_threshold = gradio.Slider(
                    0.0, 1.0, 0.0, label="SAM Mask Threshold"
                )
                image_generate_SAM_max_hole_area = gradio.Slider(
                    0, 1000, 0, label="SAM Max Hole Area"
                )
                image_generate_SAM_max_sprinkle_area = gradio.Slider(
                    0, 1000, 0, label="SAM Max Sprinkle Area"
                )
            image_generate_mask_button = gradio.Button("Generate Mask")
            with gradio.Row():
                with gradio.Column():
                    image_output_mode = gradio.Radio(
                        ["Segment", "Mask"], value="Segment", label="Output Mode"
                    )
                with gradio.Column(scale=3):
                    image_output = gradio_imageslider.ImageSlider()

            with gradio.Accordion("Debug", open=DEBUG, visible=DEBUG):
                __image_point_coords = gradio.DataFrame(
                    value=[["+", 886, 551], ["-", 1239, 576]],
                    label="Point Coords",
                    interactive=False,
                    headers=["Label", "X", "Y"],
                )
                __image_box = gradio.DataFrame(
                    value=[[254, 466, 1347, 1047]],
                    label="Box",
                    interactive=False,
                    headers=["XMin", "YMin", "XMax", "YMax"],
                )
                __current_mask = gradio.Image(label="Current Mask", interactive=False)
                __current_segment = gradio.Image(
                    label="Current Segment", interactive=False
                )

            # image_input.change(__post_process_annotator_inputs, inputs = [image_input])
            image_generate_mask_button.click(
                generate_image_mask,
                inputs=[
                    image_input,
                    image_generate_SAM_mask_threshold,
                    image_generate_SAM_max_hole_area,
                    image_generate_SAM_max_sprinkle_area,
                    image_output_mode,
                ],
                outputs=[
                    image_output,
                    __image_point_coords,
                    __image_box,
                    __current_mask,
                    __current_segment,
                ],
            )
            image_output_mode.change(
                on_image_output_mode_change,
                inputs=[
                    image_input,
                    image_output_mode,
                    __current_mask,
                    __current_segment,
                ],
                outputs=[image_output],
            )

    # Auto Segmentation
    with gradio.Tab(label="πŸ€– Auto Segmentation", id="auto_tab"):
        gradio.Markdown("Auto Segmentation", render=True)
        with gradio.Column():
            with gradio.Accordion("Auto Annotation Documentation", open=False):
                gradio.Markdown(
                    """
                    ### πŸ–ΌοΈ Auto Annotation Documentation

                    Auto annotation allows you to automatically generate masks for an image based on advanced parameters. 
                    In this app, you can configure various settings to control the mask generation process.

                    **πŸ“ How to Use Auto Annotation:**
                    - Upload or select an image.
                    - Adjust the advanced options to fine-tune the mask generation process.
                    - Click the 'Generate Auto Mask' button to generate masks automatically.

                    **βš™οΈ Advanced Options:**
                    - **Points Per Side:** Number of points to sample per side of the image.
                    - **Points Per Batch:** Number of points to process in each batch.
                    - **Pred IOU Threshold:** Threshold for the predicted Intersection over Union (IOU) score.
                    - **Stability Score Threshold:** Threshold for the stability score.
                    - **Stability Score Offset:** Offset for the stability score.
                    - **Mask Threshold:** Threshold for the mask generation.
                    - **Box NMS Threshold:** Non-Maximum Suppression (NMS) threshold for boxes.
                    - **Crop N Layers:** Number of layers to crop.
                    - **Crop NMS Threshold:** NMS threshold for crops.
                    - **Crop Overlay Ratio:** Overlay ratio for crops.
                    - **Crop N Points Downscale Factor:** Downscale factor for the number of points in crops.
                    - **Min Mask Region Area:** Minimum area for mask regions.
                    - **Use M2M:** Whether to use M2M (Mask-to-Mask) refinement.
                    - **Multi Mask Output:** Whether to generate multiple masks.

                    **🎨 Generating Masks:**
                    - Once you have configured the advanced options, click the 'Generate Auto Mask' button.
                    - The masks will be generated automatically based on the selected parameters.
                    - You can view the generated masks and adjust the settings if needed.
                    """
                )
            auto_input = gradio.Image("assets/cars.jpg")
            with gradio.Accordion("Advanced Options", open=False):
                auto_generate_SAM_points_per_side = gradio.Slider(
                    1, 64, 12, 1, label="Points Per Side", interactive=True
                )
                auto_generate_SAM_points_per_batch = gradio.Slider(
                    1, 64, 32, 1, label="Points Per Batch", interactive=True
                )
                auto_generate_SAM_pred_iou_thresh = gradio.Slider(
                    0.0, 1.0, 0.8, 1, label="Pred IOU Threshold", interactive=True
                )
                auto_generate_SAM_stability_score_thresh = gradio.Slider(
                    0.0, 1.0, 0.95, label="Stability Score Threshold", interactive=True
                )
                auto_generate_SAM_stability_score_offset = gradio.Slider(
                    0.0, 1.0, 1.0, label="Stability Score Offset", interactive=True
                )
                auto_generate_SAM_mask_threshold = gradio.Slider(
                    0.0, 1.0, 0.0, label="Mask Threshold", interactive=True
                )
                auto_generate_SAM_box_nms_thresh = gradio.Slider(
                    0.0, 1.0, 0.7, label="Box NMS Threshold", interactive=True
                )
                auto_generate_SAM_crop_n_layers = gradio.Slider(
                    0, 10, 0, 1, label="Crop N Layers", interactive=True
                )
                auto_generate_SAM_crop_nms_thresh = gradio.Slider(
                    0.0, 1.0, 0.7, label="Crop NMS Threshold", interactive=True
                )
                auto_generate_SAM_crop_overlay_ratio = gradio.Slider(
                    0.0, 1.0, 512 / 1500, label="Crop Overlay Ratio", interactive=True
                )
                auto_generate_SAM_crop_n_points_downscale_factor = gradio.Slider(
                    1, 10, 1, label="Crop N Points Downscale Factor", interactive=True
                )
                auto_generate_SAM_min_mask_region_area = gradio.Slider(
                    0, 1000, 0, label="Min Mask Region Area", interactive=True
                )
                auto_generate_SAM_use_m2m = gradio.Checkbox(
                    label="Use M2M", interactive=True
                )
                auto_generate_SAM_multimask_output = gradio.Checkbox(
                    value=True, label="Multi Mask Output", interactive=True
                )
            auto_generate_button = gradio.Button("Generate Auto Mask")
            with gradio.Row():
                with gradio.Column():
                    auto_output_mode = gradio.Radio(
                        ["Segment", "Mask"],
                        value="Segment",
                        label="Output Mode",
                        interactive=True,
                    )
                    auto_output_list = gradio.CheckboxGroup(
                        [], value=[], label="Mask List", interactive=False
                    )
                    auto_output_bbox = gradio.Checkbox(
                        value=False, label="Show Bounding Box", interactive=False
                    )
                with gradio.Column(scale=3):
                    auto_output = gradio_imageslider.ImageSlider()
            with gradio.Accordion("Debug", open=DEBUG, visible=DEBUG):
                __auto_output_gallery = gradio.Gallery(
                    None, label="Output Gallery", interactive=False, type="numpy"
                )
                __auto_bbox = gradio.DataFrame(
                    value=[[]],
                    label="Box",
                    interactive=False,
                    headers=["XMin", "YMin", "XMax", "YMax"],
                )

            auto_generate_button.click(
                generate_auto_mask,
                inputs=[
                    auto_input,
                    auto_generate_SAM_points_per_side,
                    auto_generate_SAM_points_per_batch,
                    auto_generate_SAM_pred_iou_thresh,
                    auto_generate_SAM_stability_score_thresh,
                    auto_generate_SAM_stability_score_offset,
                    auto_generate_SAM_mask_threshold,
                    auto_generate_SAM_box_nms_thresh,
                    auto_generate_SAM_crop_n_layers,
                    auto_generate_SAM_crop_nms_thresh,
                    auto_generate_SAM_crop_overlay_ratio,
                    auto_generate_SAM_crop_n_points_downscale_factor,
                    auto_generate_SAM_min_mask_region_area,
                    auto_generate_SAM_use_m2m,
                    auto_generate_SAM_multimask_output,
                    auto_output_mode,
                ],
                outputs=[
                    auto_output,
                    auto_output_list,
                    auto_output_bbox,
                    __auto_output_gallery,
                    __auto_bbox,
                ],
            )
            auto_output_list.change(
                __generate_auto_mask,
                inputs=[
                    auto_input,
                    auto_output_list,
                    auto_output_mode,
                    auto_output_bbox,
                    __auto_output_gallery,
                    __auto_bbox,
                ],
                outputs=[auto_output],
            )
            auto_output_bbox.change(
                __generate_auto_mask,
                inputs=[
                    auto_input,
                    auto_output_list,
                    auto_output_mode,
                    auto_output_bbox,
                    __auto_output_gallery,
                    __auto_bbox,
                ],
                outputs=[auto_output],
            )
            auto_output_mode.change(
                __generate_auto_mask,
                inputs=[
                    auto_input,
                    auto_output_list,
                    auto_output_mode,
                    auto_output_bbox,
                    __auto_output_gallery,
                    __auto_bbox,
                ],
                outputs=[auto_output],
            )

    # YOLOv10 assisted Segmentation.
    with gradio.Tab("πŸ€™ YOLOv10 assisted Segmentation"):
        gradio.Markdown("YOLOv10 assisted Segmentation")
        with gradio.Column():
            with gradio.Accordion("YOLOv10 Documentation", open=False):
                gradio.Markdown(
                    """
                    ### πŸ–ΌοΈ YOLOv10 Assisted Segmentation Documentation

                    YOLOv10 assisted segmentation allows you to generate masks for an image using the YOLOv10 model. 
                    In this app, you can configure various settings to control the mask generation process.

                    **πŸ“ How to Use YOLOv10 Assisted Segmentation:**
                    - Upload or select an image.
                    - Choose the desired YOLOv10 model from the dropdown.
                    - Adjust the advanced settings to fine-tune the mask generation process.
                    - Click the 'Generate YOLOv10 Mask' button to generate masks.

                    **βš™οΈ Advanced Settings:**
                    - **SAM Mask Threshold:** Threshold for the SAM mask generation.
                    - **Max Hole Area:** Maximum area for holes in the mask.
                    - **Max Sprinkle Area:** Maximum area for sprinkled regions in the mask.

                    **🎨 Generating Masks:**
                    - Once you have configured the settings, click the 'Generate YOLOv10 Mask' button.
                    - The masks will be generated based on the selected parameters.
                    - You can view the generated masks and adjust the settings if needed.
                    """
                )

            yolo_input = gradio.Image("assets/cars.jpg")
            yolo_model_choice = gradio.Dropdown(
                choices=["nano", "small", "medium", "base", "large", "xlarge"],
                value="nano",
                label="YOLOv10 Model Choice",
            )
            with gradio.Accordion("Advanced Settings", open=False):
                yolo_generate_SAM_mask_threshold = gradio.Slider(
                    0.0, 1.0, 0.0, label="SAM Mask Threshold"
                )
                yolo_generate_SAM_max_hole_area = gradio.Slider(
                    0, 1000, 0, label="SAM Max Hole Area"
                )
                yolo_generate_SAM_max_sprinkle_area = gradio.Slider(
                    0, 1000, 0, label="SAM Max Sprinkle Area"
                )

            yolo_generate_mask_button = gradio.Button("Generate YOLOv10 Mask")
            with gradio.Row():
                with gradio.Column():
                    yolo_output_mode = gradio.Radio(
                        ["Segment", "Mask"], value="Segment", label="Output Mode"
                    )
                with gradio.Column(scale=3):
                    yolo_output = gradio_imageslider.ImageSlider()

            with gradio.Accordion("Debug 1", open=DEBUG, visible=DEBUG):
                __yolo_name = gradio.Textbox(
                    label="Name", interactive=DEBUG, visible=DEBUG
                )
                __yolo_class = gradio.Number(
                    label="Class", interactive=DEBUG, visible=DEBUG
                )
                __yolo_confidence = gradio.Number(
                    label="Confidence", interactive=DEBUG, visible=DEBUG
                )
                __yolo_box = gradio.DataFrame(
                    value=[[1, 2, 3, 4]], label="Box", interactive=DEBUG, visible=DEBUG
                )
                __yolo_mask = gradio.Image(
                    label="Mask", interactive=DEBUG, visible=DEBUG
                )
                __yolo_mask_iou = gradio.Number(
                    label="Mask IOU", interactive=DEBUG, visible=DEBUG
                )

            with gradio.Row():
                yolo_masks = gradio.Dataset(
                    label="YOLOv10 Assisted Masks",
                    type="values",
                    components=[
                        __yolo_name,
                        __yolo_class,
                        __yolo_confidence,
                        __yolo_box,
                        __yolo_mask,
                        __yolo_mask_iou,
                    ],
                )

            yolo_generate_mask_button.click(
                generate_yolo_mask,
                inputs=[
                    yolo_input,
                    yolo_model_choice,
                    yolo_generate_SAM_mask_threshold,
                    yolo_generate_SAM_max_hole_area,
                    yolo_generate_SAM_max_sprinkle_area,
                    yolo_output_mode,
                ],
                outputs=[yolo_output, yolo_masks],
            )

            yolo_masks.click(
                __generate_yolo_mask,
                inputs=[yolo_input, yolo_masks, yolo_output_mode],
                outputs=[yolo_output],
            )

            yolo_output_mode.change(
                __generate_yolo_mask,
                inputs=[yolo_input, yolo_masks, yolo_output_mode],
                outputs=[yolo_output],
            )


if __name__ == "__main__":
    base_app.launch()