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97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"""
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": "<base64 encoded image>"
        }

        Output:
        {
            "features": "<base64 encoded image - passed through for decode>",
            "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": "<base64 encoded image>",
            "original_size": [height, width],
            "points": [[x1, y1], [x2, y2], ...],
            "labels": [1, 0, ...],  # 1 = positive, 0 = negative
            "mask_input": "<optional base64 previous mask>"
        }

        Output:
        {
            "masks": ["<base64 mask 1>", "<base64 mask 2>", ...],
            "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": "<base64 encoded image>",
            "prompt": "text description of what to segment",
            "confidence_threshold": 0.5,
            "mask_threshold": 0.5
        }

        Output:
        {
            "masks": ["<base64 mask 1>", "<base64 mask 2>", ...],
            "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()}