Ë
    Fêñiv"  ã                  ó‚   — d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d	d
lmZ  G d„ de«      Zy)é    )ÚannotationsN)ÚImage)ÚSegmentationPredictor)ÚDEFAULT_CFG)Úbox_iou)Úscale_masks)Ú
TORCH_1_10é   )Úadjust_bboxes_to_image_borderc                  óJ   ‡ — e Zd ZdZeddfdˆ fd„Zˆ fd„Zd	d„Zd„ Zd„ Z	ˆ xZ
S )
ÚFastSAMPredictora’  FastSAMPredictor is specialized for fast SAM (Segment Anything Model) segmentation prediction tasks.

    This class extends the SegmentationPredictor, customizing the prediction pipeline specifically for fast SAM. It
    adjusts post-processing steps to incorporate mask prediction and non-maximum suppression while optimizing for
    single-class segmentation.

    Attributes:
        prompts (dict): Dictionary containing prompt information for segmentation (bboxes, points, labels, texts).
        device (torch.device): Device on which model and tensors are processed.
        clip (Any, optional): CLIP model used for text-based prompting, loaded on demand.

    Methods:
        postprocess: Apply postprocessing to FastSAM predictions and handle prompts.
        prompt: Perform image segmentation inference based on various prompt types.
        set_prompts: Set prompts to be used during inference.
    Nc                ó6   •— t         ‰| �  |||«       i | _        y)a;  Initialize the FastSAMPredictor with configuration and callbacks.

        This initializes a predictor specialized for Fast SAM (Segment Anything Model) segmentation tasks. The predictor
        extends SegmentationPredictor with custom post-processing for mask prediction and non-maximum suppression
        optimized for single-class segmentation.

        Args:
            cfg (dict): Configuration for the predictor.
            overrides (dict, optional): Configuration overrides.
            _callbacks (dict, optional): Dictionary of callback functions.
        N)ÚsuperÚ__init__Úprompts)ÚselfÚcfgÚ	overridesÚ
_callbacksÚ	__class__s       €úd/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/models/fastsam/predict.pyr   zFastSAMPredictor.__init__#   s   ø€ ô 	‰Ñ˜˜i¨Ô4Øˆ�ó    c                ó  •— | j                   j                  dd«      }| j                   j                  dd«      }| j                   j                  dd«      }| j                   j                  dd«      }t        ‰| �  |||«      }|D ]î  }	t	        j
                  dd|	j                  d   |	j                  d   g|	j                  j                  j                  t        j                  ¬«      }
t        |	j                  j                  |	j                  «      }t	        j                  t        |
d   |«      d	kD  «      j                  «       }|j!                  «       dk7  sŒÖ|
|	j                  j                  |<   Œð | j#                  |||||¬
«      S )a”  Apply postprocessing to FastSAM predictions and handle prompts.

        Args:
            preds (list[torch.Tensor]): Raw predictions from the model.
            img (torch.Tensor): Input image tensor that was fed to the model.
            orig_imgs (list[np.ndarray]): Original images before preprocessing.

        Returns:
            (list[Results]): Processed results with prompts applied.
        ÚbboxesNÚpointsÚlabelsÚtextsr   r
   )ÚdeviceÚdtypegÍÌÌÌÌÌì?)r   r   r   r   )r   Úpopr   ÚpostprocessÚtorchÚtensorÚ
orig_shapeÚboxesÚdatar   Úfloat32r   ÚxyxyÚnonzeror   ÚflattenÚnumelÚprompt)r   ÚpredsÚimgÚ	orig_imgsr   r   r   r   ÚresultsÚresultÚfull_boxr%   Úidxr   s                €r   r!   zFastSAMPredictor.postprocess2   sM  ø€ ð —‘×!Ñ! (¨DÓ1ˆØ—‘×!Ñ! (¨DÓ1ˆØ—‘×!Ñ! (¨DÓ1ˆØ—‘× Ñ  ¨$Ó/ˆÜ‘'Ñ% e¨S°)Ó<ˆØò 	2ˆFÜ—|‘|Ø�A�v×(Ñ(¨Ñ+¨V×->Ñ->¸qÑ-AÐBÈ6Ï<É<×K\ÑK\×KcÑKcÔkp×kxÑkxôˆHô 2°&·,±,×2CÑ2CÀV×EVÑEVÓWˆEÜ—-‘-¤¨°©¸Ó >ÀÑ DÓE×MÑMÓOˆCØ�y‰y‹{˜aÓØ)1�—‘×!Ñ! #Ò&ð	2ð �{‰{˜7¨6¸&ÈÐW\ˆ{Ó]Ð]r   c                ó²
  — |€|€|€|S g }t        |t        «      s|g}|D �])  }t        |«      dk(  r|j                  |«       Œ$|j                  j
                  }|j                  dd |j                  k7  r;t        |d   j                  «       |j                  «      d   dkD  j                  «       }t        j                  t        |«      t        j                  | j                  ¬«      }	|�ût        j                  |t        j                   | j                  ¬«      }|j"                  dk(  r|d   n|}|dd…df   |dd…df   z
  |dd…df   |dd…df   z
  z  }
