§
    ‚Štj2  ã                   ó^   — d dl Z ddlmZ ddlmZmZ ddlmZ d„ Z G d„ d	e¦  «        Z	d	gZ
dS )
é    Né   )Ú'SemanticSegmentationPostProcessorOutput)ÚIMAGENET_STANDARD_MEANÚIMAGENET_STANDARD_STDé   )ÚSam2ImageProcessorc                 óÔ  — t          |t          t          f¦  «        r=t          j        d„ |D ¦   «         ¦  «        }t          j        d„ |D ¦   «         ¦  «        }nBt          |t          j        ¦  «        r|                     d¦  «        \  }}nt          d¦  «        ‚t          j        ||||gd¬¦  «        }| 	                    d¦  «         
                    | j        ¦  «        }| |z  } | S )a  
    Scale batch of bounding boxes to the target sizes.

    Args:
        boxes (`torch.Tensor` of shape `(batch_size, num_boxes, 4)`):
            Bounding boxes to scale. Each box is expected to be in (x1, y1, x2, y2) format.
        target_sizes (`list[tuple[int, int]]` or `torch.Tensor` of shape `(batch_size, 2)`):
            Target sizes to scale the boxes to. Each target size is expected to be in (height, width) format.

    Returns:
        `torch.Tensor` of shape `(batch_size, num_boxes, 4)`: Scaled bounding boxes.
    c                 ó   — g | ]
}|d          ‘ŒS )r   © ©Ú.0Úis     úc/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/transformers/models/sam3/modular_sam3.pyú
<listcomp>z _scale_boxes.<locals>.<listcomp>)   s   € Ð$@Ð$@Ð$@¨a Q q¤TÐ$@Ð$@Ð$@ó    c                 ó   — g | ]
}|d          ‘ŒS )é   r   r   s     r   r   z _scale_boxes.<locals>.<listcomp>*   s   € Ð#?Ð#?Ð#?¨Q A a¤DÐ#?Ð#?Ð#?r   r   z4`target_sizes` must be a list, tuple or torch.Tensor©Údim)Ú
isinstanceÚlistÚtupleÚtorchÚtensorÚTensorÚunbindÚ	TypeErrorÚstackÚ	unsqueezeÚtoÚdevice)ÚboxesÚtarget_sizesÚimage_heightÚimage_widthÚscale_factors        r   Ú_scale_boxesr'      sç   € õ �,¥¥u Ñ.Ô.ð PÝ”|Ð$@Ð$@°<Ð$@Ñ$@Ô$@ÑAÔAˆÝ”lÐ#?Ð#?°,Ð#?Ñ#?Ô#?Ñ@Ô@ˆˆÝ	�L¥%¤,Ñ	/Ô	/ð PØ$0×$7Ò$7¸Ñ$:Ô$:Ñ!ˆ�k�kåÐNÑOÔOÐOå”; ¨\¸;ÈÐUÐ[\Ð]Ñ]Ô]€LØ×)Ò)¨!Ñ,Ô,×/Ò/°´Ñ=Ô=€LØ�LÑ €EØ€Lr   c            	       ó¾   — e Zd ZeZeZdddœZdddœZ	 	 	 dde	e
eef                  dz  ded	ed
dfd„Zddede	e
         dz  fd„Z	 	 	 ddedede	e
         dz  fd„ZdS )ÚSam3ImageProcessorið  )ÚheightÚwidthi   Nç      à?Fr#   Ú	thresholdÚreturn_segmentation_scoresÚreturnzBlist[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]c                 ó–  ‡‡
— |j         }|€t          d¦  «        ‚|                     ¦   «         Š
t          |¦  «        }|�ßt          |¦  «        t          |¦  «        k    rt          d¦  «        ‚g }t	          |¦  «        D ]�}t
          j        j                             ‰
|          	                    d¬¦  «        ||         dd¬¦  «        }	| 
                    t          |	d	         ‰k                         t
          j        ¦  «        |	d         d
