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 lines212223242526272820 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.5. Summarize your understanding of the current state and propose the next concrete step without writing code yet.## Project Overview20 unmodified lines2122232425262720 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. 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 Overview
20 unmodified lines212223242526272820 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.5. Summarize your understanding of the current state and propose the next concrete step without writing code yet.## Project Overview20 unmodified lines2122232425262720 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. 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 Overview
2 unmodified lines34567891011122 unmodified linesemoji: "\U0001F48D"colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 5.49.0app_file: app.pypython_version: "3.10"---# Ring Sizer2 unmodified lines3456789102 unmodified linesemoji: "\U0001F48D"colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860---# Ring Sizer
6 unmodified lines789101112131415161718192021222324252627286 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.torch>=2.4.0torchvision>=0.19.0transformers>=4.47.0,<5.0huggingface_hub>=0.33.5,<1.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.06 unmodified lines78910111213146 unmodified linesgunicorn>=21.2.0openai>=1.0.0supabase>=2.0.0# SAM 2.1 via HuggingFace transformers (card segmentation)torch>=2.4.0torchvision>=0.19.0transformers>=4.47.0pillow>=10.0.0
22 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556573 unmodified lines616263646566676869707172737475767778798081828384858622 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 evenat module import time via an emulation shim, so this picks the rightpath both at startup and inside ``@spaces.GPU`` functions), otherwise``"cpu"``. Import of torch is local so CLI users without it still seea clean error from the caller."""try:import torchif torch.cuda.is_available():return "cuda"except Exception:passreturn "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 _devicedef get_sam2() -> Tuple[object, object]:3 unmodified linesthe HEAD-request retry storm that happens when huggingface.co is slow orunreachable but the weights are already on disk. On a true cache miss wefall 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-levelstartup 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, _deviceif _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}...")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")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")return _model, _processor22 unmodified lines2324252627283 unmodified lines3233343536373839404142434445464748495022 unmodified lines_model = None_processor = Nonedef get_sam2() -> Tuple[object, object]:3 unmodified linesthe HEAD-request retry storm that happens when huggingface.co is slow orunreachable but the weights are already on disk. On a true cache miss wefall through to a normal online load."""global _model, _processorif _model is None or _processor is None:from transformers import Sam2Model, Sam2Processort0 = time.time()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("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("cpu").eval()print(f" SAM 2.1 loaded (online) in {time.time() - t0:.1f}s")return _model, _processor
25 unmodified lines26272829303132498 unmodified lines5315325335345355365375385395405415425435 unmodified lines54955055155255355455555655755855956056125 unmodified linesget_quad_dimensions,order_corners,)from .sam_backend import INFERENCE_MAX_SIDE as PROMPT_INFERENCE_MAX_SIDE, get_sam2, get_sam2_device# HF Hub model id — tiny, small, base-plus, largeSAM2_MODEL_ID = "facebook/sam2.1-hiera-small"498 unmodified linesinput_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_area = float(scaled_h * scaled_w)masks_list = processor.post_process_masks(outputs.pred_masks.cpu(),original_sizes_cpu,mask_threshold=0.0,)masks_tensor = masks_list[0] # (num_prompts, num_candidates, H_s, W_s)25 unmodified lines26272829303132498 unmodified lines5315325335345355365 unmodified lines54254354454554654754854955055155255355425 unmodified linesget_quad_dimensions,order_corners,)from .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 linesinput_labels=input_labels,return_tensors="pt",)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 = 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(),inputs["original_sizes"],mask_threshold=0.0,)masks_tensor = masks_list[0] # (num_prompts, num_candidates, H_s, W_s)
21 unmodified lines2223242526272858 unmodified lines87888990919293949521 unmodified linesimport cv2import numpy as npfrom .sam_backend import INFERENCE_MAX_SIDE, get_sam2, get_sam2_devicedef _downscale(image_bgr: np.ndarray) -> Tuple[np.ndarray, float]:58 unmodified linesinput_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)21 unmodified lines2223242526272858 unmodified lines87888990919221 unmodified linesimport cv2import numpy as npfrom .sam_backend import INFERENCE_MAX_SIDE, get_sam2def _downscale(image_bgr: np.ndarray) -> Tuple[np.ndarray, float]:58 unmodified linesinput_labels=[[prompt_labels]],return_tensors="pt",)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