Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (7)
- AGENTS.md+1-2
- CLAUDE.md+1-2
- README.md+2-4
- requirements.txt+2-16
- src/sam_backend.py+6-42
- src/sam_card_detection.py+4-11
- src/sam_hand_segmentation.py+1-4
20 unmodified lines21222324252425262720 unmodified lines1. Read doc/v0/PRD.md, doc/v0/Plan.md, doc/v0/Progress.md for baseline implementation2. Read doc/v1/PRD.md, doc/v1/Plan.md, doc/v1/Progress.md for edge refinement (v1)3. Read doc/v4/PRD.md, doc/v4/Plan.md, doc/v4/Progress.md for SAM 2.1 integration (card + hand)4. Read doc/v5/PRD.md, doc/v5/Plan.md, doc/v5/Progress.md for the Gradio/ZeroGPU deployment port5. Assume this is a continuation of an existing project.4. Assume this is a continuation of an existing project.5. Summarize your understanding of the current state and propose the next concrete step without writing code yet.
## Project Overview20 unmodified lines21222324252425262720 unmodified lines1. Read doc/v0/PRD.md, doc/v0/Plan.md, doc/v0/Progress.md for baseline implementation2. Read doc/v1/PRD.md, doc/v1/Plan.md, doc/v1/Progress.md for edge refinement (v1)3. Read doc/v4/PRD.md, doc/v4/Plan.md, doc/v4/Progress.md for SAM 2.1 integration (card + hand)4. Read doc/v5/PRD.md, doc/v5/Plan.md, doc/v5/Progress.md for the Gradio/ZeroGPU deployment port5. Assume this is a continuation of an existing project.4. Assume this is a continuation of an existing project.5. Summarize your understanding of the current state and propose the next concrete step without writing code yet.
## Project Overview2 unmodified lines34567896789102 unmodified linesemoji: "\U0001F48D"colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 5.49.0app_file: app.pypython_version: "3.10"sdk: dockerapp_port: 7860---
# Ring Sizer6 unmodified lines7891011121310111216171314192021222324252627286 unmodified linesgunicorn>=21.2.0openai>=1.0.0supabase>=2.0.0# SAM 2.1 via HuggingFace transformers (card segmentation).# transformers pinned to the 4.x track for stability (SAM integration was# validated there). 4.x caps huggingface_hub at <1.0, which is fine for# everything downstream.# SAM 2.1 via HuggingFace transformers (card segmentation)torch>=2.4.0torchvision>=0.19.0transformers>=4.47.0,<5.0huggingface_hub>=0.33.5,<1.0transformers>=4.47.0pillow>=10.0.0# v5: HF ZeroGPU requires Gradio SDK; `spaces` provides @spaces.GPU (no-op off ZeroGPU).# Pinned to Gradio 5.x because:# - Gradio 4.x imports `HfFolder` from huggingface_hub; 5.x dropped it.# - Gradio 4.44 passes a dict as the template name to Starlette's# `TemplateResponse(...)`, which breaks against the newer# `starlette>=0.40` that Gradio's own deps pull in — crashes with# `TypeError: unhashable type: 'dict'` on every page load.# - Gradio 5.49 fixes both above.gradio>=5.49.0spaces>=0.30.022 unmodified lines23242526272829303132333435363738394041424344454647484950515253542627283 unmodified lines323334646566676869357136373874397640414279804344454647848548495022 unmodified lines
_model = None_processor = None_device: str = "cpu"
def _select_device() -> str: """Pick a torch device for SAM inference.
Returns ``"cuda"`` when a GPU is visible (HF ZeroGPU exposes CUDA even at module import time via an emulation shim, so this picks the right path both at startup and inside ``@spaces.GPU`` functions), otherwise ``"cpu"``. Import of torch is local so CLI users without it still see a clean error from the caller. """ try: import torch if torch.cuda.is_available(): return "cuda" except Exception: pass return "cpu"
def get_sam2_device() -> str: """Return the device the SAM singleton was loaded on.
Callers use this to move their ``processor(..., return_tensors="pt")`` outputs onto the same device as the model before the forward pass. Returns ``"cpu"`` before ``get_sam2()`` has been called. """ return _device
def get_sam2() -> Tuple[object, object]:3 unmodified lines the HEAD-request retry storm that happens when huggingface.co is slow or unreachable but the weights are already on disk. On a true cache miss we fall through to a normal online load.
The model is placed on the device returned by ``_select_device()``. HF ZeroGPU docs require CUDA placements to happen at module-level startup for best performance — callers in ZeroGPU Spaces should invoke ``get_sam2()`` once at import time so this runs before the first ``@spaces.GPU``-wrapped request. """ global _model, _processor, _device global _model, _processor if _model is None or _processor is None: from transformers import Sam2Model, Sam2Processor _device = _select_device() t0 = time.time() print(f" Loading SAM 2.1 ({SAM2_MODEL_ID}) on {_device}...") print(f" Loading SAM 2.1 ({SAM2_MODEL_ID})...") try: _processor = Sam2Processor.from_pretrained(SAM2_MODEL_ID, local_files_only=True) _model = Sam2Model.from_pretrained(SAM2_MODEL_ID, local_files_only=True).to(_device).eval() print(f" SAM 2.1 loaded (offline cache, {_device}) in {time.time() - t0:.1f}s") _model = Sam2Model.from_pretrained(SAM2_MODEL_ID, local_files_only=True).to("cpu").eval() print(f" SAM 2.1 loaded (offline cache) in {time.time() - t0:.1f}s") except (OSError, ValueError): # Cache miss — fall back to online download. _processor = Sam2Processor.from_pretrained(SAM2_MODEL_ID) _model = Sam2Model.from_pretrained(SAM2_MODEL_ID).to(_device).eval() print(f" SAM 2.1 loaded (online, {_device}) in {time.time() - t0:.1f}s") _model = Sam2Model.from_pretrained(SAM2_MODEL_ID).to("cpu").eval() print(f" SAM 2.1 loaded (online) in {time.time() - t0:.1f}s") return _model, _processor25 unmodified lines2627282929303132498 unmodified lines5315325335345355365375385395405345355365 unmodified lines54254354455255354554654754854955055855155255355425 unmodified lines get_quad_dimensions, order_corners,)from .sam_backend import INFERENCE_MAX_SIDE as PROMPT_INFERENCE_MAX_SIDE, get_sam2, get_sam2_devicefrom .sam_backend import INFERENCE_MAX_SIDE as PROMPT_INFERENCE_MAX_SIDE, get_sam2
# HF Hub model id — tiny, small, base-plus, largeSAM2_MODEL_ID = "facebook/sam2.1-hiera-small"498 unmodified lines input_labels=input_labels, return_tensors="pt", ) # `original_sizes` is used after the forward pass for mask post-processing # and scale calculations. Pull it to CPU before moving `inputs` to the # model device so downstream code never has to chase device placement. original_sizes_cpu = inputs["original_sizes"].cpu() if hasattr(inputs["original_sizes"], "cpu") else inputs["original_sizes"] device = get_sam2_device() if device != "cpu": inputs = inputs.to(device) with torch.inference_mode(): # multimask_output=True gives 3 masks per seed (small / medium / large # disambiguation of the prompt). Empirically this matters for card5 unmodified lines
# Score masks in the scaled 1024-space. Only the single winner is # upscaled to full resolution afterward, which avoids O(N) 12 MP resizes. scaled_h = int(original_sizes_cpu[0][0].item()) scaled_w = int(original_sizes_cpu[0][1].item()) scaled_h = inputs["original_sizes"][0][0].item() scaled_w = inputs["original_sizes"][0][1].item() scaled_area = float(scaled_h * scaled_w)
masks_list = processor.post_process_masks( outputs.pred_masks.cpu(), original_sizes_cpu, inputs["original_sizes"], mask_threshold=0.0, ) masks_tensor = masks_list[0] # (num_prompts, num_candidates, H_s, W_s)21 unmodified lines222324252526272858 unmodified lines87888990919290919221 unmodified linesimport cv2import numpy as np
from .sam_backend import INFERENCE_MAX_SIDE, get_sam2, get_sam2_devicefrom .sam_backend import INFERENCE_MAX_SIDE, get_sam2
def _downscale(image_bgr: np.ndarray) -> Tuple[np.ndarray, float]:58 unmodified lines input_labels=[[prompt_labels]], return_tensors="pt", ) device = get_sam2_device() if device != "cpu": inputs = inputs.to(device) with torch.inference_mode(): outputs = model(**inputs, multimask_output=True)
AGENTS.md+1-2
CLAUDE.md+1-2
README.md+2-4
requirements.txt+2-16
src/sam_backend.py+6-42
src/sam_card_detection.py+4-11
src/sam_hand_segmentation.py+1-4