œ¬¦  «        ¦  «         Œžnˆ
ˆfd„t	          |¦  «        D ¦   «         }|sd„ |D ¦   «         }|S )a±  
        Converts the output of [`Sam3Model`] into semantic segmentation maps.

        Args:
            outputs ([`Sam3ImageSegmentationOutput`]):
                Raw outputs of the model containing semantic_seg.
            target_sizes (`list[tuple[int, int]]` of length `batch_size`, *optional*):
                List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
                predictions will not be resized.
            threshold (`float`, *optional*, defaults to 0.5):
                Threshold for binarizing the semantic segmentation masks.
            return_segmentation_scores (`bool`, *optional*, defaults to `False`):
                Whether to return segmentation scores alongside the segmentation map. When `True`, each element of
                the returned list is a [`SemanticSegmentationPostProcessorOutput`] with fields `segmentation`
                (binary class IDs, shape `(height, width)`) and `segmentation_scores` (sigmoid probabilities,
                shape `(1, height, width)`).

        Returns:
            `list[torch.Tensor]` or `list[SemanticSegmentationPostProcessorOutput]`: When
            `return_segmentation_scores=False` (default), a list of length `batch_size` where each item is a
            segmentation map of shape `(height, width)` with class IDs. When `return_segmentation_scores=True`,
            a list of [`SemanticSegmentationPostProcessorOutput`] with fields `segmentation` (class IDs, shape
            `(height, width)`) and `segmentation_scores` (shape `(1, height, width)`). In both cases,
            `(height, width)` corresponds to the target size (if `target_sizes` is specified).
        NzƒSemantic segmentation output is not available in the model outputs. Make sure the model was run with semantic segmentation enabled.zTMake sure that you pass in as many target sizes as the batch dimension of the logitsr   r   ÚbilinearF©ÚsizeÚmodeÚalign_corners)r   r   ©ÚsegmentationÚsegmentation_scores©Údatac                 ó”   •— g | ]D}t          ‰|d f         ‰k                         t          j        ¦  «        ‰|         dœ¬¦  «        ‘ŒES )r   r6   r9   )r   r    r   Úlong)r   r   Úsemantic_probsr-   s     €€r   r   zISam3ImageProcessor.post_process_semantic_segmentation.<locals>.<listcomp>‚   sm   ø€ ð %ð %ð %ð õ 8à)7¸¸1¸Ô)=À	Ò)I×(MÒ(MÍeÌjÑ(YÔ(YØ/=¸aÔ/@ðð ðñ ô ð%ð %ð %r   c                 ó   — g | ]	}|j         ‘Œ
S r   )r7   )r   Úitems     r   r   zISam3ImageProcessor.post_process_semantic_segmentation.<locals>.<listcomp>�   s   € Ð$YÐ$YÐ$Y¸4 TÔ%6Ð$YÐ$YÐ$Yr   )Úsemantic_segÚ
ValueErrorÚsigmoidÚlenÚranger   ÚnnÚ
functionalÚinterpolater   Úappendr   r    r<   )ÚselfÚoutputsr#   r-   r.   Úsemantic_logitsÚ
batch_sizeÚsemantic_segmentationÚidxÚresized_probsr=   s      `      @r   Ú"post_process_semantic_segmentationz5Sam3ImageProcessor.post_process_semantic_segmentation<   s°  øø€ ðD "Ô.ˆàÐ"ÝðRñô ð ð )×0Ò0Ñ2Ô2ˆÝ˜Ñ)Ô)ˆ
ð Ð#Ý�?Ñ#Ô#¥s¨<Ñ'8Ô'8Ò8Ð8Ý Øjñô ð ð %'Ð!Ý˜ZÑ(Ô(ð ð �Ý %¤Ô 3× ?Ò ?Ø" 3Ô'×1Ò1°aÐ1Ñ8Ô8Ø% cÔ*Ø#Ø"'ð	 !@ñ !ô !�ð &×,Ò,Ý;à-:¸4Ô-@À9Ò-L×,PÒ,PÕQVÔQ[Ñ,\Ô,\Ø3@ÀÔ3Cðð ðñ ô ñô ð ð ðð %ð %ð %ð %ð %õ ˜zÑ*Ô*ð%ñ %ô %Ð!ð *ð 	ZØ$YÐ$YÐCXÐ$YÑ$YÔ$YÐ!à$Ð$r   ç333333Ó?c                 ó¤  — |j         }|j        }|j        }|j        d         }|�"t	          |¦  «        |k    rt          d¦  «        ‚|                     ¦   «         }|�|                     ¦   «         }	||	z  }|}
|�t          |
|¦  «        }
g }t          ||
¦  «        D ]3\  }}||k    }||         }||         }| 	                    ||dœ¦  «         Œ4|S )aD  
        Converts the raw output of [`Sam3Model`] into final bounding boxes in (top_left_x, top_left_y,
        bottom_right_x, bottom_right_y) format.

        Args:
            outputs ([`Sam3ImageSegmentationOutput`]):
                Raw outputs of the model containing pred_boxes, pred_logits, and optionally presence_logits.
            threshold (`float`, *optional*, defaults to 0.3):
                Score threshold to keep object detection predictions.
            target_sizes (`list[tuple[int, int]]`, *optional*):
                List of tuples (`tuple[int, int]`) containing the target size `(height, width)` of each image in the
                batch. If unset, predictions will not be resized.

        Returns:
            `list[dict]`: A list of dictionaries, each dictionary containing the following keys:
                - **scores** (`torch.Tensor`): The confidence scores for each predicted box on the image.
                - **boxes** (`torch.Tensor`): Image bounding boxes in (top_left_x, top_left_y, bottom_right_x,
                  bottom_right_y) format.
        r   Nú9Make sure that you pass in as many target sizes as images)Úscoresr"   )
Úpred_logitsÚ
pred_boxesÚpresence_logitsÚshaperC   rA   rB   r'   ÚziprH   )rI   rJ   r-   r#   rU   rV   rW   rL   Úbatch_scoresÚpresence_scoresÚbatch_boxesÚresultsrT   r"   Úkeeps                  r   Úpost_process_object_detectionz0Sam3ImageProcessor.post_process_object_detection‘   s  € ð( Ô)ˆØÔ'ˆ
Ø!Ô1ˆà Ô& qÔ)ˆ
àÐ#­¨LÑ(9Ô(9¸ZÒ(GÐ(GÝÐXÑYÔYÐYð #×*Ò*Ñ,Ô,ˆØÐ&Ø-×5Ò5Ñ7Ô7ˆOØ'¨/Ñ9ˆLð !ˆð Ð#Ý& {°LÑAÔAˆKàˆÝ  ¨{Ñ;Ô;ð 	?ð 	?‰MˆF�EØ˜IÒ%ˆDØ˜D”\ˆFØ˜$”KˆEØ�NŠN f°uÐ=Ð=Ñ>Ô>Ð>Ð>àˆr   Úmask_thresholdc                 ó,  — |j         }|j        }|j        }|j        }|j        d         }	|�"t          |¦  «        |	k    rt          d¦  «        ‚|                     ¦   «         }
|�|                     ¦   «         }|
|z  }
|                     ¦   «         }|}|�t          ||¦  «        }g }t          t          |
||¦  «        ¦  «        D ]Î\  }\  }}}||k    }||         }||         }||         }|�i||         }t          |¦  «        dk    rNt          j        j                             |                     d¦  «        |dd¬¦  «                             d¦  «        }||k                         t          j        ¦  «        }|                     |||dœ¦  «         ŒÏ|S )aQ  
        Converts the raw output of [`Sam3Model`] into instance segmentation predictions with bounding boxes and masks.

        Args:
            outputs ([`Sam3ImageSegmentationOutput`]):
                Raw outputs of the model containing pred_boxes, pred_logits, pred_masks, and optionally
                presence_logits.
            threshold (`float`, *optional*, defaults to 0.3):
                Score threshold to keep instance predictions.
            mask_threshold (`float`, *optional*, defaults to 0.5):
                Threshold for binarizing the predicted masks.
            target_sizes (`list[tuple[int, int]]`, *optional*):
                List of tuples (`tuple[int, int]`) containing the target size `(height, width)` of each image in the
                batch. If unset, predictions will not be resized.

        Returns:
            `list[dict]`: A list of dictionaries, each dictionary containing the following keys:
                - **scores** (`torch.Tensor`): The confidence scores for each predicted instance on the image.
                - **boxes** (`torch.Tensor`): Image bounding boxes in (top_left_x, top_left_y, bottom_right_x,
                  bottom_right_y) format.
                - **masks** (`torch.Tensor`): Binary segmentation masks for each instance, shape (num_instances,
                  height, width).
        r   NrS   r1   Fr2   )rT   r"   Úmasks)rU   rV   Ú
pred_masksrW   rX   rC   rA   rB   r'   Ú	enumeraterY   r   rE   rF   rG   r   Úsqueezer    r<   rH   )rI   rJ   r-   r`   r#   rU   rV   rc   rW   rL   rZ   r[   Úbatch_masksr\   r]   rN   rT   r"   rb   r^   Útarget_sizes                        r   Ú"post_process_instance_segmentationz5Sam3ImageProcessor.post_process_instance_segmentationÄ   sÁ  € ð< Ô)ˆØÔ'ˆ
ØÔ'ˆ
Ø!Ô1ˆà Ô& qÔ)ˆ
àÐ#­¨LÑ(9Ô(9¸ZÒ(GÐ(GÝÐXÑYÔYÐYð #×*Ò*Ñ,Ô,ˆØÐ&Ø-×5Ò5Ñ7Ô7ˆOØ'¨/Ñ9ˆLð !×(Ò(Ñ*Ô*ˆð !ˆð Ð#Ý& {°LÑAÔAˆKàˆÝ+4µS¸À{ÐT_Ñ5`Ô5`Ñ+aÔ+að 	Oð 	OÑ'ˆCÑ'�&˜% à˜IÒ%ˆDØ˜D”\ˆFØ˜$”KˆEØ˜$”KˆEð Ð'Ø*¨3Ô/�Ý�u‘:”: ’>�>Ý!œHÔ/×;Ò;ØŸš¨Ñ*Ô*Ø(Ø'Ø&+ð	 <ñ ô ÷
 ’g˜a‘j”jð ð ˜^Ò+×/Ò/µ´
