
    sg=k              
          d dl mZmZmZmZmZmZmZ d dlZ	ddl
mZmZ ddlmZmZmZmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZ ddlm Z m!Z!m"Z"  e"jF                  e$      Z% e!       r
d dl&Z&d dl&m'Z' d	ee(e(f   fd
Z)ded	eee	jT                        fdZ+dee   d	ee   fdZ,	 ddeee	jT                        deee-ef      d	ee(   fdZ.	 dde	jT                  dee(e(f   deee-ef      d	e	jT                  fdZ/ded	efdZ0 G d de      Z1y)    )AnyDictIterableListOptionalTupleUnionN   )BaseImageProcessorBatchFeature)PaddingModepadresizeto_channel_dimension_format)IMAGENET_STANDARD_MEANIMAGENET_STANDARD_STDChannelDimension
ImageInputPILImageResamplingget_image_sizeinfer_channel_dimension_formatis_scaled_imageis_valid_imageto_numpy_arrayvalid_imagesvalidate_preprocess_arguments)
TensorTypeis_vision_availablelogging)Imagereturnc                     t        | |      \  }}|d   }|d   }||z  }||k\  r||kD  r|}t        ||z        }n||kD  r||kD  r|}t        ||z        }t        ||      }t        ||      }||fS )a  
    Get the output size of the image after resizing given a dictionary specifying the max and min sizes.

    Args:
        image (`np.ndarray`):
            Image to resize.
        size (`Dict[str, int]`):
            Size of the output image containing the keys "shortest_edge" and "longest_edge".
        input_data_format (`ChannelDimension` or `str`):
            The channel dimension format of the input image.

    Returns:
        The output size of the image after resizing.
    channel_dimshortest_edgelongest_edge)r   intmax)imagesizeinput_data_formatheightwidthmin_lenmax_lenaspect_ratios           i/var/www/html/venv/lib/python3.12/site-packages/transformers/models/idefics2/image_processing_idefics2.pyget_resize_output_image_sizer2   0   s     #56GHMFE?#G>"G6>L57?U\)*	%FW,F\)*!FwE5=    imagesc                 l   t        |       r| gg} | S t        | t        t        f      r!t	        |       dkD  rt        | d         r| g} | S t        | t        t        f      rLt	        |       dkD  r>t        | d   t        t        f      r%t	        | d         dkD  rt        | d   d         r	 | S t        d      )z
    Convert a single image or a list of images to a list of numpy arrays.

    Args:
        images (`ImageInput`):
            A single image or a list of images.

    Returns:
        A list of numpy arrays.
    r   z]Invalid input type. Must be a single image, a list of images, or a list of batches of images.)r   
isinstancelisttuplelen
ValueError)r4   s    r1   make_list_of_imagesr;   P   s     f(" M 
FT5M	*s6{Q>RXYZR[C\ M 	6D%=)K!Ovay4-0q	NQ6!9Q<(
 M k
 	
r3   valuesc                 J    t        |  D cg c]  }t        |       c}S c c}w )zO
    Return the maximum value across all indices of an iterable of values.
    )zipr(   )r<   values_is     r1   max_across_indicesr@   r   s      +.v,7hCM777s    images_listr+   c                     |t        | d   d         }g }| D ]%  }|D ]  }|j                  t        ||               ' t        |      \  }}||fS )zH
    Get the maximum height and width across all images in a batch.
    r   r#   )r   appendr   r@   )rA   r+   image_sizesr4   r)   
max_height	max_widths          r1   get_max_height_widthrG   y   sw      :;q>!;LMK U 	UE~eARST	UU /{;J		""r3   r)   output_sizec                     t        | |      \  }}t        j                  |t        j                        }d|d|d|f<   |S )a  
    Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.

    Args:
        image (`np.ndarray`):
            Image to make the pixel mask for.
        output_size (`Tuple[int, int]`):
            Output size of the mask.
    r#   dtype   N)r   npzerosint64)r)   rH   r+   input_heightinput_widthmasks         r1   make_pixel_maskrS      sF     !/uBS TL+88Krxx0D()D,	$%Kr3   c                 &   t        | t        j                  j                        s| S | j                  dk(  r| S | j	                  d      }t        j
                  d|j                  d      }t        j                  ||      }|j	                  d      }|S )z
    Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
    as is.
    Args:
        image (Image):
            The image to convert.
    RGBRGBA)   rW   rW   )r6   PILr    modeconvertnewr*   alpha_composite)r)   
