
     `i:                     (   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            rddlZ ej         e!          Z"d
 Z#d Z$ ed           G 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                    |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         /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/imagegpt/image_processing_imagegpt.pysquared_euclidean_distancer+   -   s    	A		!1	%	%	%B		!1	%	%	%B	1aB
111d7a"fr$'{*AH    c                 z    |                      dd          } t          | |          }t          j        |d          S )Nr   r   r   )reshaper+   r    argmin)xclustersr)   s      r*   color_quantizer3   6   s9    			"aA"1h//A9QQr,   )vision)backendsc                       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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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            Z 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 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_valuesNTr2   	do_resizesizeresampledo_normalizedo_color_quantizereturnc                      t                      j        di | ||nddd}t          |          }|t          j        |          nd | _        || _        || _        || _        || _	        || _
        d S )N   )heightwidth )super__init__r   r    arrayr2   r9   r:   r;   r<   r=   )	selfr2   r9   r:   r;   r<   r=   kwargs	__class__s	           r*   rE   zImageGPTImageProcessor.__init__W   s     	""6"""'ttc-J-JT"".6.B***"	 (!2r,   imagedata_formatinput_data_formatc                     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.
        rA   rB   zFThe `size` dictionary must contain the keys `height` and `width`. Got )r:   r;   rK   rL   )r   
ValueErrorkeysr
   )rG   rJ   r:   r;   rK   rL   rH   output_sizes           r*   r
   zImageGPTImageProcessor.resizem   s    F T""47$#6#6sfjfofofqfqsstttH~tG}5
#/
 
 
 
 	
r,   c                 6    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?)rJ   scalerK   rL   r   )r	   )rG   rJ   rK   rL   s       r*   	normalizez ImageGPTImageProcessor.normalize   s)    " e9+arsss	r,   imagesreturn_tensorsc                    	
 ||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 |D             }|r/t          |d                   rt                              d           
t!          |d                   
|r
 fd|D             }|r
 fd	|D             }|r
fd
|D             }t          j        |          }t#          ||                              |j        dd                   }|j        d         }|                    |d          }t)          |          }d|i}n	
fd|D             }d|i}t+          ||          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.)r9   r:   r;   z8Clusters must be specified if do_color_quantize is True.c                 ,    g | ]}t          |          S rC   )r   ).0rJ   s     r*   
<listcomp>z5ImageGPTImageProcessor.preprocess.<locals>.<listcomp>  s     <<<E.''<<<r,   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                 B    g | ]}                     |           S ))rJ   r:   r;   rL   )r
   )rX   rJ   rL   r;   rG   r:   s     r*   rY   z5ImageGPTImageProcessor.preprocess.<locals>.<listcomp>  s>        %dXYjkk  r,   c                 >    g | ]}                     |           S ))rJ   rL   )rS   )rX   rJ   rL   rG   s     r*   rY   z5ImageGPTImageProcessor.preprocess.<locals>.<listcomp>  s+    kkk[`dnn5DUnVVkkkr,   c                 F    g | ]}t          |t          j                  S rC   )r   r   LAST)rX   rJ   rL   s     r*   rY   z5ImageGPTImageProcessor.preprocess.<locals>.<listcomp>  s,    wwwgl1%9I9NPabbwwwr,   r.   	input_idsc                 2    g | ]}t          |          S rC   )r   )rX   rJ   rK   rL   s     r*   rY   z5ImageGPTImageProcessor.preprocess.<locals>.<listcomp>(  s(    mmm]b1%FWXXmmmr,   r8   )datatensor_type)r9   r:   r   r;   r<   r=   r2   r    rF   r   r   rN   r   r   loggerwarning_oncer   r3   r/   shapelistr   )rG   rT   r9   r:   r;   r<   r=   r2   rU   rK   rL   
batch_sizer`   s   `  ``    ``  r*   
preprocessz!ImageGPTImageProcessor.preprocess   s   l "+!6IIDN	'ttTYT""'388'3'?||TEV1B1N--TXTj'3888H%%$V,,F## 	:   	&	
 	
 	
 	
  	Y!1WXXX =<V<<< 	OF1I66 	h  
 $ >vay I I 	      #  F
  	lkkkkkdjkkkF 	,wwwwpvwwwFXf%%F#FH55==fl3B3>OPPF  aJ^^J33F &\\F(DDmmmmmflmmmF"F+D>BBBBr,   c                    t                                                      }|                    d          =t          |d         t          j                  r|d                                         |d<   g d}|D ]}||v rd ||<   |S )Nr2   )
image_mean	image_stdrescale_factor
do_rescale)rD   to_dictget
isinstancer    ndarraytolist)rG   outputmissing_keyskeyrI   s       r*   rm   zImageGPTImageProcessor.to_dict,  s    ""::j!!-*VJ=OQSQ[2\2\-!'
!3!:!:!<!<F:RRR 	# 	#Cf}}"sr,   )NN)__name__
__module____qualname____doc__model_input_namesr   BILINEARr   r   re   intr    rp   booldictstrrE   r   r
   rS   r   FIRSTr   r   PILImagerg   rm   __classcell__)rI   s   @r*   r7   r7   <   s5        . ((
 BF)-'9'B!"&3 3 5d3i"*!<=>3 	3
 tCH~&3 %3 3  3 
3 3 3 3 3 34 (:'B>BDH.
 .
z.
 38n.
 %	.

 eC)9$9:;.
 $E#/?*?$@A.
 
.
 .
 .
 .
f ?CDH	 z eC)9$9:; $E#/?*?$@A	
 
   * %$&& %))-15'+,0AE;?>N>TDHwC wCwC D>wC tCH~&	wC
 -.wC tnwC $D>wC 5d3i"*!<=>wC !sJ!78wC eC)9$9:;wC $E#/?*?$@AwC 
wC wC wC '&wCr        r,   r7   )'rx   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   r   
get_loggerru   rb   r+   r3   r7   __all__rC   r,   r*   <module>r      s   * ) " " " " " " " "     U U U U U U U U U U L L L L L L L L L L
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 _ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ * * * * * *  JJJ 
	H	%	%        
;z z z z z/ z z  zz $
$r,   