Ñ;Ô;ˆEà�NŠN f°uÀuÐMÐMÑNÔNÐNÐNàˆr   )Nr,   F)rQ   N)rQ   r,   N)Ú__name__Ú
__module__Ú__qualname__r   Ú
image_meanr   Ú	image_stdr3   Ú	mask_sizer   r   ÚintÚfloatÚboolrP   r_   rh   r   r   r   r)   r)   6   s+  € € € € € Ø'€JØ%€IØ TÐ*Ð*€DØ¨Ð-Ð-€Ið
 6:ØØ+0ðS%ð S%ð ˜5  c œ?Ô+¨dÑ2ðS%ð ð	S%ð
 %)ðS%ð 
NðS%ð S%ð S%ð S%ðj1ð 1Àð 1Ð[_Ð`eÔ[fÐimÑ[mð 1ð 1ð 1ð 1ðl Ø #Ø+/ðPð Pð ðPð ð	Pð
 ˜5”k DÑ(ðPð Pð Pð Pð Pð Pr   r)   )r   Úimage_processing_outputsr   Úimage_utilsr   r   Úsam2.image_processing_sam2r   r'   r)   Ú__all__r   r   r   ú<module>rv      s¯   ðð  €€€à OÐ OÐ OÐ OÐ OÐ Oðð ð ð ð ð ð ð ð <Ð ;Ð ;Ð ;Ð ;Ð ;ðð ð ð8^ð ^ð ^ð ^ð ^Ð+ñ ^ô ^ð ^ðB  Ð
 €€€r   