t        j$                  |D �cg c],  }|dd…|d   |d   …|d   |d   …f   j'                  d¬	«      ‘Œ. c}«      }t        j&                  |d¬	«      }|
dd…df   |z   |z
  }d
|	t        j(                  ||z  d¬	«      <   |��£t        j                  |t        j                   | j                  ¬«      }|j"                  dk(  r|d   n|}|€"t        j*                  |j                  d   «      }t        j                  |t        j                   | j                  ¬«      }t        |«      t        |«      k(  s J dt        |«      › dt        |«      › d�«       ‚|j'                  «       dk(  r9t        j*                  t        |«      t        j                  | j                  ¬«      n8t        j                  t        |«      t        j                  | j                  ¬«      }t-        ||«      D ]9  \  }}t        |«      |t        j.                  |dd…|d   |d   f   d
¬«      d   <   Œ; |	|z  }	|��¦t        |t0        «      r|g}g g }}t3        |j4                  j6                  j9                  «       «      D ]Ó  \  }}d„ |D «       \  }}}}t:        r||   j'                  «       n!||   j'                  d«      j'                  «       dk  r|j                  |«       Œd|j<                  ||…||…f   ||||…||…df   j?                  «       jA                  «       z  }|j                  tC        jD                  |dd…dd…ddd…f   «      «       ŒÕ | jG                  ||«      }t        j(                  |d¬	«      }t        |«      rStI        t        |«      «      D �cg c]	  }||vsŒ|‘Œ }}t        jJ                  |tM        |«         | j                  ¬«      }d
|	|<   |j                  ||	   «       �Œ, |S c c}w c c}w )a  Perform image segmentation inference based on cues like bounding boxes, points, and text prompts.

        Args:
            results (Results | list[Results]): Original inference results from FastSAM models without any prompts.
            bboxes (np.ndarray | list, optional): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | list, optional): Points indicating object locations with shape (N, 2), in pixels.
            labels (np.ndarray | list, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
            texts (str | list[str], optional): Textual prompts, a list containing string objects.

        Returns:
            (list[Results]): Output results filtered and determined by the provided prompts.
        Nr   r
   g      à?)r   r   é   é   )r
   r6   )ÚdimTz?Expected `labels` to have the same length as `points`, but got z and ú.)Úas_tuplec              3  ó2   K  — | ]  }t        |«      –— Œ y ­w)N)Úint)Ú.0Úxs     r   ú	<genexpr>z*FastSAMPredictor.prompt.<locals>.<genexpr>‡   s   è ø€ Ò%8°¤c¨!§fÑ%8ùs   ‚éd   éÿÿÿÿ©r   )'Ú
