File size: 6,653 Bytes
74593d4
0cc203f
74593d4
 
 
e933213
 
74593d4
 
 
e933213
74593d4
2187069
 
 
 
 
 
 
 
 
 
 
 
 
74593d4
 
2187069
74593d4
 
 
2187069
 
74593d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2187069
74593d4
 
2187069
74593d4
 
 
2187069
 
 
 
 
 
74593d4
 
 
 
 
 
 
 
 
2187069
74593d4
 
 
 
e933213
 
 
 
 
 
 
 
 
 
 
 
74593d4
0cc203f
b01e247
74593d4
 
b01e247
e933213
 
 
 
74593d4
e933213
74593d4
1b33b1c
e933213
 
 
 
1b33b1c
e933213
1fd4203
e933213
 
1b33b1c
 
 
 
 
 
e933213
 
 
 
 
b01e247
1b33b1c
e933213
 
 
 
 
 
 
 
 
1b33b1c
 
e933213
74593d4
 
e933213
74593d4
 
e933213
74593d4
e933213
74593d4
 
2187069
74593d4
e933213
 
 
 
74593d4
e933213
 
 
 
 
 
 
 
 
 
 
05bb57b
e933213
 
0bd7a83
 
e933213
 
 
 
 
 
 
 
 
 
 
 
 
 
5a34082
e933213
 
 
 
 
74593d4
 
480887f
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
import os
import spaces
import gradio as gr
import numpy as np
import torch
import random
from PIL import Image, ImageDraw
from typing import Iterable
from gradio.themes import Soft
from gradio.themes.utils import colors, fonts, sizes
from transformers import Sam3Processor, Sam3Model

colors.steel_blue = colors.Color(
    name="steel_blue",
    c50="#EBF3F8",
    c100="#D3E5F0",
    c200="#A8CCE1",
    c300="#7DB3D2",
    c400="#529AC3",
    c500="#4682B4",
    c600="#3E72A0",
    c700="#36638C",
    c800="#2E5378",
    c900="#264364",
    c950="#1E3450",
)

class SteelBlueTheme(Soft):
    def __init__(
        self,
        *,
        primary_hue: colors.Color | str = colors.gray,
        secondary_hue: colors.Color | str = colors.steel_blue,
        neutral_hue: colors.Color | str = colors.slate,
        text_size: sizes.Size | str = sizes.text_lg,
        font: fonts.Font | str | Iterable[fonts.Font | str] = (
            fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
        ),
        font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
            fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
        ),
    ):
        super().__init__(
            primary_hue=primary_hue,
            secondary_hue=secondary_hue,
            neutral_hue=neutral_hue,
            text_size=text_size,
            font=font,
            font_mono=font_mono,
        )
        super().set(
            background_fill_primary="*primary_50",
            background_fill_primary_dark="*primary_900",
            body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
            body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
            button_primary_text_color="white",
            button_primary_text_color_hover="white",
            button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
            button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
            button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
            button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
            slider_color="*secondary_500",
            slider_color_dark="*secondary_600",
            block_title_text_weight="600",
            block_border_width="3px",
            block_shadow="*shadow_drop_lg",
            button_primary_shadow="*shadow_drop_lg",
            button_large_padding="11px",
            color_accent_soft="*primary_100",
            block_label_background_fill="*primary_200",
        )

steel_blue_theme = SteelBlueTheme()

device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")

try:
    print("Loading SAM3 Model and Processor...")
    model = Sam3Model.from_pretrained("facebook/sam3").to(device)
    processor = Sam3Processor.from_pretrained("facebook/sam3")
    print("Model loaded successfully.")
    
except Exception as e:
    print(f"Error loading model: {e}")
    print("Ensure you have the correct libraries installed and access to the model.")
    # Fallback/Placeholder for demonstration if model doesn't exist in environment yet
    model = None 
    processor = None

@spaces.GPU
def segment_image(input_image, text_prompt, threshold=0.5):
    if input_image is None:
        raise gr.Error("Please upload an image.")
    if not text_prompt:
        raise gr.Error("Please enter a text prompt (e.g., 'cat', 'face').")
    
    if model is None or processor is None:
        raise gr.Error("Model not loaded correctly.")

    # Convert image to RGB
    image_pil = input_image.convert("RGB")

    # Preprocess
    inputs = processor(images=image_pil, text=text_prompt, return_tensors="pt").to(device)

    # Inference
    with torch.no_grad():
        outputs = model(**inputs)

    # Post-process results
    results = processor.post_process_instance_segmentation(
        outputs,
        threshold=threshold,
        mask_threshold=0.5,
        target_sizes=inputs.get("original_sizes").tolist()
    )[0]

    masks = results['masks'] # Boolean tensor [N, H, W]
    scores = results['scores']
    
    # Prepare for Gradio AnnotatedImage
    # Gradio expects (image, [(mask, label), ...])
    
    annotations = []
    masks_np = masks.cpu().numpy()
    scores_np = scores.cpu().numpy()
    
    for i, mask in enumerate(masks_np):
        # mask is a boolean array (True/False). 
        # AnnotatedImage handles the coloring automatically.
        # We just pass the mask and a label.
        score_val = scores_np[i]
        label = f"{text_prompt} ({score_val:.2f})"
        annotations.append((mask, label))
    
    # Return tuple format for AnnotatedImage
    return (image_pil, annotations)

css="""
#col-container {
    margin: 0 auto;
    max-width: 980px;
}
#main-title h1 {font-size: 2.1em !important;}
"""

with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# **SAM3 Image Segmentation**", 
            elem_id="main-title"
        )
        
        gr.Markdown("Segment objects in images using **SAM3** (Segment Anything Model 3) with text prompts.")

        with gr.Row():
            with gr.Column(scale=1):
                input_image = gr.Image(label="Input Image", type="pil", height=300)
                text_prompt = gr.Textbox(
                    label="Text Prompt",
                    placeholder="e.g., cat, ear, car wheel...",
                )
                
                run_button = gr.Button("Segment", variant="primary")

            with gr.Column(scale=1.5):
                output_image = gr.AnnotatedImage(label="Segmented Output", height=380)
                
                with gr.Row():
                    threshold = gr.Slider(label="Confidence Threshold", minimum=0.0, maximum=1.0, value=0.4, step=0.05)
        
        gr.Examples(
            examples=[
                ["examples/player.jpg", "player in white", 0.5],
                ["examples/goldencat.webp", "black cat", 0.4],
                ["examples/taxi.jpg", "blue taxi", 0.5],
            ],
            inputs=[input_image, text_prompt, threshold],
            outputs=[output_image],
            fn=segment_image,
            cache_examples="lazy",
            label="Examples"
        )

    run_button.click(
        fn=segment_image,
        inputs=[input_image, text_prompt, threshold],
        outputs=[output_image]
    )

if __name__ == "__main__":
    demo.launch(mcp_server=True, ssr_mode=False, show_error=True)