
    sg7                         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       rddlZ ej@                  e!      Z"d	 Z#d
 Z$ G d de	      Z%y)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                 $   |j                   }t        j                  t        j                  |       d      }t        j                  t        j                  |      d      }t        j                  | |      }|d d d f   d|z  z
  |d d d f   z   }|S )N   axisr      )Tnpsumsquarematmul)aba2b2abds         i/var/www/html/venv/lib/python3.12/site-packages/transformers/models/imagegpt/image_processing_imagegpt.pysquared_euclidean_distancer,   ,   sr    	A			!1	%B			!1	%B	1aB
1d7a"fr$'{*AH    c                 l    | j                  dd      } t        | |      }t        j                  |d      S )Nr   r   r   )reshaper,   r!   argmin)xclustersr*   s      r+   color_quantizer4   5   s/    			"aA"1h/A99QQr-   c                       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
f   de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ef      deeeef      dej                  fdZ e       dddddddej*                  df	dededeee
f   ded	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j2                  j2                  fd       Z x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`.
    pixel_valuesNTr3   	do_resizesizeresampledo_normalizedo_color_quantizereturnc                     t        |   di | ||nddd}t        |      }|t        j                  |      nd | _        || _        || _        || _        || _	        || _
        y )N   )heightwidth )super__init__r
   r!   arrayr3   r8   r9   r:   r;   r<   )	selfr3   r8   r9   r:   r;   r<   kwargs	__class__s	           r+   rD   zImageGPTImageProcessor.__init__U   sl     	"6"'tc-JT".6.B*"	 (!2r-   imagedata_formatinput_data_formatc                     t        |      }d|vsd|vrt        d|j                                |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@   rA   zFThe `size` dictionary must contain the keys `height` and `width`. Got )r9   r:   rJ   rK   )r
   
ValueErrorkeysr   )rF   rI   r9   r:   rJ   rK   rG   output_sizes           r+   r   zImageGPTImageProcessor.resizek   sy    F T"47$#6efjfofofqersttH~tG}5
#/
 
 	
r-   c                 .    t        |d||      }|dz
  }|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?)rI   scalerJ   rK   r   )r   )rF   rI   rJ   rK   s       r+   	normalizez ImageGPTImageProcessor.normalize   s#    " e9+ars	r-   imagesreturn_tensorsc           	      V   ||n| j                   }||n| j                  }t        |      }||n| j                  }||n| j                  }||n| j
                  }||n| j                  }t        j                  |      }t        |      }t        |      st        d      t        |||       |r|t        d      |D cg c]  }t        |       }}t        |d         r|rt        j!                  d       |
t#        |d         }
|r"|D cg c]  }| j%                  ||||
       }}|r |D cg c]  }| j'                  ||
       }}|r|D cg c]  }t)        |t*        j,                  |
       }}t        j                  |      }t/        ||      j1                  |j2                  dd	       }|j2                  d   }|j1                  |d	      }t5        |      }n|D cg c]  }t)        ||	|

       }}d|i}t7        ||      S c c}w c c}w c c}w c c}w c c}w )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.)r8   r9   r:   z8Clusters must be specified if do_color_quantize is True.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].)rI   r9   r:   rK   )rI   rK   r/   )input_channel_dim	input_ids)datatensor_type)r8   r9   r
   r:   r;   r<   r3   r!   rE   r   r   rM   r   r   r   loggerwarning_oncer   r   rR   r   r   LASTr4   r0   shapelistr	   )rF   rS   r8   r9   r:   r;   r<   r3   rT   rJ   rK   rI   
batch_sizerX   s                 r+   
preprocessz!ImageGPTImageProcessor.preprocess   s`   l "+!6IDNN	'tTYYT"'38'3'?|TEVEV1B1N-TXTjTj'3888H%$V,F#:  	&	
 !1WXX 6<<E.'<<6!9%,h
 $ >vay I $ %dXYjkF 
 djk[`dnn5DUnVkFkpvwgl1%9I9N9NPabwFwXXf%F#FH5==fll3B>OPF  aJ^^J3F &\F $ ,E;RcdF 
 V$>BBQ = l xs   HH6H"H!*H&)NN)__name__
__module____qualname____doc__model_input_namesr   BILINEARr   r   r   intr!   ndarrayboolr   strrD   r   r   rR   r   FIRSTr   r   PILImager`   __classcell__)rH   s   @r+   r6   r6   ;   s   . ((
 BF#'9'B'B!"&3 5d3i"**!<=>3 	3
 38n3 %3 3  3 
34 (:'B'B>BDH.
zz.
 38n.
 %	.

 eC)9$9:;.
 $E#/?*?$@A.
 
.
f ?CDH	zz eC)9$9:; $E#/?*?$@A	
 
* %& #'+!,0AE;?>N>T>TDHzCzC zC 38n	zC
 %zC zC $D>zC 5d3i"**!<=>zC !sJ!78zC eC)9$9:;zC $E#/?*?$@AzC 
zC 'zCr-   r6   )&rd   typingr   r   r   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   rl   
get_loggerra   rZ   r,   r4   r6   rB   r-   r+   <module>rv      sq    * . .  U U L L
 
 
 _ ^  
		H	% pC/ pCr-   