V4ldeLund commited on
Commit
281a357
·
verified ·
1 Parent(s): 58606bd

Handle SAM3 gated model with HF_TOKEN and trust_remote_code

Browse files
app.py CHANGED
@@ -37,7 +37,15 @@ def load_sam3(prompt: str, device: str):
37
  "This Space installs transformers from GitHub; if you still see this, restart the Space "
38
  "to rebuild with the latest image."
39
  )
40
- return SAM3Segmenter(text_prompt=prompt, device=device)
 
 
 
 
 
 
 
 
41
 
42
 
43
  def _make_overlay(rgb_image: np.ndarray, anomaly_map: np.ndarray) -> Image.Image:
 
37
  "This Space installs transformers from GitHub; if you still see this, restart the Space "
38
  "to rebuild with the latest image."
39
  )
40
+ try:
41
+ return SAM3Segmenter(text_prompt=prompt, device=device)
42
+ except OSError as e:
43
+ # Common for gated models when HF_TOKEN is not set
44
+ raise gr.Error(
45
+ "Failed to load SAM3. The model is gated; please add your HF token as a Space secret "
46
+ "named HF_TOKEN (Settings → Secrets) and restart the Space.\n\n"
47
+ f"Loader error: {e}"
48
+ )
49
 
50
 
51
  def _make_overlay(rgb_image: np.ndarray, anomaly_map: np.ndarray) -> Image.Image:
segmenters/__pycache__/sam3.cpython-311.pyc CHANGED
Binary files a/segmenters/__pycache__/sam3.cpython-311.pyc and b/segmenters/__pycache__/sam3.cpython-311.pyc differ
 
segmenters/sam3.py CHANGED
@@ -3,7 +3,8 @@ from __future__ import annotations
3
  import numpy as np
4
  import torch
5
  from PIL import Image
6
- from transformers import Sam3Processor, Sam3Model
 
7
 
8
  from segmenters import BaseSegmenter
9
 
@@ -41,9 +42,19 @@ class SAM3Segmenter(BaseSegmenter):
41
  self.mask_threshold = mask_threshold
42
 
43
  # Loading model model + defining processor
44
- self.model = Sam3Model.from_pretrained(model_name).to(self.device)
45
- self.model.eval()
46
- self.processor = Sam3Processor.from_pretrained(model_name)
 
 
 
 
 
 
 
 
 
 
47
 
48
  def get_object_mask(self, image: np.ndarray) -> np.ndarray:
49
  """
 
3
  import numpy as np
4
  import torch
5
  from PIL import Image
6
+ import os
7
+ from transformers import Sam3Processor, Sam3Model
8
 
9
  from segmenters import BaseSegmenter
10
 
 
42
  self.mask_threshold = mask_threshold
43
 
44
  # Loading model model + defining processor
45
+ token = os.getenv("HF_TOKEN")
46
+ # facebook/sam3 is a gated model; token required on Spaces without pre-approval
47
+ self.model = Sam3Model.from_pretrained(
48
+ model_name,
49
+ token=token,
50
+ trust_remote_code=True,
51
+ ).to(self.device)
52
+ self.model.eval()
53
+ self.processor = Sam3Processor.from_pretrained(
54
+ model_name,
55
+ token=token,
56
+ trust_remote_code=True,
57
+ )
58
 
59
  def get_object_mask(self, image: np.ndarray) -> np.ndarray:
60
  """