o
    Zh|8                     @   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 dd	lm Z  e rUd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.    )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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   Zaxisr      )TnpsumZsquarematmul)abZa2b2abd r'   e/var/www/auris/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   Zargmin)xclustersr&   r'   r'   r(   color_quantize6   s   
r.   )Z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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  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`.
    Z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-   r1   r2   r3   r4   r5   )selfr-   r1   r2   r3   r4   r5   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.
        r8   r9   zFThe `size` dictionary must contain the keys `height` and `width`. Got )r2   r3   rB   rC   )r	   
ValueErrorkeysr   )r=   rA   r2   r3   rB   rC   r>   Z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?)rA   scalerB   rC   r   )r
   )r=   rA   rB   rC   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|}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.)r1   r2   r3   z8Clusters must be specified if do_color_quantize is True.c                 S   s   g | ]}t |qS r'   )r   .0rA   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 ))rA   r2   r3   rC   )r   rJ   )rC   r3   r=   r2   r'   r(   rL     s    c                    s   g | ]	}j | d qS ))rA   rC   )rG   rJ   )rC   r=   r'   r(   rL         c                    s   g | ]	}t |tj qS r'   )r   r   ZLASTrJ   )rC   r'   r(   rL     rM   r*   c                    s   g | ]	}t | d qS ))Zinput_channel_dim)r   rJ   )rB   rC   r'   r(   rL   '  s    Z	input_ids)dataZtensor_type)r1   r2   r	   r3   r4   r5   r-   r   r<   r   r   rD   r   r   loggerZwarning_oncer   r.   r+   shapelistr   )r=   rH   r1   r2   r3   r4   r5   r-   rI   rB   rC   Z
batch_sizerN   r'   )rB   rC   r3   r=   r2   r(   
preprocess   sZ   6



z!ImageGPTImageProcessor.preprocess)NN)__name__
__module____qualname____doc__Zmodel_input_namesr   ZBILINEARr   r   r   intr   Zndarrayboolr   strr;   r   r   rG   r   ZFIRSTr   r   PILZImagerR   __classcell__r'   r'   r?   r(   r0   <   s    


3
	
r0   ))rV   typingr   r   r   r   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   Zutils.import_utilsr   rZ   Z
get_loggerrS   rO   r)   r.   r0   __all__r'   r'   r'   r(   <module>   s"   ,
	 
t