Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,30 +1,32 @@
|
|
| 1 |
"""
|
| 2 |
-
SAM 3 — Image / Video / Panorama / Multi-Class Segmentation
|
| 3 |
-
Hugging Face Spaces app.
|
| 4 |
-
|
| 5 |
-
Requires
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 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 |
import spaces
|
|
|
|
|
|
|
| 23 |
|
| 24 |
# ----------------------------------------------------------------------
|
| 25 |
# Auth (Space secret) -- gated checkpoint download needs this at startup.
|
| 26 |
# ----------------------------------------------------------------------
|
| 27 |
-
HF_TOKEN = os.environ.get("
|
| 28 |
if HF_TOKEN:
|
| 29 |
login(token=HF_TOKEN)
|
| 30 |
print("Logged in to Hugging Face using HF_TOKEN secret.")
|
|
@@ -32,20 +34,30 @@ else:
|
|
| 32 |
print("WARNING: HF_TOKEN secret not set. Gated checkpoint download will fail.")
|
| 33 |
print("Add it in this Space's Settings -> Variables and secrets.")
|
| 34 |
|
| 35 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 36 |
-
print(f"Using device={DEVICE}")
|
| 37 |
-
|
| 38 |
os.makedirs("/tmp/output", exist_ok=True)
|
| 39 |
|
| 40 |
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
|
| 41 |
VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
|
| 42 |
MAX_CLASSES = 5
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# ----------------------------------------------------------------------
|
| 45 |
-
# Lazy model loaders
|
| 46 |
# ----------------------------------------------------------------------
|
| 47 |
-
|
| 48 |
-
|
| 49 |
|
| 50 |
|
| 51 |
def _find_bpe_path():
|
|
@@ -67,26 +79,101 @@ BPE_PATH = _find_bpe_path()
|
|
| 67 |
print(f"Using bpe_path: {BPE_PATH}")
|
| 68 |
|
| 69 |
|
| 70 |
-
def
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
from sam3.model_builder import build_sam3_image_model
|
| 73 |
from sam3.model.sam3_image_processor import Sam3Processor
|
| 74 |
-
print("Loading SAM 3 image model (checkpoint auto-downloads/caches on first call)...")
|
| 75 |
-
model = build_sam3_image_model(bpe_path=BPE_PATH, device=DEVICE)
|
| 76 |
-
model = model.to(DEVICE)
|
| 77 |
-
_image_model_cache["processor"] = Sam3Processor(model)
|
| 78 |
-
print("Image model ready.")
|
| 79 |
-
return _image_model_cache["processor"]
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
def get_video_predictor():
|
| 83 |
-
if "predictor" not in _video_predictor_cache:
|
| 84 |
from sam3.model_builder import build_sam3_video_predictor
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
# ----------------------------------------------------------------------
|
|
@@ -119,7 +206,7 @@ def segment_panorama(processor, image, prompt, tile_overlap=0.25, min_tile_w=768
|
|
| 119 |
for x0 in x_starts:
|
| 120 |
x1 = min(x0 + tile_w, w)
|
| 121 |
tile = image.crop((x0, 0, x1, h))
|
| 122 |
-
with torch.inference_mode(), torch.autocast(device_type=
|
| 123 |
state = processor.set_image(tile)
|
| 124 |
out = processor.set_text_prompt(state=state, prompt=prompt)
|
| 125 |
masks_np = _to_numpy_masks(out["masks"])
|
|
@@ -184,7 +271,7 @@ def segment_multiclass_image(processor, image, class_names, panorama=False):
|
|
| 184 |
per_class_counts = {}
|
| 185 |
|
| 186 |
if not panorama:
|
| 187 |
-
with torch.inference_mode(), torch.autocast(device_type=
|
| 188 |
state = processor.set_image(image)
|
| 189 |
|
| 190 |
for name in class_names:
|
|
@@ -197,7 +284,7 @@ def segment_multiclass_image(processor, image, class_names, panorama=False):
|
|
| 197 |
overlay[combined_mask].astype(np.float32) * (1 - alpha) + color * alpha
|
| 198 |
).astype(np.uint8)
|
| 199 |
else:
|
| 200 |
-
with torch.inference_mode(), torch.autocast(device_type=
|
| 201 |
out = processor.set_text_prompt(state=state, prompt=name)
|
| 202 |
masks_np = _to_numpy_masks(out["masks"])
|
| 203 |
per_class_counts[name] = masks_np.shape[0]
|
|
@@ -222,120 +309,15 @@ def propagate_in_video(video_predictor, session_id):
|
|
| 222 |
outputs_per_frame[idx] = frame_output["outputs"]
|
| 223 |
return outputs_per_frame
|
| 224 |
|
| 225 |
-
# ----------------------------------------------------------------------
|
| 226 |
-
# Main inference entrypoint
|
| 227 |
-
# ----------------------------------------------------------------------
|
| 228 |
-
# ----------------------------------------------------------------------
|
| 229 |
-
# 1. Image Inference (Default Duration - Works for ALL users)
|
| 230 |
-
# ----------------------------------------------------------------------
|
| 231 |
-
@spaces.GPU
|
| 232 |
-
def run_sam3_image(file_path, class_names, timestamp, progress):
|
| 233 |
-
progress(0.1, desc="Loading image model...")
|
| 234 |
-
processor = get_image_processor()
|
| 235 |
-
image = Image.open(file_path).convert("RGB")
|
| 236 |
-
panorama = is_panorama(image)
|
| 237 |
-
|
| 238 |
-
progress(0.3, desc=f"Segmenting {len(class_names)} class(es)" + (" (panorama tiling)..." if panorama else "..."))
|
| 239 |
-
result_image, per_class_counts = segment_multiclass_image(processor, image, class_names, panorama=panorama)
|
| 240 |
-
status = "Found: " + ", ".join(f"{k}={v}" for k, v in per_class_counts.items())
|
| 241 |
-
|
| 242 |
-
progress(0.9, desc="Saving output...")
|
| 243 |
-
out_path = f"/tmp/output/sam3_overlay_{timestamp}.png"
|
| 244 |
-
result_image.save(out_path)
|
| 245 |
-
progress(1.0, desc="Done!")
|
| 246 |
-
|
| 247 |
-
return (
|
| 248 |
-
gr.update(value=result_image, visible=True),
|
| 249 |
-
gr.update(visible=False),
|
| 250 |
-
gr.update(value=out_path, visible=True),
|
| 251 |
-
status,
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
# ----------------------------------------------------------------------
|
| 255 |
-
# 2. Video Inference (High Duration - Works for Space Owners/PRO)
|
| 256 |
-
# ----------------------------------------------------------------------
|
| 257 |
-
@spaces.GPU(duration=450)
|
| 258 |
-
def run_sam3_video(file_path, class_names, timestamp, progress):
|
| 259 |
-
progress(0.1, desc="Loading video predictor...")
|
| 260 |
-
from sam3.visualization_utils import save_masklet_video
|
| 261 |
-
video_predictor = get_video_predictor()
|
| 262 |
-
|
| 263 |
-
tracked_classes_str = ", ".join(class_names)
|
| 264 |
-
|
| 265 |
-
progress(0.2, desc="Reading video frames...")
|
| 266 |
-
cap = cv2.VideoCapture(file_path)
|
| 267 |
-
video_fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
|
| 268 |
-
video_frames = []
|
| 269 |
-
while True:
|
| 270 |
-
ret, frame = cap.read()
|
| 271 |
-
if not ret:
|
| 272 |
-
break
|
| 273 |
-
video_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 274 |
-
cap.release()
|
| 275 |
-
|
| 276 |
-
progress(0.3, desc="Tracking objects (multi-pass)...")
|
| 277 |
-
master_outputs_per_frame = {i: {} for i in range(len(video_frames))}
|
| 278 |
-
|
| 279 |
-
with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
|
| 280 |
-
for obj_idx, class_name in enumerate(class_names):
|
| 281 |
-
response = video_predictor.handle_request(
|
| 282 |
-
request=dict(type="start_session", resource_path=file_path)
|
| 283 |
-
)
|
| 284 |
-
session_id = response["session_id"]
|
| 285 |
-
|
| 286 |
-
video_predictor.handle_request(
|
| 287 |
-
request=dict(
|
| 288 |
-
type="add_prompt",
|
| 289 |
-
session_id=session_id,
|
| 290 |
-
frame_index=0,
|
| 291 |
-
obj_id=obj_idx,
|
| 292 |
-
text=class_name
|
| 293 |
-
)
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
-
for frame_output in video_predictor.handle_stream_request(
|
| 297 |
-
request=dict(type="propagate_in_video", session_id=session_id, propagation_direction="both")
|
| 298 |
-
):
|
| 299 |
-
idx = frame_output["frame_index"]
|
| 300 |
-
out_data = frame_output["outputs"]
|
| 301 |
-
|
| 302 |
-
if isinstance(out_data, dict):
|
| 303 |
-
for k, v in out_data.items():
|
| 304 |
-
if k not in master_outputs_per_frame[idx]:
|
| 305 |
-
master_outputs_per_frame[idx][k] = []
|
| 306 |
-
if isinstance(v, list):
|
| 307 |
-
master_outputs_per_frame[idx][k].extend(v)
|
| 308 |
-
else:
|
| 309 |
-
master_outputs_per_frame[idx][k].append(v)
|
| 310 |
-
|
| 311 |
-
video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))
|
| 312 |
-
|
| 313 |
-
progress(0.85, desc="Rendering combined overlay video...")
|
| 314 |
-
out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"
|
| 315 |
-
|
| 316 |
-
for idx in master_outputs_per_frame:
|
| 317 |
-
for k, v_list in master_outputs_per_frame[idx].items():
|
| 318 |
-
if isinstance(v_list, list) and len(v_list) > 0:
|
| 319 |
-
if torch.is_tensor(v_list[0]):
|
| 320 |
-
master_outputs_per_frame[idx][k] = torch.cat(v_list, dim=0)
|
| 321 |
-
elif isinstance(v_list[0], np.ndarray):
|
| 322 |
-
master_outputs_per_frame[idx][k] = np.concatenate(v_list, axis=0)
|
| 323 |
-
|
| 324 |
-
save_masklet_video(video_frames, master_outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)
|
| 325 |
-
progress(1.0, desc="Done!")
|
| 326 |
-
|
| 327 |
-
status = f"Tracked {len(video_frames)} frames for: {tracked_classes_str}"
|
| 328 |
-
return (
|
| 329 |
-
gr.update(visible=False),
|
| 330 |
-
gr.update(value=out_path, visible=True),
|
| 331 |
-
gr.update(value=out_path, visible=True),
|
| 332 |
-
status,
|
| 333 |
-
)
|
| 334 |
|
| 335 |
# ----------------------------------------------------------------------
|
| 336 |
-
#
|
| 337 |
# ----------------------------------------------------------------------
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
if file_path is None:
|
| 340 |
raise gr.Error("Please upload an image or video first.")
|
| 341 |
if not prompt or not prompt.strip():
|
|
@@ -349,11 +331,77 @@ def run_sam3(file_path, prompt, progress=gr.Progress()):
|
|
| 349 |
ext = os.path.splitext(file_path)[1].lower()
|
| 350 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 351 |
|
| 352 |
-
# Route to the appropriate function based on file type
|
| 353 |
if ext in IMAGE_EXTS:
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
elif ext in VIDEO_EXTS:
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
else:
|
| 358 |
raise gr.Error(f"Unsupported file type: {ext}")
|
| 359 |
|
|
@@ -363,16 +411,22 @@ def run_sam3(file_path, prompt, progress=gr.Progress()):
|
|
| 363 |
# ----------------------------------------------------------------------
|
| 364 |
with gr.Blocks(title="SAM 3 Segmentation") as demo:
|
| 365 |
gr.Markdown(
|
| 366 |
-
"## 🟦 SAM 3 — Image / Video / Panorama / Multi-Class Segmentation\n"
|
| 367 |
-
"Upload an image or video, type up to 5 comma-separated classes, hit Run. "
|
| 368 |
"Panoramas (very wide images) are auto-tiled. Multiple classes are merged into one overlay with a legend."
|
| 369 |
)
|
| 370 |
|
| 371 |
with gr.Row():
|
| 372 |
with gr.Column(scale=1):
|
| 373 |
file_input = gr.File(label="Upload image or video", file_types=["image", "video"], type="filepath")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
prompt_input = gr.Textbox(
|
| 375 |
-
label="Text prompt(s) — comma-separated, up to 5 classes
|
| 376 |
placeholder="e.g. person, dog, red car",
|
| 377 |
)
|
| 378 |
run_btn = gr.Button("▶ Run Segmentation", variant="primary")
|
|
@@ -385,7 +439,7 @@ with gr.Blocks(title="SAM 3 Segmentation") as demo:
|
|
| 385 |
|
| 386 |
run_btn.click(
|
| 387 |
fn=run_sam3,
|
| 388 |
-
inputs=[file_input, prompt_input],
|
| 389 |
outputs=[image_output, video_output, download_output, status_box],
|
| 390 |
)
|
| 391 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
SAM 3 / SAM 3.1 — Image / Video / Panorama / Multi-Class Segmentation
|
| 3 |
+
Hugging Face Spaces app (ZeroGPU).
|
| 4 |
+
|
| 5 |
+
Requires:
|
| 6 |
+
- ZeroGPU hardware selected under Settings -> Hardware
|
| 7 |
+
- An HF_TOKEN secret (Settings -> Variables and secrets) with access to the gated
|
| 8 |
+
facebook/sam3 and facebook/sam3.1 checkpoints (request access at
|
| 9 |
+
https://huggingface.co/facebook/sam3 and https://huggingface.co/facebook/sam3.1)
|
| 10 |
"""
|
| 11 |
|
| 12 |
import os
|
| 13 |
import glob
|
| 14 |
import hashlib
|
| 15 |
+
import subprocess
|
| 16 |
from datetime import datetime
|
| 17 |
|
| 18 |
import cv2
|
| 19 |
import numpy as np
|
| 20 |
import torch
|
| 21 |
import gradio as gr
|
|
|
|
|
|
|
| 22 |
import spaces
|
| 23 |
+
from PIL import Image, ImageDraw
|
| 24 |
+
from huggingface_hub import login, list_repo_files, hf_hub_download
|
| 25 |
|
| 26 |
# ----------------------------------------------------------------------
|
| 27 |
# Auth (Space secret) -- gated checkpoint download needs this at startup.
|
| 28 |
# ----------------------------------------------------------------------
|
| 29 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 30 |
if HF_TOKEN:
|
| 31 |
login(token=HF_TOKEN)
|
| 32 |
print("Logged in to Hugging Face using HF_TOKEN secret.")
|
|
|
|
| 34 |
print("WARNING: HF_TOKEN secret not set. Gated checkpoint download will fail.")
|
| 35 |
print("Add it in this Space's Settings -> Variables and secrets.")
|
| 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 |
+
VERSION_REPOS = {
|
| 44 |
+
"SAM 3.1": "facebook/sam3.1",
|
| 45 |
+
"SAM 3": "facebook/sam3",
|
| 46 |
+
}
|
| 47 |
+
DEFAULT_VERSION = "SAM 3.1"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_device():
|
| 51 |
+
"""ZeroGPU only attaches a GPU inside a @spaces.GPU-decorated call, so this must
|
| 52 |
+
be evaluated at call time, never at module import time."""
|
| 53 |
+
return "cuda" if torch.cuda.is_available() else "cpu"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
# ----------------------------------------------------------------------
|
| 57 |
+
# Lazy, version-aware model loaders
|
| 58 |
# ----------------------------------------------------------------------
|
| 59 |
+
_model_cache = {} # version -> {"processor": ..., "predictor": ...}
|
| 60 |
+
_current_version = {"value": None} # which version is currently loaded on GPU
|
| 61 |
|
| 62 |
|
| 63 |
def _find_bpe_path():
|
|
|
|
| 79 |
print(f"Using bpe_path: {BPE_PATH}")
|
| 80 |
|
| 81 |
|
| 82 |
+
def _resolve_checkpoint_path(repo_id):
|
| 83 |
+
"""Lists the repo's actual files and picks the right weight file automatically,
|
| 84 |
+
instead of assuming a filename that may differ between repos/versions."""
|
| 85 |
+
files = list_repo_files(repo_id)
|
| 86 |
+
weight_files = [f for f in files if f.endswith(".pt") or f.endswith(".safetensors")]
|
| 87 |
+
assert weight_files, f"No .pt/.safetensors checkpoint file found in {repo_id}"
|
| 88 |
+
pt_files = [f for f in weight_files if f.endswith(".pt")]
|
| 89 |
+
chosen = pt_files[0] if pt_files else weight_files[0]
|
| 90 |
+
print(f"Resolved checkpoint file in {repo_id}: {chosen}")
|
| 91 |
+
return hf_hub_download(repo_id=repo_id, filename=chosen)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _unload_current_model():
|
| 95 |
+
"""Frees GPU memory from whichever version is currently loaded before switching."""
|
| 96 |
+
if _current_version["value"] is not None:
|
| 97 |
+
old = _current_version["value"]
|
| 98 |
+
_model_cache.pop(old, None)
|
| 99 |
+
if torch.cuda.is_available():
|
| 100 |
+
torch.cuda.empty_cache()
|
| 101 |
+
print(f"Unloaded {old} to free GPU memory.")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_image_processor(version=DEFAULT_VERSION):
|
| 105 |
+
if version not in VERSION_REPOS:
|
| 106 |
+
raise ValueError(f"Unknown version '{version}', expected one of {list(VERSION_REPOS)}")
|
| 107 |
+
|
| 108 |
+
if version not in _model_cache or "processor" not in _model_cache.get(version, {}):
|
| 109 |
+
if _current_version["value"] is not None and _current_version["value"] != version:
|
| 110 |
+
_unload_current_model()
|
| 111 |
+
|
| 112 |
from sam3.model_builder import build_sam3_image_model
|
| 113 |
from sam3.model.sam3_image_processor import Sam3Processor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
repo_id = VERSION_REPOS[version]
|
| 116 |
+
print(f"Loading {version} image model from {repo_id} (downloads/caches on first call)...")
|
| 117 |
+
ckpt_path = _resolve_checkpoint_path(repo_id)
|
| 118 |
+
model = build_sam3_image_model(bpe_path=BPE_PATH, checkpoint_path=ckpt_path, device=get_device())
|
| 119 |
+
model = model.to(get_device())
|
| 120 |
+
|
| 121 |
+
_model_cache.setdefault(version, {})["processor"] = Sam3Processor(model)
|
| 122 |
+
_current_version["value"] = version
|
| 123 |
+
print(f"{version} image model ready.")
|
| 124 |
+
|
| 125 |
+
return _model_cache[version]["processor"]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_video_predictor(version=DEFAULT_VERSION):
|
| 129 |
+
if version not in VERSION_REPOS:
|
| 130 |
+
raise ValueError(f"Unknown version '{version}', expected one of {list(VERSION_REPOS)}")
|
| 131 |
+
|
| 132 |
+
if version not in _model_cache or "predictor" not in _model_cache.get(version, {}):
|
| 133 |
+
if _current_version["value"] is not None and _current_version["value"] != version:
|
| 134 |
+
_unload_current_model()
|
| 135 |
|
|
|
|
|
|
|
| 136 |
from sam3.model_builder import build_sam3_video_predictor
|
| 137 |
+
|
| 138 |
+
repo_id = VERSION_REPOS[version]
|
| 139 |
+
print(f"Loading {version} video predictor from {repo_id} (downloads/caches on first call)...")
|
| 140 |
+
ckpt_path = _resolve_checkpoint_path(repo_id)
|
| 141 |
+
predictor = build_sam3_video_predictor(bpe_path=BPE_PATH, checkpoint_path=ckpt_path, async_loading_frames=True)
|
| 142 |
+
|
| 143 |
+
_model_cache.setdefault(version, {})["predictor"] = predictor
|
| 144 |
+
_current_version["value"] = version
|
| 145 |
+
print(f"{version} video predictor ready.")
|
| 146 |
+
|
| 147 |
+
return _model_cache[version]["predictor"]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# ----------------------------------------------------------------------
|
| 151 |
+
# Video repair (fixes "moov atom not found" / truncated uploads)
|
| 152 |
+
# ----------------------------------------------------------------------
|
| 153 |
+
def ensure_readable_video(file_path):
|
| 154 |
+
"""cv2/SAM3 can fail on MP4s with a missing/misplaced moov atom (common with large
|
| 155 |
+
or truncated uploads). Remux through ffmpeg first -- this fixes most container-level
|
| 156 |
+
issues without re-encoding. Raises a clear gr.Error if the file is genuinely corrupted."""
|
| 157 |
+
fixed_path = file_path + "_fixed.mp4"
|
| 158 |
+
try:
|
| 159 |
+
result = subprocess.run(
|
| 160 |
+
["ffmpeg", "-y", "-v", "error", "-i", file_path,
|
| 161 |
+
"-c", "copy", "-movflags", "+faststart", fixed_path],
|
| 162 |
+
capture_output=True, text=True, timeout=180,
|
| 163 |
+
)
|
| 164 |
+
except FileNotFoundError:
|
| 165 |
+
raise gr.Error("ffmpeg is not installed on this Space -- check packages.txt includes 'ffmpeg'.")
|
| 166 |
+
except subprocess.TimeoutExpired:
|
| 167 |
+
raise gr.Error("Video repair step timed out -- the file may be too large or genuinely corrupted.")
|
| 168 |
+
|
| 169 |
+
if result.returncode != 0 or not os.path.exists(fixed_path) or os.path.getsize(fixed_path) == 0:
|
| 170 |
+
stderr_tail = result.stderr[-500:] if result and result.stderr else "unknown error"
|
| 171 |
+
raise gr.Error(
|
| 172 |
+
"This video file appears to be corrupted or incompletely uploaded "
|
| 173 |
+
"(missing video index / moov atom). Try re-exporting or re-uploading it. "
|
| 174 |
+
f"ffmpeg said: {stderr_tail}"
|
| 175 |
+
)
|
| 176 |
+
return fixed_path
|
| 177 |
|
| 178 |
|
| 179 |
# ----------------------------------------------------------------------
|
|
|
|
| 206 |
for x0 in x_starts:
|
| 207 |
x1 = min(x0 + tile_w, w)
|
| 208 |
tile = image.crop((x0, 0, x1, h))
|
| 209 |
+
with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):
|
| 210 |
state = processor.set_image(tile)
|
| 211 |
out = processor.set_text_prompt(state=state, prompt=prompt)
|
| 212 |
masks_np = _to_numpy_masks(out["masks"])
|
|
|
|
| 271 |
per_class_counts = {}
|
| 272 |
|
| 273 |
if not panorama:
|
| 274 |
+
with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):
|
| 275 |
state = processor.set_image(image)
|
| 276 |
|
| 277 |
for name in class_names:
|
|
|
|
| 284 |
overlay[combined_mask].astype(np.float32) * (1 - alpha) + color * alpha
|
| 285 |
).astype(np.uint8)
|
| 286 |
else:
|
| 287 |
+
with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):
|
| 288 |
out = processor.set_text_prompt(state=state, prompt=name)
|
| 289 |
masks_np = _to_numpy_masks(out["masks"])
|
| 290 |
per_class_counts[name] = masks_np.shape[0]
|
|
|
|
| 309 |
outputs_per_frame[idx] = frame_output["outputs"]
|
| 310 |
return outputs_per_frame
|
| 311 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
# ----------------------------------------------------------------------
|
| 314 |
+
# Main inference entrypoint
|
| 315 |
# ----------------------------------------------------------------------
|
| 316 |
+
# ZeroGPU only grants a GPU for the duration of a decorated call. duration is the max
|
| 317 |
+
# seconds this call is allowed to hold the GPU -- raise it if longer videos time out
|
| 318 |
+
# (check your account's max allowed duration in the ZeroGPU docs if this errors).
|
| 319 |
+
@spaces.GPU(duration=120)
|
| 320 |
+
def run_sam3(file_path, prompt, model_version, progress=gr.Progress()):
|
| 321 |
if file_path is None:
|
| 322 |
raise gr.Error("Please upload an image or video first.")
|
| 323 |
if not prompt or not prompt.strip():
|
|
|
|
| 331 |
ext = os.path.splitext(file_path)[1].lower()
|
| 332 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 333 |
|
|
|
|
| 334 |
if ext in IMAGE_EXTS:
|
| 335 |
+
progress(0.1, desc=f"Loading {model_version} image model...")
|
| 336 |
+
processor = get_image_processor(model_version)
|
| 337 |
+
image = Image.open(file_path).convert("RGB")
|
| 338 |
+
panorama = is_panorama(image)
|
| 339 |
+
|
| 340 |
+
progress(0.3, desc=f"Segmenting {len(class_names)} class(es)" + (" (panorama tiling)..." if panorama else "..."))
|
| 341 |
+
result_image, per_class_counts = segment_multiclass_image(processor, image, class_names, panorama=panorama)
|
| 342 |
+
status = f"[{model_version}] Found: " + ", ".join(f"{k}={v}" for k, v in per_class_counts.items())
|
| 343 |
+
|
| 344 |
+
progress(0.9, desc="Saving output...")
|
| 345 |
+
out_path = f"/tmp/output/sam3_overlay_{timestamp}.png"
|
| 346 |
+
result_image.save(out_path)
|
| 347 |
+
progress(1.0, desc="Done!")
|
| 348 |
+
|
| 349 |
+
return (
|
| 350 |
+
gr.update(value=result_image, visible=True),
|
| 351 |
+
gr.update(visible=False),
|
| 352 |
+
gr.update(value=out_path, visible=True),
|
| 353 |
+
status,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
elif ext in VIDEO_EXTS:
|
| 357 |
+
progress(0.05, desc="Checking video file...")
|
| 358 |
+
file_path = ensure_readable_video(file_path)
|
| 359 |
+
|
| 360 |
+
progress(0.15, desc=f"Loading {model_version} video predictor...")
|
| 361 |
+
from sam3.visualization_utils import save_masklet_video
|
| 362 |
+
video_predictor = get_video_predictor(model_version)
|
| 363 |
+
video_prompt = class_names[0]
|
| 364 |
+
note = ""
|
| 365 |
+
if len(class_names) > 1:
|
| 366 |
+
note = f" (only first class '{video_prompt}' is tracked for video)"
|
| 367 |
+
|
| 368 |
+
progress(0.25, desc="Reading video frames...")
|
| 369 |
+
cap = cv2.VideoCapture(file_path)
|
| 370 |
+
video_fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
|
| 371 |
+
video_frames = []
|
| 372 |
+
while True:
|
| 373 |
+
ret, frame = cap.read()
|
| 374 |
+
if not ret:
|
| 375 |
+
break
|
| 376 |
+
video_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 377 |
+
cap.release()
|
| 378 |
+
|
| 379 |
+
progress(0.4, desc="Tracking object through video...")
|
| 380 |
+
with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):
|
| 381 |
+
response = video_predictor.handle_request(
|
| 382 |
+
request=dict(type="start_session", resource_path=file_path)
|
| 383 |
+
)
|
| 384 |
+
session_id = response["session_id"]
|
| 385 |
+
video_predictor.handle_request(
|
| 386 |
+
request=dict(type="add_prompt", session_id=session_id, frame_index=0, text=video_prompt)
|
| 387 |
+
)
|
| 388 |
+
outputs_per_frame = propagate_in_video(video_predictor, session_id)
|
| 389 |
+
|
| 390 |
+
progress(0.85, desc="Rendering overlay video...")
|
| 391 |
+
out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"
|
| 392 |
+
save_masklet_video(video_frames, outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)
|
| 393 |
+
|
| 394 |
+
video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))
|
| 395 |
+
progress(1.0, desc="Done!")
|
| 396 |
+
|
| 397 |
+
status = f"[{model_version}] Tracked {len(outputs_per_frame)} frames for '{video_prompt}'.{note}"
|
| 398 |
+
return (
|
| 399 |
+
gr.update(visible=False),
|
| 400 |
+
gr.update(value=out_path, visible=True),
|
| 401 |
+
gr.update(value=out_path, visible=True),
|
| 402 |
+
status,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
else:
|
| 406 |
raise gr.Error(f"Unsupported file type: {ext}")
|
| 407 |
|
|
|
|
| 411 |
# ----------------------------------------------------------------------
|
| 412 |
with gr.Blocks(title="SAM 3 Segmentation") as demo:
|
| 413 |
gr.Markdown(
|
| 414 |
+
"## 🟦 SAM 3 / SAM 3.1 — Image / Video / Panorama / Multi-Class Segmentation\n"
|
| 415 |
+
"Upload an image or video, pick a model version, type up to 5 comma-separated classes, hit Run. "
|
| 416 |
"Panoramas (very wide images) are auto-tiled. Multiple classes are merged into one overlay with a legend."
|
| 417 |
)
|
| 418 |
|
| 419 |
with gr.Row():
|
| 420 |
with gr.Column(scale=1):
|
| 421 |
file_input = gr.File(label="Upload image or video", file_types=["image", "video"], type="filepath")
|
| 422 |
+
model_toggle = gr.Radio(
|
| 423 |
+
choices=["SAM 3.1", "SAM 3"],
|
| 424 |
+
value=DEFAULT_VERSION,
|
| 425 |
+
label="Model version",
|
| 426 |
+
info="SAM 3.1 = faster multi-object video tracking (Object Multiplex). Toggle to SAM 3 for the original.",
|
| 427 |
+
)
|
| 428 |
prompt_input = gr.Textbox(
|
| 429 |
+
label="Text prompt(s) — comma-separated, up to 5 classes",
|
| 430 |
placeholder="e.g. person, dog, red car",
|
| 431 |
)
|
| 432 |
run_btn = gr.Button("▶ Run Segmentation", variant="primary")
|
|
|
|
| 439 |
|
| 440 |
run_btn.click(
|
| 441 |
fn=run_sam3,
|
| 442 |
+
inputs=[file_input, prompt_input, model_toggle],
|
| 443 |
outputs=[image_output, video_output, download_output, status_box],
|
| 444 |
)
|
| 445 |
|