isinstanceÚlistÚlenÚappendÚmasksr&   Úshaper$   r   ÚfloatÚbyter"   ÚzerosÚboolr   Ú	as_tensorÚint32ÚndimÚstackÚsumÚargmaxÚonesÚzipr)   ÚstrÚ	enumerater%   r(   Útolistr	   Úorig_imgÚcpuÚnumpyr   Ú	fromarrayÚ_clip_inferenceÚranger#   r;   )r   r0   r   r   r   r   Úprompt_resultsr1   rF   r3   Ú
bbox_areasÚbÚ
mask_areasÚfull_mask_areasÚunionÚ	point_idxÚpointÚlabelÚcrop_imsÚ
filter_idxÚiÚx1Úy1Úx2Úy2ÚcropÚ
similarityÚtext_idxÚori_idxss                                r   r,   zFastSAMPredictor.promptM   sÌ  € ð ˆ>˜f˜n°°ØˆNØˆÜ˜'¤4Ô(Ø�iˆGØó 6	/ˆFÜ�6‹{˜aÒØ×%Ñ% fÔ-ØØ—L‘L×%Ñ%ˆEØ�{‰{˜1˜2ˆ &×"3Ñ"3Ò3Ü$ U¨4¡[×%6Ñ%6Ó%8¸&×:KÑ:KÓLÈQÑOÐRUÑU×[Ñ[Ó]�ä—+‘+œc &›k´·±ÀDÇKÁKÔPˆCØÐ!ÜŸ™¨´u·{±{È4Ï;É;ÔW�Ø)/¯©¸Ò)9˜ š¸v�Ø$¢Q¨ T™l¨V²A°q°D©\Ñ9¸fÂQÈÀT¹lÈVÒTUÐWXÐTXÉ\Ñ>YÑZ�
Ü"Ÿ[™[ÐflÖ)mÐab¨%²°1°Q±4¸!¸A¹$°;ÀÀ!ÁÀqÈÁtÀÐ0KÑ*L×*PÑ*PÐU[Ð*PÕ*\Ò)mÓn�
Ü"'§)¡)¨E°vÔ">�à"¢1 d 7Ñ+¨oÑ=À
ÑJ�Ø?C�”E—L‘L ¨eÑ!3¸Ô;Ñ<ØÑ!ÜŸ™¨´u·{±{È4Ï;É;ÔW�Ø)/¯©¸Ò)9˜ š¸v�Ø�>Ü"ŸZ™Z¨¯©°Q©Ó8�FÜŸ™¨´u·{±{È4Ï;É;ÔW�Ü˜6“{¤c¨&£kÒ1ð ØUÔVYÐZ`ÓVaÐUbÐbgÔhkÐlrÓhsÐgtÐtuÐvóÐ1ð
 —z‘z“| qÒ(ô —J‘Jœs 6›{´%·*±*ÀTÇ[Á[ÕQäŸ™¤S¨£[¼¿
¹
È4Ï;É;ÔWð ô
 %(¨°Ó$7ò k‘L�E˜5Ü_cÐdiÓ_j�IœeŸm™m¨E²!°U¸1±X¸uÀQ¹xÐ2GÑ,HÐSWÔXÐYZÑ[Ò\ðkà�yÑ �ØÑ Ü˜e¤SÔ)Ø"˜G�EØ')¨2˜*�Ü% f§l¡l×&7Ñ&7×&>Ñ&>Ó&@ÓAò G‘D�A�qÙ%8°aÔ%8‘N�B˜˜B Ý*4˜˜a™Ÿ™œ¸%À¹(¿,¹,Àq»/×:MÑ:MÓ:OÐTWÒWØ"×)Ñ)¨!Ô,Ø Ø!Ÿ?™?¨2¨b¨5°"°R°%¨<Ñ8¸5ÀÀBÀrÀEÈ2ÈbÈ5ÐRVÐAVÑ;W×;[Ñ;[Ó;]×;cÑ;cÓ;eÑe�DØ—O‘O¤E§O¡O°DººA¹tÀ¸t¸Ñ4DÓ$EÕFðGð "×1Ñ1°(¸EÓB�
Ü Ÿ<™<¨
¸Ô;�Ü�z”?ä+0´°V³Ó+=ÖU aÀÈ*ÒAT¢ÐU�HÐUÜ$Ÿ|™|¨H´S¸³]Ñ,CÈDÏKÉKÔX�HØ $��H‘à×!Ñ! &¨¡+Ö.ðm6	/ðp ÐùòW *nùòJ  Vs   Å,1U
Ó4	UÓ>Uc                óÈ  — ddl m} t        | d«      s |d| j                  ¬«      | _        t        j                  |D �cg c]6  }| j                  j                  |«      j                  | j                  «      ‘Œ8 c}«      }| j                  j                  |«      }| j                  j                  | j                  j                  |«      «      }||j                  z  S c c}w )aœ  Perform CLIP inference to calculate similarity between images and text prompts.

        Args:
            images (list[PIL.Image]): List of source images, each should be PIL.Image with RGB channel order.
            texts (list[str]): List of prompt texts, each should be a string object.

        Returns:
            (torch.Tensor): Similarity matrix between given images and texts with shape (M, N).
        r   )ÚCLIPÚclipzViT-B/32rA   )Úultralytics.nn.text_modelrr   Úhasattrr   rs   r"   rO   Úimage_preprocessÚtoÚencode_imageÚencode_textÚtokenizeÚT)r   Úimagesr   rr   ÚimageÚimage_featuresÚtext_featuress          r   r[   z FastSAMPredictor._clip_inference™   sª   € õ 	3ä�t˜VÔ$Ù˜Z°·±Ô<ˆDŒIÜ—‘Ð]cÖdÐTY˜dŸi™i×8Ñ8¸Ó?×BÑBÀ4Ç;Á;ÕOÒdÓeˆØŸ™×/Ñ/°Ó7ˆØŸ	™	×-Ñ-¨d¯i©i×.@Ñ.@ÀÓ.GÓHˆØ˜~×/Ñ/Ñ/Ð/ùò es   ¿;Cc                ó   — || _         y)z(Set prompts to be used during inference.N)r   )r   r   s     r   Úset_promptszFastSAMPredictor.set_prompts¬   s	   € àˆ�r   )r   zdict | None)NNNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r!   r,   r[   r�   Ú__classcell__)r   s   @r   r   r      s.   ø„ ñð" '°$ÐRVö ô^ó6JòX0ö&r   r   )Ú
__future__r   r"   ÚPILr   Úultralytics.models.yolo.segmentr   Úultralytics.utilsr   Úultralytics.utils.metricsr   Úultralytics.utils.opsr   Úultralytics.utils.torch_utilsr	   Úutilsr   r   © r   r   ú<module>r�      s1   ðõ #ã Ý å AÝ )Ý -Ý -Ý 4å 0ô]Ð,õ ]r   