
    g*                         d Z ddlmZ ddlmZmZ ddlZddlm	Z	 ddl
mZ ddlmZmZmZ  e            rddlZ e            rddlZ G d	 d
e	          ZdS )z
Processor class for SAM.
    )deepcopy)OptionalUnionN   )ProcessorMixin)BatchEncoding)
TensorTypeis_tf_availableis_torch_availablec                        e Zd ZdZdgZdZ fdZ	 	 	 	 	 	 ddeee	e
f                  defdZ	 	 	 	 dd
Zd Z	 ddedej        dej        fdZ	 	 	 ddZed             Zd Z xZS )SamProcessora  
    Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a
    single processor.

    [`SamProcessor`] offers all the functionalities of [`SamImageProcessor`]. See the docstring of
    [`~SamImageProcessor.__call__`] for more information.

    Args:
        image_processor (`SamImageProcessor`):
            An instance of [`SamImageProcessor`]. The image processor is a required input.
    image_processorSamImageProcessorc                     t                                          |           | j        | _        d| _        | j        j        d         | _        d S )Nilongest_edge)super__init__r   current_processorpoint_pad_valuesizetarget_size)selfr   	__class__s     b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/sam/processing_sam.pyr   zSamProcessor.__init__4   sG    )))!%!5"/4^D    Nreturn_tensorsreturnc                      | j         |f||d|}|d         }	t          |	d          r|	                                }	|                     |||          \  }}}|                     ||	||||          }|S )z
        This method uses [`SamImageProcessor.__call__`] method to prepare image(s) for the model. It also prepares 2D
        points and bounding boxes for the model if they are provided.
        )segmentation_mapsr   original_sizesnumpy)input_pointsinput_labelsinput_boxes)r"   r#   r$   r   )r   hasattrr!   _check_and_preprocess_points_normalize_and_convert)
r   imagesr   r"   r#   r$   r   kwargsencoding_image_processorr    s
             r   __call__zSamProcessor.__call__:   s     $84#7$
/)$
 $
 	$
 $
  22BC>7++ 	4+1133N262S2S%%# 3T 3
 3
/lK $(#>#>$%%#) $? $
 $
  ('r   ptc                 4    t                    t                    k    r fdD             n fdt                    D             t          fdD                       s|                     |          \  }t	          j                  |t	          j        |          }|`t                    t          |          k    r fd|D             }n fdt          |          D             }t	          j        |          }||dk    rDt          j        |          }t          |j                  dk    r|	                    d          n|}nI|d	k    rCt          j        |          }t          |j                  dk    rt          j        |d          n|}|                    d
|i           |dk    rDt          j                  t          j                  dk    r	                    d          nnI|d	k    rCt          j                  t          j                  dk    rt          j        d          n|                    di           ||dk    rDt          j        |          }t          |j                  dk    r|	                    d          n|}nI|d	k    rCt          j        |          }t          |j                  dk    rt          j        |d          n|}|                    d|i           |S )Nc                 T    g | ]$}                     j        |d                    %S r   _normalize_coordinatesr   ).0pointr    r   s     r   
<listcomp>z7SamProcessor._normalize_and_convert.<locals>.<listcomp>q   sA          `eD//0@%XYIZ[[     r   c                 N    g | ]!\  }}                     j        ||          "S  r0   )r2   r3   original_sizer   s      r   r4   z7SamProcessor._normalize_and_convert.<locals>.<listcomp>u   sB          ,} //0@%WW     r   c              3   D   K   | ]}|j         d          j         k    V  dS )r   Nshape)r2   r3   r"   s     r   	<genexpr>z6SamProcessor._normalize_and_convert.<locals>.<genexpr>z   s1      VVu{l1o&;;VVVVVVr   c                 X    g | ]&}                     j        |d          d          'S )r   Tis_bounding_boxr0   )r2   boxr    r   s     r   r4   z7SamProcessor._normalize_and_convert.<locals>.<listcomp>   sJ        //0@#~VWGXjn/oo  r   c                 R    g | ]#\  }}                     j        ||d           $S )Tr=   r0   )r2   r?   r7   r   s      r   r4   z7SamProcessor._normalize_and_convert.<locals>.<listcomp>   sH       *] //0@#}fj/kk  r   r,   r      tfr$      r"   r#   )lenzipall_pad_points_and_labelsnparraytorch
from_numpyr:   	unsqueezerB   convert_to_tensorexpand_dimsupdate)r   r*   r    r"   r#   r$   r   s   ` ``   r   r'   z#SamProcessor._normalize_and_convertf   s    #>""c,&7&777         iu            03L.0Q0Q     
 VVVVVVVVV i+151L1L\[g1h1h.L,8L11L#8L11L">""c+&6&666    *  
   .1+~.N.N   (;//K"%%#.{;;:=k>O:P:PTU:U:Uk33A666[f4'' 2;??@CKDU@V@VZ[@[@[bn[!<<<al$++]K,HIII#%%$/==<?@R<S<SWX<X<X|55a888^j4''!3LAABElFXBYBY]^B^B^r~lA>>>dp$++^\,JKKK#%%$/==<?@R<S<SWX<X<X|55a888^j4''!3LAABElFXBYBY]^B^B^r~lA>>>dp$++^\,JKKK''r   c           	         t          d |D                       }g }t          |          D ]\  }}|j        d         |k    rft          j        |t          j        ||j        d         z
  df          | j        z   gd          }t          j        ||         | j        g          ||<   |                    |           |}||fS )zh
        The method pads the 2D points and labels to the maximum number of points in the batch.
        c                 (    g | ]}|j         d          S r/   r9   )r2   r3   s     r   r4   z7SamProcessor._pad_points_and_labels.<locals>.<listcomp>   s    !K!K!KU%+a.!K!K!Kr   r      )axis)max	enumerater:   rH   concatenatezerosr   append)r   r"   r#   expected_nb_pointsprocessed_input_pointsir3   s          r   rG   z#SamProcessor._pad_points_and_labels   s     !!K!Kl!K!K!KLL!#!,// 	1 	1HAu{1~!333BH&85;q>&I1%MNNQUQeefmn   #%)LOd>R=S"T"TQ"))%0000-\))r   Fr   coordsc                 B   |\  }}| j                             ||          \  }}t          |                              t                    }|r|                    ddd          }|d         ||z  z  |d<   |d         ||z  z  |d<   |r|                    dd          }|S )z~
        Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H, W) format.
        )r   rR   ).r   ).rA   rC   )r   _get_preprocess_shaper   astypefloatreshape)	r   r   r\   r7   r>   old_hold_wnew_hnew_ws	            r   r1   z#SamProcessor._normalize_coordinates   s     %u+AA-^iAjju&!!((// 	.^^B1--F55=9v55=9v 	+^^B**Fr   c                 r   |t          |d          r&|                                                                }t          |t                    rt          |d         t                    st          d          d |D             }nd}|t          |d          r&|                                                                }t          |t                    rt          |d         t                    st          d          d |D             }nd}|t          |d          r&|                                                                }t          |t                    r<t          |d         t                    r!t          |d         d         t                    st          d          d	 |D             }nd}|||fS )