image_rgba
backgroundr\   s       r1   convert_to_rgbr_      sz     eSYY__- zzUv&J6:??ODJ++J
CO%--e4Or3   c                        e Zd ZdZdgZdddej                  dddddddfdeded	ee	e
f   d
ededededeeeee   f      deeeee   f      dededdf fdZej                  ddfdej"                  d	ee	e
f   d
edeee	ef      deee	ef      dej"                  fdZ	 	 	 d'dej"                  dee
e
f   deeee   f   dee   deee	ef      dej"                  fdZ	 	 	 	 	 d(deej"                     deeee   f   dedeee	ef      dee   deee	ef      defdZ	 d)dej"                  d e
d!e
d"e
d#e
deee	ef      dej"                  fd$Z	 d)dej"                  deee	ef      fd%Zdddddddddddddej8                  fdedee   dee   d	eee	e
f      d
edee   dee   dee   deeeee   f      deeeee   f      dee   dee   deee	ef      dee   dee   fd&Z xZS )*Idefics2ImageProcessoraH  
    Constructs a Idefics image processor.

    Args:
        do_convert_rgb (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA.
            Only has an effect if the input image is in the PIL format.
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image. The longest edge of the image is resized to  be <= `size["longest_edge"]`, with the
            shortest edge resized to keep the input aspect ratio, with a minimum size of `size["shortest_edge"]`.
        size (`Dict`, *optional*):
            Controls the size of the output image. This is a dictionary containing the keys "shortest_edge" and "longest_edge".
        resample (`Resampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use when resizing the image.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Whether to rescale the image. If set to `True`, the image is rescaled to have pixel values between 0 and 1.
        rescale_factor (`float`, *optional*, defaults to `1/255`):
            Rescale factor to rescale the image by if `do_rescale` is set to `True`.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image. If set to `True`, the image is normalized to have a mean of `image_mean` and
            a standard deviation of `image_std`.
        image_mean (`float` or `List[float]`, *optional*, defaults to `IDEFICS_STANDARD_MEAN`):
            Mean to use if normalizing the image. This is a float or list of floats the length of the number of
            channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
            overridden by the `image_mean` parameter in the `preprocess` method.
        image_std (`float` or `List[float]`, *optional*, defaults to `IDEFICS_STANDARD_STD`):
            Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
            number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
            Can be overridden by the `image_std` parameter in the `preprocess` method.
        do_pad (`bool`, *optional*, defaults to `True`):
            Whether or not to pad the images to the largest height and width in the batch and number of images per
            sample in the batch, such that the returned tensor is of shape (batch_size, max_num_images, num_channels, max_height, max_width).
        do_image_splitting (`bool`, *optional*, defaults to `False`):
            Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That
            strategy was first introduced in https://arxiv.org/abs/2311.06607.
    pixel_valuesTNgp?Fdo_convert_rgb	do_resizer*   resample
do_rescalerescale_factordo_normalize
image_mean	image_stddo_paddo_image_splittingr!   c                     t        |   di | || _        || _        ||nddd| _        || _        || _        || _        || _        ||nt        | _
        |	|	nt        | _        |
| _        || _        y )Niz  i  )r%   r&    )super__init__rc   rd   r*   re   rf   rg   rh   r   ri   r   rj   rk   rl   )selfrc   rd   r*   re   rf   rg   rh   ri   rj   rk   rl   kwargs	__class__s                r1   rp   zIdefics2ImageProcessor.__init__   s     	"6"," ,DCY\2]	 $,((2(>*DZ&/&;AV"4r3   r)   data_formatr+   c                     d|v rd|v rt        |||      }nd|v rd|v r|d   |d   f}nt        d      t        ||f|||d|S )aZ  
        Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
        resized to keep the input aspect ratio.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Size of the output image.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
                Resampling filter to use when resiizing the image.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the image. If not provided, it will be the same as the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        r%   r&   r,   r-   z_size must be a dictionary with keys 'shortest_edge' and 'longest_edge' or 'height' and 'width'.)re   rt   r+   )r2   r:   r   )rq   r)   r*   re   rt   r+   rr   s          r1   r   zIdefics2ImageProcessor.resize   s{    2 d"~'=/t=NOD'T/NDM2Dq  4
"*Wh
lr
 	
r3   rH   constant_valuesc                     t        ||      \  }}|\  }}	||z
  }
|	|z
  }d|
fd|ff}t        ||t        j                  |||      }|S )z<
        Pad an image with zeros to the given size.
        r#   r   )rY   rv   rt   r+   )r   r   r   CONSTANT)rq   r)   rH   rv   rt   r+   rP   rQ   output_heightoutput_width
pad_bottom	pad_rightpaddingpadded_images                 r1   
_pad_imagez!Idefics2ImageProcessor._pad_image   sp     %35FW$X!k&1#|"\1
 ;.	z?Q	N3%%+#/
 r3   r4   return_pixel_maskreturn_tensorsc           
      j   t        ||      }t        |      }t        d |D              }	|t        |d   d         n|}||n|}d }
t	        |      D cg c]"  }t	        |	      D cg c]  } |
||       c}$ }}t	        |      D cg c].  }t	        |	      D cg c]  }t        j                  |       c}0 }}t	        |      D ]H  }t        ||         D ]5  \  }}| j                  |||||      ||   |<   t        |||      ||   |<   7 J |r|nd}||fS c c}w c c}w c c}w c c}w )ay  
        For a list of images, for each images, pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width.
        For each sample in the batch, pads the sample with empty images to the max_number of images per sample in the batch. Optionally returns a pixel mask.

        Args:
            images (`np.ndarray`):
                List of list of images to pad. Pads to the largest height and width in the batch.
            constant_values (`float` or `Iterable[float]`, *optional*):
                The value to use for the padding if `mode` is `"constant"`.
            return_pixel_mask (`bool`, *optional*, defaults to `True`):
                Whether to return a pixel mask.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:
                    - Unset: Return a list of `np.ndarray`.
                    - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                    - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                    - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                    - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the image. If not provided, it will be the same as the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        )r+   c              3   2   K   | ]  }t        |        y wN)r9   ).0images_s     r1   	<genexpr>z-Idefics2ImageProcessor.pad.<locals>.<genexpr>^  s     @gS\@s   Nr   c                 
   |t         j                  k(  r)t        j                  dg| t        j                        S |t         j
                  k(  r*t        j                  g | dt        j                        S t        d      )Nr
   rJ   z!Invalid channel dimension format.)r   FIRSTrM   rN   uint8LASTr:   )r*   r+   s     r1   empty_imagez/Idefics2ImageProcessor.pad.<locals>.empty_imaged  sd     $4$:$::xx
T
"((;;"&6&;&;;xx
$

"((;;@AAr3   )rv   rt   r+   )rH   r+   )
rG   r9   r(   r   rangerM   rN   	enumerater   rS   )rq   r4   rv   r   r   rt   r+   pad_size
batch_sizemax_num_imagesr   _padded_images_listpadded_masks	batch_idx
sample_idxr)   s                    r1   r   zIdefics2ImageProcessor.pad;  sz   @ (BST[
@@@<M<U*6!9Q<8[l 	 ,7+>'K	B Z__iYj
TU~9NOA[;/O
 
 V[[eUfgPQU>5JK(+Kggz* 	I%.vi/@%A 
!
E<@OO$3 +&7 =L ="9-j9 7FxCT7Y'
3
	 (9|d!<//% P
 Lgs0   D&(D!
8D&D0D+
:D0!D&+D0imw1h1w2h2c                     |t         j                  k(  r|d d ||||f   S |t         j                  k(  r|||||d d f   S y r   )r   r   r   )rq   r   r   r   r   r   r+   s          r1   _cropzIdefics2ImageProcessor._crop  sY      0 6 66aB2o&&"2"7"77beRUAo&& 8r3   c                     t        ||      \  }}|dz  }|dz  }| j                  |dd|||      | j                  ||d|||      | j                  |d||||      | j                  ||||||      |gS )a"  
        Split an image into 4 equal sub-images, and the concatenate that sequence with the original image.
        That means that a single image becomes a sequence of 5 images.
        This is a "trick" to spend more compute on each image with no changes in the vision encoder.

        Args:
            image (`np.ndarray`):
                Images to split.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
           r   )r   r   )rq   r)   r+   r,   r-   	mid_width
mid_heights          r1   split_imagez"Idefics2ImageProcessor.split_image  s      'u.?@QJ	q[
JJuaIz;LMJJuiE:?PQJJuaY@QRJJuiUFDUV
 	
r3   c                 R   ||n| j                   }||n| j                  }||n| j                  }||n| j                  }||n| j                  }||n| j
                  }|	|	n| j                  }	|
|
n| j                  }
||n| j                  }||n| j                  }||n| j                  }t        |      }t        |d         st        d      t        ||||	|
|||       |r(|D cg c]  }|D cg c]  }t        |       c} }}}|D cg c]  }|D cg c]  }t!        |       c} }}}t#        |d   d         r|rt$        j'                  d       |t)        |d   d         }|rFg }|D ]=  }g }|D ]#  }|j+                  | j-                  ||             % |j/                  |       ? |}|r2|D cg c]%  }|D cg c]  }| j1                  ||||       c}' }}}|r1|D cg c]$  }|D cg c]  }| j3                  |||       c}& }}}|r2|D cg c]%  }|D cg c]  }| j5                  ||	|
|       c}' }}}d}|r| j7                  |d	||
      \  }}|+|D cg c]  }|D cg c]  }t9        |||       c}  }}}d|rt;        j<                  |      n|i}||rt;        j<                  |      n||d<   t?        ||      S c c}w c c}}w c c}w c c}}w c c}w c c}}w c c}w c c}}w c c}w c c}}w c c}w c c}}w )a  
        Preprocess a batch of images.

        Args:
            images (`ImageInput`):
                A list of images to preprocess.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to convert the image to RGB.
            do_resize (`bool`, *optional*, defaults to `self.do_resize`):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to `self.size`):
                Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
                the longest edge resized to keep the input aspect ratio.
            resample (`int`, *optional*, defaults to `self.resample`):
                Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
                has an effect if `do_resize` is set to `True`.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image.
            rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to rescale the image by if `do_rescale` is set to `True`.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
                Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
                `True`.
            do_pad (`bool`, *optional*, defaults to `self.do_pad`):
                Whether or not to pad the images to the largest height and width in the batch.
            do_image_splitting (`bool`, *optional*, defaults to `self.do_image_splitting`):
                Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That
                strategy was first introduced in https://arxiv.org/abs/2311.06607.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:
                - Unset: Return a list of `np.ndarray`.
                - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - Unset: Use the channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        Nr   zkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)rf   rg   rh   ri   rj   rd   r*   re   zIt looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.)r)   r*   re   r+   )r)   scaler+   )r)   meanstdr+   T)r   r   r+   )input_channel_dimrb   pixel_attention_mask)datatensor_type) rd   r*   re   rf   rg   rh   ri   rj   rc   rk   rl   r;   r   r:   r   r_   r   r   loggerwarning_oncer   extendr   rC   r   rescale	normalizer   r   rM   arrayr   )rq   r4   rc   rd   r*   re   rf   rg   rh   ri   rj   rk   rl   r   r+   rt   rA   r)   new_images_list
new_imagesr   r   s                         r1   
preprocessz!Idefics2ImageProcessor.preprocess  s   J "+!6IDNN	'tTYY'38#-#9Zt
+9+E4K^K^'3'?|TEVEV#-#9Zt
!*!6IDNN	+9+E4K^K^!-4;;3E3Q/W[WnWn)&1KN+: 
 	&!)%!		
 U`a6vFeN51FaKa R]]v6B%u-B]];q>!,-*s
 $ >{1~a?P Q O% 3
# RE%%d&6&6u>O&PQR&&z2	3
 *K *
  "( KKe$]nKoK   *
  "( LLuNVgLhK   *
  "( NNZYbsNtK   $04tNfw 19 1-K- " *
  "( 0{VghK   5[Q+MS2884H+IYmD'(>BBM Ga C]. s   /	K,8K'
K,	K7 K22K7	LK=)L8	LLL+	L4LL;	L#LL#'K,2K7=LLLL#)r   NN)r   TNNNr   ) __name__
__module____qualname____doc__model_input_namesr   BILINEARboolr   strr'   floatr   r	   r   rp   rM   ndarrayr   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__)rs   s   @r1   ra   ra      sr   #J ((  $#'9'B'B '!:>9=#(55 5 38n	5
 %5 5 5 5 U5$u+#5675 E%e"4565 5 !5 
