""" Combined SAM2 + SAM3 Hugging Face Inference Handler - SAM2: Point-based segmentation (encode/decode pattern) - SAM3: Text-based segmentation """ from transformers import Sam2Processor, Sam2Model, Sam3Processor, Sam3Model import torch from PIL import Image import numpy as np import base64 import io from typing import Any, Dict, List, Optional class EndpointHandler: def __init__(self, path: str = ""): self.device = "cuda" if torch.cuda.is_available() else "cpu" # Load SAM2 for point-based segmentation print("Loading SAM2 model...") self.sam2_model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-large").to( self.device ) self.sam2_processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-large") # Load SAM3 for text-based segmentation print("Loading SAM3 model...") self.sam3_model = Sam3Model.from_pretrained("facebook/sam3").to(self.device) self.sam3_processor = Sam3Processor.from_pretrained("facebook/sam3") print(f"Models loaded on {self.device}") def _decode_base64_image(self, image_data: str) -> Image.Image: """Decode base64 image string to PIL Image.""" # Remove data URL prefix if present if "," in image_data: image_data = image_data.split(",", 1)[1] image_bytes = base64.b64decode(image_data) image = Image.open(io.BytesIO(image_bytes)).convert("RGB") return image def _encode_mask_to_base64(self, mask: np.ndarray) -> str: """Encode binary mask to base64 PNG string.""" # Convert boolean/float mask to uint8 if mask.dtype == bool: mask_uint8 = (mask * 255).astype(np.uint8) else: mask_uint8 = (mask > 0.5).astype(np.uint8) * 255 # Create PIL image from mask mask_image = Image.fromarray(mask_uint8, mode="L") # Encode to base64 buffer = io.BytesIO() mask_image.save(buffer, format="PNG") mask_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8") return mask_base64 def _encode_tensor_to_base64(self, tensor) -> str: """Encode a tensor (or list of tensors) to base64 for client-side storage.""" # Handle list case if isinstance(tensor, list): tensor = tensor[0] if tensor else None if tensor is None: raise ValueError("No tensor to encode") # Move to CPU if needed if hasattr(tensor, "cpu"): tensor = tensor.cpu() buffer = io.BytesIO() torch.save(tensor, buffer) return base64.b64encode(buffer.getvalue()).decode("utf-8") def _decode_base64_to_tensor(self, data: str) -> torch.Tensor: """Decode base64 string back to tensor.""" buffer = io.BytesIO(base64.b64decode(data)) return torch.load(buffer, map_location=self.device) # ==================== SAM2: Point-based Segmentation ==================== def _sam2_encode(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """ Encode image with SAM2 - stores the image for later decode. Input: { "action": "encode", "image": "" } Output: { "features": "", "original_size": [height, width] } """ image_data = inputs.get("image") if not image_data: return {"error": "No image provided"} image = self._decode_base64_image(image_data) original_size = [image.height, image.width] # For SAM2, we store the image itself (not embeddings) to do full inference in decode # This is simpler and more reliable than trying to cache embeddings # Strip data URL prefix if present for consistency if "," in image_data: image_b64 = image_data.split(",", 1)[1] else: image_b64 = image_data return { "features": image_b64, "original_size": original_size, } def _sam2_decode(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """ Decode masks from image and point prompts using SAM2. Input: { "action": "decode", "features": "", "original_size": [height, width], "points": [[x1, y1], [x2, y2], ...], "labels": [1, 0, ...], # 1 = positive, 0 = negative "mask_input": "" } Output: { "masks": ["", "", ...], "scores": [0.95, 0.87, ...], "best_mask_idx": 0 } """ features_data = inputs.get("features") original_size = inputs.get("original_size") points = inputs.get("points", []) labels = inputs.get("labels", []) if not features_data: return {"error": "No features provided"} if not original_size: return {"error": "No original_size provided"} if not points or not labels: return {"error": "No points/labels provided"} # Decode the image from base64 image = self._decode_base64_image(features_data) # Format points for SAM2 processor # SAM2 processor expects: [[[x1, y1], [x2, y2], ...]] for input_points # And [[label1, label2, ...]] for input_labels input_points = [[points]] input_labels = [[labels]] try: # Process through SAM2 processor processor_inputs = self.sam2_processor( images=image, input_points=input_points, input_labels=input_labels, return_tensors="pt", ).to(self.device) with torch.no_grad(): outputs = self.sam2_model(**processor_inputs) except Exception as model_err: return { "error": f"Model inference failed: {str(model_err)}", "points": str(points), "labels": str(labels), } # Get pred_masks - handle both tensor and list cases pred_masks = outputs.pred_masks if isinstance(pred_masks, list): pred_masks = pred_masks[0] if pred_masks else None if pred_masks is None: return {"error": "No masks generated"} # Move to CPU if it's a tensor if hasattr(pred_masks, "cpu"): pred_masks_cpu = pred_masks.cpu() else: pred_masks_cpu = torch.tensor(pred_masks) # Post-process masks try: masks_list = self.sam2_processor.post_process_masks( pred_masks_cpu, original_sizes=[original_size], ) except Exception as post_err: # If post_process fails, try to handle masks directly return { "error": f"post_process_masks failed: {str(post_err)}", "pred_masks_type": str(type(pred_masks_cpu)), "pred_masks_shape": str(pred_masks_cpu.shape) if hasattr(pred_masks_cpu, "shape") else "N/A", } # Get the first batch result masks = masks_list[0] if masks_list else None if masks is None: return {"error": "Post-processing returned no masks"} # Get IoU scores iou_scores = outputs.iou_scores if isinstance(iou_scores, list): iou_scores = iou_scores[0] if iou_scores else torch.tensor([0.5]) if hasattr(iou_scores, "cpu"): scores = iou_scores.cpu().numpy().flatten().tolist() else: scores = [float(s) for s in np.array(iou_scores).flatten()] # Convert masks to base64 - handle tensor or list masks_base64 = [] def extract_mask(m): """Extract numpy array from mask.""" if hasattr(m, "cpu"): m = m.cpu() if hasattr(m, "numpy"): return m.numpy() return np.array(m) # Handle different mask formats if isinstance(masks, list): # List of masks for mask in masks[:3]: mask_np = extract_mask(mask) # Handle extra dimensions while len(mask_np.shape) > 2: mask_np = mask_np[0] masks_base64.append(self._encode_mask_to_base64(mask_np)) elif hasattr(masks, "shape"): # Tensor case masks_cpu = masks.cpu() if hasattr(masks, "cpu") else masks if len(masks_cpu.shape) == 4: # Shape: [1, num_masks, H, W] for i in range(min(masks_cpu.shape[1], 3)): mask_np = extract_mask(masks_cpu[0, i]) masks_base64.append(self._encode_mask_to_base64(mask_np)) elif len(masks_cpu.shape) == 3: # Shape: [num_masks, H, W] for i in range(min(masks_cpu.shape[0], 3)): mask_np = extract_mask(masks_cpu[i]) masks_base64.append(self._encode_mask_to_base64(mask_np)) else: # Shape: [H, W] - single mask mask_np = extract_mask(masks_cpu) masks_base64.append(self._encode_mask_to_base64(mask_np)) else: return {"error": f"Unexpected masks type: {type(masks)}"} # Find best mask by score best_idx = int(np.argmax(scores[:len(masks_base64)])) if scores else 0 return { "masks": masks_base64, "scores": scores[:len(masks_base64)], "best_mask_idx": best_idx, } # ==================== SAM3: Text-based Segmentation ==================== def _sam3_segment_text(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """ Segment image using text prompt with SAM3. Input: { "action": "segment_text", "image": "", "prompt": "text description of what to segment", "confidence_threshold": 0.5, "mask_threshold": 0.5 } Output: { "masks": ["", "", ...], "scores": [0.95, 0.87, ...], "boxes": [[x1, y1, x2, y2], ...], "best_mask_idx": 0, "message": "Found N objects" } """ image_data = inputs.get("image") prompt = inputs.get("prompt", "") confidence_threshold = float(inputs.get("confidence_threshold", 0.5)) mask_threshold = float(inputs.get("mask_threshold", 0.5)) if not image_data: return {"error": "No image provided"} if not prompt: return {"error": "No text prompt provided"} # Decode base64 image image = self._decode_base64_image(image_data) # Process with SAM3 processor_inputs = self.sam3_processor( images=image, text=prompt, return_tensors="pt" ) processor_inputs = processor_inputs.to(self.device) with torch.no_grad(): outputs = self.sam3_model(**processor_inputs) # Post-process to get masks results = self.sam3_processor.post_process_instance_segmentation( outputs, threshold=confidence_threshold, mask_threshold=mask_threshold, target_sizes=[(image.height, image.width)], )[0] masks = results.get("masks", []) scores = results.get("scores", []) boxes = results.get("boxes", []) if len(masks) == 0: return { "masks": [], "scores": [], "boxes": [], "best_mask_idx": 0, "message": f"No objects matching '{prompt}' found", } # Convert masks to base64 masks_base64: List[str] = [] scores_list: List[float] = [] boxes_list: List[List[float]] = [] for i, mask in enumerate(masks): # Convert tensor to numpy if needed if hasattr(mask, "cpu"): mask_np = mask.cpu().numpy() else: mask_np = np.array(mask) masks_base64.append(self._encode_mask_to_base64(mask_np)) # Get score if i < len(scores): score = scores[i] if hasattr(score, "item"): score = score.item() scores_list.append(float(score)) # Get box if i < len(boxes): box = boxes[i] if hasattr(box, "tolist"): box = box.tolist() boxes_list.append([float(x) for x in box]) # Find best mask (highest score) best_idx = 0 if scores_list: best_idx = int(np.argmax(scores_list)) return { "masks": masks_base64, "scores": scores_list, "boxes": boxes_list, "best_mask_idx": best_idx, "message": f"Found {len(masks_base64)} object(s) matching '{prompt}'", } # ==================== Main Handler ==================== def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]: """ Main handler entry point. Routes to appropriate method based on action: - "encode": SAM2 image encoding - "decode": SAM2 mask decoding from points - "segment_text": SAM3 text-based segmentation """ try: # Extract inputs (HuggingFace wraps in "inputs" key) inputs = data.get("inputs", data) action = inputs.get("action", "segment_text") if action == "encode": return self._sam2_encode(inputs) elif action == "decode": return self._sam2_decode(inputs) elif action == "segment_text": return self._sam3_segment_text(inputs) else: return {"error": f"Unknown action: {action}"} except Exception as e: import traceback return {"error": str(e), "traceback": traceback.format_exc()}