a8  
        Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they
        are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`,
        it is converted to a `numpy.ndarray` and then to a `list`.
        Nr!   r   z7Input points must be a list of list of floating points.c                 6    g | ]}t          j        |          S r6   rH   rI   )r2   input_points     r   r4   z=SamProcessor._check_and_preprocess_points.<locals>.<listcomp>   s"    RRRkBH[11RRRr   z-Input labels must be a list of list integers.c                 6    g | ]}t          j        |          S r6   ri   )r2   labels     r   r4   z=SamProcessor._check_and_preprocess_points.<locals>.<listcomp>   s     FFFBHUOOFFFr   z>Input boxes must be a list of list of list of floating points.c                 p    g | ]3}t          j        |                              t           j                  4S r6   )rH   rI   r`   float32)r2   r?   s     r   r4   z=SamProcessor._check_and_preprocess_points.<locals>.<listcomp>   s0    SSS28C==//
;;SSSr   )r%   r!   tolist
isinstancelist
ValueError)r   r"   r#   r$   s       r   r&   z)SamProcessor._check_and_preprocess_points   s    #|W-- =+1133::<<lD11 \LQROUY9Z9Z \ !Z[[[RR\RRRLLL#|W-- =+1133::<<lD11 RLQROUY9Z9Z R !PQQQFFFFFLLL"{G,, ;)//1188:: {D11c!+a.$77c "+a."3T::c
 !!abbbSS{SSSKKK\;66r   c                 h    | j         j        }t          t                              |                    S N)r   model_input_namesrq   dictfromkeys)r   image_processor_input_namess     r   ru   zSamProcessor.model_input_names  s)    &*&:&L#DMM"=>>???r   c                 &     | j         j        |i |S rt   )r   post_process_masks)r   argsr)   s      r   rz   zSamProcessor.post_process_masks
  s    6t#6GGGGr   )NNNNNN)NNNr,   )F)NNN)__name__
__module____qualname____doc__
attributesimage_processor_classr   r   r   strr	   r   r+   r'   rG   intrH   ndarrayr1   r&   propertyru   rz   __classcell__)r   s   @r   r   r   $   sm       
 
 $$J/E E E E E ;?*( *( !sJ!78*( 
*( *( *( *(` I( I( I( I(V* * *" TY (*
	   . 	-7 -7 -7 -7^ @ @ X@H H H H H H Hr   r   )r   copyr   typingr   r   r!   rH   processing_utilsr   tokenization_utils_baser   utilsr	   r
   r   rJ   
tensorflowrB   r   r6   r   r   <module>r      s	          " " " " " " " "     . . . . . . 4 4 4 4 4 4 D D D D D D D D D D  LLL? gH gH gH gH gH> gH gH gH gH gHr   