U
    9%e`*                     @   s   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 rbddlZe rpddlZG d	d
 d
e	ZdS )z
Processor class for SAM.
    )deepcopy)OptionalUnionN   )ProcessorMixin)BatchEncoding)
TensorTypeis_tf_availableis_torch_availablec                       s   e Zd ZdZdgZdZ fddZdeee	e
f  eddd	ZdddZdd ZdeejejdddZdddZedd Zdd Z  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_processorZSamImageProcessorc                    s,   t  | | j| _d| _| jjd | _d S )Nilongest_edge)super__init__r   Zcurrent_processorpoint_pad_valuesizetarget_size)selfr   	__class__ e/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/sam/processing_sam.pyr   2   s    zSamProcessor.__init__N)return_tensorsreturnc           	      K   s`   | j |fd|i|}|d }t|dr0| }| j|||d\}}}| j||||||d}|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.
        r   original_sizesnumpy)input_pointsinput_labelsinput_boxes)r   r   r   r   )r   hasattrr   _check_and_preprocess_points_normalize_and_convert)	r   Zimagesr   r   r   r   kwargsencoding_image_processorr   r   r   r   __call__8   s0    
	zSamProcessor.__call__ptc                    sd   d k	r~t t  kr.fdd D  nfddt D  t fdd D st|d k	rt |\ }t  |d k	rt|}|d k	rt t |krfdd|D }nfddt|D }t|}|d k	r`|dkrt|}t |jd	kr|	d
n|}n4|dkrRt
|}t |jd	krNt
|d
n|}|d|i  d k	r|dkrt  t  jdkr 	d
n  n4|dkrt
  t  jdkrt
 d
n  |d i |d k	r`|dkrt|}t |jd	kr|	d
n|}n4|dkrRt
|}t |jd	krNt
|d
n|}|d|i |S )Nc                    s    g | ]} j| d  qS r   _normalize_coordinatesr   .0pointr   r   r   r   
<listcomp>m   s    z7SamProcessor._normalize_and_convert.<locals>.<listcomp>c                    s    g | ]\}}   j||qS r   r'   )r*   r+   original_sizer   r   r   r-   q   s   c                 3   s   | ]}|j  d  j kV  qdS )r   Nshaper)   )r   r   r   	<genexpr>v   s     z6SamProcessor._normalize_and_convert.<locals>.<genexpr>c                    s$   g | ]}j j| d  ddqS )r   Tis_bounding_boxr'   r*   boxr,   r   r   r-      s   c                    s$   g | ]\}} j  j||d dqS )Tr3   r'   )r*   r6   r.   r/   r   r   r-      s   r%   r      tfr      r   r   )lenzipall_pad_points_and_labelsnparraytorchZ
from_numpyr1   Z	unsqueezer8   Zconvert_to_tensorZexpand_dimsupdate)r   r#   r   r   r   r   r   r   )r   r   r   r   r!   b   s`    	







 

 


 

 


 

 z#SamProcessor._normalize_and_convertc                 C   s   t dd |D }g }t|D ]d\}}|jd |krxtj|t||jd  df| j gdd}t|| | jg||< || q|}||fS )zh
        The method pads the 2D points and labels to the maximum number of points in the batch.
        c                 S   s   g | ]}|j d  qS r&   r0   r)   r   r   r   r-      s     z7SamProcessor._pad_points_and_labels.<locals>.<listcomp>r      )Zaxis)max	enumerater1   r>   ZconcatenateZzerosr   append)r   r   r   Zexpected_nb_pointsZprocessed_input_pointsir+   r   r   r   r=      s      z#SamProcessor._pad_points_and_labelsF)r   coordsr   c           	      C   sx   |\}}| j j||d\}}t|t}|r<|ddd}|d ||  |d< |d ||  |d< |rt|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   rB   ).r   ).r7   r9   )r   Z_get_preprocess_shaper   astypefloatZreshape)	r   r   rG   r.   r4   Zold_hZold_wZnew_hZnew_wr   r   r   r(      s    z#SamProcessor._normalize_coordinatesc                 C   s  |dk	rNt |dr|  }t|tr6t|d ts>tddd |D }nd}|dk	rt |drp|  }t|trt|d tstddd |D }nd}|dk	rt |dr|  }t|trt|d trt|d d tstd	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                 S   s   g | ]}t |qS r   r>   r?   )r*   Zinput_pointr   r   r   r-      s     z=SamProcessor._check_and_preprocess_points.<locals>.<listcomp>z-Input labels must be a list of list integers.c                 S   s   g | ]}t |qS r   rK   )r*   labelr   r   r   r-      s     z>Input boxes must be a list of list of list of floating points.c                 S   s   g | ]}t |t jqS r   )r>   r?   rI   Zfloat32r5   r   r   r   r-      s     )r   r   tolist
isinstancelist
ValueError)r   r   r   r   r   r   r   r       s6    



z)SamProcessor._check_and_preprocess_pointsc                 C   s   | j j}tt|S N)r   model_input_namesrO   dictfromkeys)r   Zimage_processor_input_namesr   r   r   rR     s    zSamProcessor.model_input_namesc                 O   s   | j j||S rQ   )r   post_process_masks)r   argsr"   r   r   r   rU     s    zSamProcessor.post_process_masks)NNNNN)NNNr%   )F)NNN)__name__
__module____qualname____doc__
attributesZimage_processor_classr   r   r   strr   r   r$   r!   r=   intr>   Zndarrayr(   r    propertyrR   rU   __classcell__r   r   r   r   r   #   s@        .    
K     
/
r   )rZ   copyr   typingr   r   r   r>   Zprocessing_utilsr   Ztokenization_utils_baser   utilsr   r	   r
   r@   Z
tensorflowr8   r   r   r   r   r   <module>   s   