5@ (:'B'B>BDH#
zz#
 38n#
 %	#

 eC)9$9:;#
 $E#/?*?$@A#
 
#
T :;26DHzz 38_ uhuo56	
 ./ $E#/?*?$@A 
< :;"&;?26DHC0RZZ C0 uhuo56C0  	C0
 !sJ!78C0 ./C0 $E#/?*?$@AC0 
C0X EI'JJ' ' 	'
 ' ' $E#/?*?$@A' 
'" EI
zz
 $E#/?*?$@A
> *.$()-'+%)*.'+:>9=!%-1;?8<2B2H2H!kCkC !kC D>	kC
 tCH~&kC %kC TNkC !kC tnkC U5$u+#567kC E%e"456kC kC %TNkC !sJ!78kC $$45kC  ./!kCr3   ra   r   )2typingr   r   r   r   r   r   r	   numpyrM   image_processing_utilsr   r   image_transformsr   r   r   r   image_utilsr   r   r   r   r   r   r   r   r   r   r   r   utilsr   r   r   
get_loggerr   r   rX   r    r'   r2   r   r;   r@   r   rG   rS   r_   ra   rn   r3   r1   <module>r      se  " E D D  F U U    > = 
		H	% E#s(O @
 tD4D/E D8x} 8c 8 fj#d2::&'#<DU3P`K`Ea<b#	#Y#( rv::$)#s(OHPQVWZ\lWlQmHnZZ&*  ._C/ _Cr3   