o
    i:                     @   s   d Z ddl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 dd	lmZ e rQddlZe e!Z"d
d Z#dd Z$eddG dd deZ%dgZ&dS )z#Image processor class for ImageGPT.    )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logging)requiresc                 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   axisr      )Tnpsumsquarematmul)aba2b2abd r(   j/home/ubuntu/.local/lib/python3.10/site-packages/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   argmin)xclustersr'   r(   r(   r)   color_quantize6   s   
r0   )vision)backendsc                       s  e Zd ZdZdgZdddejddfdeee	e	e
  ejf  dedeeee
f  ded	ed
eddf fd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dZ		ddejdeeeef  deeeef  dejfddZe dddddddejdf	dedee deeee
f  dee d	ee d
ee deee	e	e
  ejf  deeeef  deeeef  deeeef  dejjfddZ f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 overridden 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`.
    pixel_valuesNTr/   	do_resizesizeresampledo_normalizedo_color_quantizereturnc                    sj   t  jdi | |d ur|nddd}t|}|d ur!t|nd | _|| _|| _|| _|| _	|| _
d S )N   )heightwidthr(   )super__init__r   r   arrayr/   r5   r6   r7   r8   r9   )selfr/   r5   r6   r7   r8   r9   kwargs	__class__r(   r)   r?   W   s   
zImageGPTImageProcessor.__init__imagedata_formatinput_data_formatc                 K   sT   t |}d|vsd|v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.
        r<   r=   zFThe `size` dictionary must contain the keys `height` and `width`. Got )r6   r7   rF   rG   )r   
ValueErrorkeysr	   )rA   rE   r6   r7   rF   rG   rB   output_sizer(   r(   r)   r	   m   s   #zImageGPTImageProcessor.resizec                 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?)rE   scalerF   rG   r   )r   )rA   rE   rF   rG   r(   r(   r)   	normalize   s   z ImageGPTImageProcessor.normalizeimagesreturn_tensorsc                    s  |dur|nj }durnjtdurnj|dur%|nj}|dur.|nj}|dur7|nj}t|}t	|}t
|sKtdt|d |r\|du r\tddd |D }|rpt|d rptd du rzt|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|}d|i}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.)r5   r6   r7   z8Clusters must be specified if do_color_quantize is True.c                 S   s   g | ]}t |qS r(   )r   .0rE   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 ))rE   r6   r7   rG   )r	   rO   )rG   r7   rA   r6   r(   r)   rQ     s    c                    s   g | ]	}j | d qS ))rE   rG   )rL   rO   )rG   rA   r(   r)   rQ         c                    s   g | ]	}t |tj qS r(   )r
   r   LASTrO   )rG   r(   r)   rQ     rR   r+   	input_idsc                    s   g | ]}t | qS r(   )r
   rO   )rF   rG   r(   r)   rQ   (  s    r4   )datatensor_type)r5   r6   r   r7   r8   r9   r/   r   r@   r   r   rH   r   r   loggerwarning_oncer   r0   r,   shapelistr   )rA   rM   r5   r6   r7   r8   r9   r/   rN   rF   rG   
batch_sizerU   r(   )rF   rG   r7   rA   r6   r)   
preprocess   sX   6



z!ImageGPTImageProcessor.preprocessc                    s^   t   }|dd urt|d tjr|d  |d< g d}|D ]
}||v r,d ||< q"|S )Nr/   )
image_mean	image_stdrescale_factor
do_rescale)r>   to_dictget
isinstancer   ndarraytolist)rA   outputmissing_keyskeyrC   r(   r)   ra   ,  s   
zImageGPTImageProcessor.to_dict)NN)__name__
__module____qualname____doc__model_input_namesr   BILINEARr   r   rZ   intr   rd   booldictstrr?   r   r	   rL   r   FIRSTr   r   PILImager\   ra   __classcell__r(   r(   rC   r)   r3   <   s    


3
	
yr3   )'rl   typingr   r   numpyr   image_processing_utilsr   r   r   image_transformsr   r	   r
   image_utilsr   r   r   r   r   r   r   r   r   utilsr   r   r   r   utils.import_utilsr   rt   
get_loggerri   rW   r*   r0   r3   __all__r(   r(   r(   r)   <module>   s"   ,
	 
~