U
    4Af7                     @   s   d Z ddlmZmZmZmZ ddlZddlm	Z	m
Z
mZ ddl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 ddlmZmZmZmZ e rddlZe e!Z"d	d
 Z#dd Z$G dd de	Z%dS )z#Image processor class for ImageGPT.    )DictListOptionalUnionN   )BaseImageProcessorBatchFeatureget_size_dict)rescaleresizeto_channel_dimension_format)	ChannelDimension
ImageInputPILImageResamplinginfer_channel_dimension_formatis_scaled_imagemake_list_of_imagesto_numpy_arrayvalid_imagesvalidate_preprocess_arguments)
TensorTypefilter_out_non_signature_kwargsis_vision_availableloggingc                 C   sf   |j }tjt| dd}tjt|dd}t| |}|d d d f d|  |d d d f  }|S )N   Zaxisr      )TnpsumZsquarematmul)abZa2Zb2abd r%   Z/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/imagegpt/image_processing_imagegpt.pysquared_euclidean_distance,   s    (r'   c                 C   s$   |  dd} t| |}tj|ddS )Nr   r   r   )reshaper'   r   Zargmin)xclustersr$   r%   r%   r&   color_quantize5   s    
r,   c                       sf  e Zd ZdZdgZdddejddfeee	e	e
  ejf  eeee
f eeedd fddZejddfejeee
f eeeeef  eeeef  ejdd	d
Zdejeeeef  eeeef  ejdddZe dddddddejdf	eeeee
f eeee eee	e	e
  ejf  eeeef  eeeef  eeeef  ejjdddZ  ZS )ImageGPTImageProcessora  
    Constructs a ImageGPT image processor. This image processor can be used to resize images to a smaller resolution
    (such as 32x32 or 64x64), normalize them and finally color quantize them to obtain sequences of "pixel values"
    (color clusters).

    Args:
        clusters (`np.ndarray` or `List[List[int]]`, *optional*):
            The color clusters to use, of shape `(n_clusters, 3)` when color quantizing. Can be overriden by `clusters`
            in `preprocess`.
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image's dimensions to `(size["height"], size["width"])`. Can be overridden by
            `do_resize` in `preprocess`.
        size (`Dict[str, int]` *optional*, defaults to `{"height": 256, "width": 256}`):
            Size of the image after resizing. Can be overridden by `size` in `preprocess`.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image pixel value to between [-1, 1]. Can be overridden by `do_normalize` in
            `preprocess`.
        do_color_quantize (`bool`, *optional*, defaults to `True`):
            Whether to color quantize the image. Can be overridden by `do_color_quantize` in `preprocess`.
    Zpixel_valuesNT)r+   	do_resizesizeresampledo_normalizedo_color_quantizereturnc                    sf   t  jf | |d k	r|nddd}t|}|d k	r>t|nd | _|| _|| _|| _|| _	|| _
d S )N   )heightwidth)super__init__r	   r   arrayr+   r.   r/   r0   r1   r2   )selfr+   r.   r/   r0   r1   r2   kwargs	__class__r%   r&   r8   U   s    zImageGPTImageProcessor.__init__)imager/   r0   data_formatinput_data_formatr3   c                 K   sT   t |}d|ksd|kr*td|  |d |d f}t|f||||d|S )a  
        Resize an image to `(size["height"], size["width"])`.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
                `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
            data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the output image. If unset, the channel dimension format of the input
                image is used. 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.
            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.

        Returns:
            `np.ndarray`: The resized image.
        r5   r6   zFThe `size` dictionary must contain the keys `height` and `width`. Got )r/   r0   r?   r@   )r	   
ValueErrorkeysr   )r:   r>   r/   r0   r?   r@   r;   Zoutput_sizer%   r%   r&   r   k   s    #zImageGPTImageProcessor.resize)r>   r?   r@   r3   c                 C   s   t |d||d}|d }|S )a  
        Normalizes an images' pixel values to between [-1, 1].

        Args:
            image (`np.ndarray`):
                Image to normalize.
            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.
        g?)r>   Zscaler?   r@   r   )r
   )r:   r>   r?   r@   r%   r%   r&   	normalize   s    z ImageGPTImageProcessor.normalize)imagesr.   r/   r0   r1   r2   r+   return_tensorsr?   r@   r3   c                    s  |dk	r|nj }dk	rnjtdk	r8nj|dk	rJ|nj}|dk	r\|nj}|dk	rn|nj}t|}t	|}t
|stdt|d |r|dkrtddd |D }t|d r|rtd dkrt|d |rfd	d|D }|r,fd
d|D }|rfdd|D }t|}t|||jdd }|jd }||d}t|}n fdd|D }d|i}t||dS )aX  
        Preprocess an image or batch of images.

        Args:
            images (`ImageInput`):
                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
                passing in images with pixel values between 0 and 1, set `do_normalize=False`.
            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.
            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_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image
            do_color_quantize (`bool`, *optional*, defaults to `self.do_color_quantize`):
                Whether to color quantize the image.
            clusters (`np.ndarray` or `List[List[int]]`, *optional*, defaults to `self.clusters`):
                Clusters used to quantize the image of shape `(n_clusters, 3)`. Only has an effect if
                `do_color_quantize` is set to `True`.
            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:
                    - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                    - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                Only has an effect if `do_color_quantize` is set to `False`.
            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.
        NzkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)r.   r/   r0   z8Clusters must be specified if do_color_quantize is True.c                 S   s   g | ]}t |qS r%   )r   .0r>   r%   r%   r&   
<listcomp>  s     z5ImageGPTImageProcessor.preprocess.<locals>.<listcomp>r   zIt looks like you are trying to rescale already rescaled images. If you wish to do this, make sure to set `do_normalize` to `False` and that pixel values are between [-1, 1].c                    s   g | ]}j | d qS ))r>   r/   r0   r@   )r   rF   )r@   r0   r:   r/   r%   r&   rH     s   c                    s   g | ]}j | d qS ))r>   r@   )rC   rF   )r@   r:   r%   r&   rH     s     c                    s   g | ]}t |tj qS r%   )r   r   ZLASTrF   )r@   r%   r&   rH     s     r(   c                    s   g | ]}t | d qS ))Zinput_channel_dim)r   rF   )r?   r@   r%   r&   rH   %  s   Z	input_ids)dataZtensor_type)r.   r/   r	   r0   r1   r2   r+   r   r9   r   r   rA   r   r   loggerZwarning_oncer   r,   r)   shapelistr   )r:   rD   r.   r/   r0   r1   r2   r+   rE   r?   r@   Z
batch_sizerI   r%   )r?   r@   r0   r:   r/   r&   
preprocess   sZ    6



z!ImageGPTImageProcessor.preprocess)NN)__name__
__module____qualname____doc__Zmodel_input_namesr   ZBILINEARr   r   r   intr   Zndarrayboolr   strr8   r   r   rC   r   ZFIRSTr   r   PILZImagerM   __classcell__r%   r%   r<   r&   r-   ;   sv   

3  
r-   )&rQ   typingr   r   r   r   Znumpyr   Zimage_processing_utilsr   r   r	   Zimage_transformsr
   r   r   Zimage_utilsr   r   r   r   r   r   r   r   r   utilsr   r   r   r   rU   Z
get_loggerrN   rJ   r'   r,   r-   r%   r%   r%   r&   <module>   s   ,
	