Harshil0777 commited on
Commit
dddcccb
·
1 Parent(s): 4c66172

Add SAM3 multi-class segmentation app

Browse files
Files changed (4) hide show
  1. README.md +16 -6
  2. app.py +346 -0
  3. packages.txt +3 -0
  4. requirements.txt +9 -0
README.md CHANGED
@@ -1,15 +1,25 @@
1
  ---
2
  title: SAM3 Multiclass Segmentation
3
- emoji: 🐨
4
  colorFrom: blue
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.19.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
- license: apache-2.0
12
- short_description: IGL
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: SAM3 Multiclass Segmentation
3
+ emoji: 🟦
4
  colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.19.0
 
8
  app_file: app.py
9
  pinned: false
10
+ license: other
 
11
  ---
12
 
13
+ # SAM 3 — Image / Video / Panorama / Multi-Class Segmentation
14
+
15
+ Upload an image or video, type up to 5 comma-separated classes, and get a mask overlay you
16
+ can preview and download. Panoramas (very wide images) are automatically tiled and stitched.
17
+
18
+ **Requirements for this Space to run:**
19
+ - GPU hardware (T4 or better) — set under Settings → Hardware
20
+ - An `HF_TOKEN` secret (Settings → Variables and secrets) with access to the gated
21
+ `facebook/sam3` checkpoint (request access once at
22
+ https://huggingface.co/facebook/sam3)
23
+
24
+ Built with [SAM 3](https://github.com/facebookresearch/sam3) by Meta. See the repo for
25
+ license terms before commercial use.
app.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM 3 — Image / Video / Panorama / Multi-Class Segmentation
3
+ Hugging Face Spaces app.
4
+
5
+ Requires a GPU-backed Space (T4 or better) and an HF_TOKEN secret with access
6
+ to the gated facebook/sam3 checkpoint (request access at
7
+ https://huggingface.co/facebook/sam3, then add HF_TOKEN in
8
+ Settings -> Variables and secrets on this Space).
9
+ """
10
+
11
+ import os
12
+ import glob
13
+ import hashlib
14
+ from datetime import datetime
15
+
16
+ import cv2
17
+ import numpy as np
18
+ import torch
19
+ import gradio as gr
20
+ from PIL import Image, ImageDraw
21
+ from huggingface_hub import login
22
+
23
+ # ----------------------------------------------------------------------
24
+ # Auth (Space secret) -- gated checkpoint download needs this at startup.
25
+ # ----------------------------------------------------------------------
26
+ HF_TOKEN = os.environ.get("HF_TOKEN")
27
+ if HF_TOKEN:
28
+ login(token=HF_TOKEN)
29
+ print("Logged in to Hugging Face using HF_TOKEN secret.")
30
+ else:
31
+ print("WARNING: HF_TOKEN secret not set. Gated checkpoint download will fail.")
32
+ print("Add it in this Space's Settings -> Variables and secrets.")
33
+
34
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
35
+ print(f"Using device={DEVICE}")
36
+
37
+ os.makedirs("/tmp/output", exist_ok=True)
38
+
39
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
40
+ VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
41
+ MAX_CLASSES = 5
42
+
43
+ # ----------------------------------------------------------------------
44
+ # Lazy model loaders
45
+ # ----------------------------------------------------------------------
46
+ _image_model_cache = {}
47
+ _video_predictor_cache = {}
48
+
49
+
50
+ def _find_bpe_path():
51
+ """Locate the bundled BPE tokenizer file regardless of how sam3 was installed."""
52
+ import sam3
53
+ pkg_dir = os.path.dirname(sam3.__file__) if getattr(sam3, "__file__", None) else None
54
+ search_roots = [pkg_dir] if pkg_dir else []
55
+ search_roots += ["/usr/local/lib", "/usr/lib", os.getcwd()]
56
+ for root in search_roots:
57
+ if not root:
58
+ continue
59
+ matches = glob.glob(os.path.join(root, "**", "bpe_simple_vocab_16e6.txt.gz"), recursive=True)
60
+ if matches:
61
+ return matches[0]
62
+ raise FileNotFoundError("Could not locate bpe_simple_vocab_16e6.txt.gz -- check sam3 install.")
63
+
64
+
65
+ BPE_PATH = _find_bpe_path()
66
+ print(f"Using bpe_path: {BPE_PATH}")
67
+
68
+
69
+ def get_image_processor():
70
+ if "processor" not in _image_model_cache:
71
+ from sam3.model_builder import build_sam3_image_model
72
+ from sam3.model.sam3_image_processor import Sam3Processor
73
+ print("Loading SAM 3 image model (checkpoint auto-downloads/caches on first call)...")
74
+ model = build_sam3_image_model(bpe_path=BPE_PATH, device=DEVICE)
75
+ model = model.to(DEVICE)
76
+ _image_model_cache["processor"] = Sam3Processor(model)
77
+ print("Image model ready.")
78
+ return _image_model_cache["processor"]
79
+
80
+
81
+ def get_video_predictor():
82
+ if "predictor" not in _video_predictor_cache:
83
+ from sam3.model_builder import build_sam3_video_predictor
84
+ print("Loading SAM 3 video predictor (checkpoint auto-downloads/caches on first call)...")
85
+ predictor = build_sam3_video_predictor(bpe_path=BPE_PATH, async_loading_frames=True)
86
+ _video_predictor_cache["predictor"] = predictor
87
+ print("Video predictor ready.")
88
+ return _video_predictor_cache["predictor"]
89
+
90
+
91
+ # ----------------------------------------------------------------------
92
+ # Helpers: masks, panorama tiling, multi-class, video propagation
93
+ # ----------------------------------------------------------------------
94
+ def _to_numpy_masks(masks):
95
+ return masks.detach().cpu().numpy() if hasattr(masks, "detach") else np.array(masks)
96
+
97
+
98
+ def is_panorama(image, ratio_threshold=2.5):
99
+ w, h = image.size
100
+ return (w / h) >= ratio_threshold
101
+
102
+
103
+ def segment_panorama(processor, image, prompt, tile_overlap=0.25, min_tile_w=768):
104
+ w, h = image.size
105
+ tile_w = max(min_tile_w, h)
106
+ tile_w = min(tile_w, w)
107
+ stride = max(int(tile_w * (1 - tile_overlap)), 1)
108
+
109
+ x_starts = list(range(0, max(w - tile_w, 0) + 1, stride))
110
+ if not x_starts:
111
+ x_starts = [0]
112
+ if x_starts[-1] + tile_w < w:
113
+ x_starts.append(w - tile_w)
114
+
115
+ combined_mask = np.zeros((h, w), dtype=bool)
116
+ all_boxes, all_scores = [], []
117
+
118
+ for x0 in x_starts:
119
+ x1 = min(x0 + tile_w, w)
120
+ tile = image.crop((x0, 0, x1, h))
121
+ with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
122
+ state = processor.set_image(tile)
123
+ out = processor.set_text_prompt(state=state, prompt=prompt)
124
+ masks_np = _to_numpy_masks(out["masks"])
125
+ boxes, scores = out["boxes"], out["scores"]
126
+
127
+ for i in range(masks_np.shape[0]):
128
+ m = masks_np[i]
129
+ if m.ndim == 3:
130
+ m = m[0]
131
+ m = m.astype(bool)
132
+ combined_mask[0:h, x0:x1] |= m[:, : (x1 - x0)]
133
+
134
+ for b in boxes:
135
+ bx = b.tolist() if hasattr(b, "tolist") else list(b)
136
+ bx[0] += x0
137
+ bx[2] += x0
138
+ all_boxes.append(bx)
139
+ for s in scores:
140
+ all_scores.append(float(s))
141
+
142
+ return combined_mask, all_boxes, all_scores
143
+
144
+
145
+ def parse_class_prompt(prompt, max_classes=MAX_CLASSES):
146
+ class_names = [p.strip() for p in prompt.split(",") if p.strip()]
147
+ class_names = list(dict.fromkeys(class_names))
148
+ if not class_names:
149
+ raise ValueError("Please enter at least one class.")
150
+ if len(class_names) > max_classes:
151
+ raise ValueError(f"Please enter at most {max_classes} classes (you entered {len(class_names)}).")
152
+ return class_names
153
+
154
+
155
+ def get_class_colors(class_names):
156
+ colors = {}
157
+ for name in class_names:
158
+ h = hashlib.md5(name.encode()).hexdigest()
159
+ r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
160
+ colors[name] = tuple(max(80, c) for c in (r, g, b))
161
+ return colors
162
+
163
+
164
+ def draw_legend(image, class_colors):
165
+ img = image.copy()
166
+ draw = ImageDraw.Draw(img)
167
+ pad, box, line_h = 8, 14, 22
168
+ w = max(120, max(len(c) for c in class_colors) * 8 + 40)
169
+ h = line_h * len(class_colors) + pad * 2
170
+ draw.rectangle([4, 4, 4 + w, 4 + h], fill=(0, 0, 0))
171
+ for i, (name, color) in enumerate(class_colors.items()):
172
+ y = 4 + pad + i * line_h
173
+ draw.rectangle([12, y, 12 + box, y + box], fill=color)
174
+ draw.text((12 + box + 8, y - 2), name, fill=(255, 255, 255))
175
+ return img
176
+
177
+
178
+ def segment_multiclass_image(processor, image, class_names, panorama=False):
179
+ class_colors = get_class_colors(class_names)
180
+ img_np = np.array(image.convert("RGB")).astype(np.uint8)
181
+ overlay = img_np.copy()
182
+ alpha = 0.55
183
+ per_class_counts = {}
184
+
185
+ if not panorama:
186
+ with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
187
+ state = processor.set_image(image)
188
+
189
+ for name in class_names:
190
+ color = np.array(class_colors[name], dtype=np.float32)
191
+
192
+ if panorama:
193
+ combined_mask, boxes, scores = segment_panorama(processor, image, name)
194
+ per_class_counts[name] = len(boxes)
195
+ overlay[combined_mask] = (
196
+ overlay[combined_mask].astype(np.float32) * (1 - alpha) + color * alpha
197
+ ).astype(np.uint8)
198
+ else:
199
+ with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
200
+ out = processor.set_text_prompt(state=state, prompt=name)
201
+ masks_np = _to_numpy_masks(out["masks"])
202
+ per_class_counts[name] = masks_np.shape[0]
203
+ for i in range(masks_np.shape[0]):
204
+ m = masks_np[i]
205
+ if m.ndim == 3:
206
+ m = m[0]
207
+ m = m.astype(bool)
208
+ overlay[m] = (overlay[m].astype(np.float32) * (1 - alpha) + color * alpha).astype(np.uint8)
209
+
210
+ result = Image.fromarray(overlay)
211
+ result = draw_legend(result, class_colors)
212
+ return result, per_class_counts
213
+
214
+
215
+ def propagate_in_video(video_predictor, session_id):
216
+ outputs_per_frame = {}
217
+ for frame_output in video_predictor.handle_stream_request(
218
+ request=dict(type="propagate_in_video", session_id=session_id, propagation_direction="both")
219
+ ):
220
+ idx = frame_output["frame_index"]
221
+ outputs_per_frame[idx] = frame_output["outputs"]
222
+ return outputs_per_frame
223
+
224
+
225
+ # ----------------------------------------------------------------------
226
+ # Main inference entrypoint
227
+ # ----------------------------------------------------------------------
228
+ def run_sam3(file_path, prompt, progress=gr.Progress()):
229
+ if file_path is None:
230
+ raise gr.Error("Please upload an image or video first.")
231
+ if not prompt or not prompt.strip():
232
+ raise gr.Error("Please type at least one class (e.g. 'person, dog, car').")
233
+
234
+ try:
235
+ class_names = parse_class_prompt(prompt, max_classes=MAX_CLASSES)
236
+ except ValueError as e:
237
+ raise gr.Error(str(e))
238
+
239
+ ext = os.path.splitext(file_path)[1].lower()
240
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
241
+
242
+ if ext in IMAGE_EXTS:
243
+ progress(0.1, desc="Loading image model...")
244
+ processor = get_image_processor()
245
+ image = Image.open(file_path).convert("RGB")
246
+ panorama = is_panorama(image)
247
+
248
+ progress(0.3, desc=f"Segmenting {len(class_names)} class(es)" + (" (panorama tiling)..." if panorama else "..."))
249
+ result_image, per_class_counts = segment_multiclass_image(processor, image, class_names, panorama=panorama)
250
+ status = "Found: " + ", ".join(f"{k}={v}" for k, v in per_class_counts.items())
251
+
252
+ progress(0.9, desc="Saving output...")
253
+ out_path = f"/tmp/output/sam3_overlay_{timestamp}.png"
254
+ result_image.save(out_path)
255
+ progress(1.0, desc="Done!")
256
+
257
+ return (
258
+ gr.update(value=result_image, visible=True),
259
+ gr.update(visible=False),
260
+ gr.update(value=out_path, visible=True),
261
+ status,
262
+ )
263
+
264
+ elif ext in VIDEO_EXTS:
265
+ progress(0.1, desc="Loading video predictor...")
266
+ from sam3.visualization_utils import save_masklet_video
267
+ video_predictor = get_video_predictor()
268
+ video_prompt = class_names[0]
269
+ note = ""
270
+ if len(class_names) > 1:
271
+ note = f" (only first class '{video_prompt}' is tracked for video)"
272
+
273
+ progress(0.2, desc="Reading video frames...")
274
+ cap = cv2.VideoCapture(file_path)
275
+ video_fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
276
+ video_frames = []
277
+ while True:
278
+ ret, frame = cap.read()
279
+ if not ret:
280
+ break
281
+ video_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
282
+ cap.release()
283
+
284
+ progress(0.4, desc="Tracking object through video...")
285
+ with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
286
+ response = video_predictor.handle_request(
287
+ request=dict(type="start_session", resource_path=file_path)
288
+ )
289
+ session_id = response["session_id"]
290
+ video_predictor.handle_request(
291
+ request=dict(type="add_prompt", session_id=session_id, frame_index=0, text=video_prompt)
292
+ )
293
+ outputs_per_frame = propagate_in_video(video_predictor, session_id)
294
+
295
+ progress(0.85, desc="Rendering overlay video...")
296
+ out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"
297
+ save_masklet_video(video_frames, outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)
298
+
299
+ video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))
300
+ progress(1.0, desc="Done!")
301
+
302
+ status = f"Tracked {len(outputs_per_frame)} frames for '{video_prompt}'.{note}"
303
+ return (
304
+ gr.update(visible=False),
305
+ gr.update(value=out_path, visible=True),
306
+ gr.update(value=out_path, visible=True),
307
+ status,
308
+ )
309
+
310
+ else:
311
+ raise gr.Error(f"Unsupported file type: {ext}")
312
+
313
+
314
+ # ----------------------------------------------------------------------
315
+ # UI
316
+ # ----------------------------------------------------------------------
317
+ with gr.Blocks(title="SAM 3 Segmentation") as demo:
318
+ gr.Markdown(
319
+ "## 🟦 SAM 3 — Image / Video / Panorama / Multi-Class Segmentation\n"
320
+ "Upload an image or video, type up to 5 comma-separated classes, hit Run. "
321
+ "Panoramas (very wide images) are auto-tiled. Multiple classes are merged into one overlay with a legend."
322
+ )
323
+
324
+ with gr.Row():
325
+ with gr.Column(scale=1):
326
+ file_input = gr.File(label="Upload image or video", file_types=["image", "video"], type="filepath")
327
+ prompt_input = gr.Textbox(
328
+ label="Text prompt(s) — comma-separated, up to 5 classes",
329
+ placeholder="e.g. person, dog, red car",
330
+ )
331
+ run_btn = gr.Button("▶ Run Segmentation", variant="primary")
332
+ status_box = gr.Textbox(label="Status", interactive=False)
333
+
334
+ with gr.Column(scale=1):
335
+ image_output = gr.Image(label="Result (image)", visible=False)
336
+ video_output = gr.Video(label="Result (video)", visible=False)
337
+ download_output = gr.File(label="Download result", visible=False)
338
+
339
+ run_btn.click(
340
+ fn=run_sam3,
341
+ inputs=[file_input, prompt_input],
342
+ outputs=[image_output, video_output, download_output, status_box],
343
+ )
344
+
345
+ if __name__ == "__main__":
346
+ demo.launch()
packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ libgl1
2
+ libglib2.0-0
3
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ git+https://github.com/facebookresearch/sam3.git
4
+ gradio
5
+ opencv-python-headless
6
+ huggingface_hub
7
+ pillow
8
+ tqdm
9
+ timm