
    rhp8                        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&y)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         /var/www/html/ai-insurance-compliance-backend/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_quantizer3   6   s/    			"aA"1h/A99QQ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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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 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        |   di | ||nddd}t        |      }|t        j                  |      nd | _        || _        || _        || _        || _	        || _
        y )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   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.
        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   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?)rJ   scalerK   rL   r   )r	   )rG   rJ   rK   rL   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        |       }}|r#t        |d         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.)r9   r:   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].)rJ   r:   r;   rL   )rJ   rL   r.   )input_channel_dim	input_ids)datatensor_type)r9   r:   r   r;   r<   r=   r2   r    rF   r   r   rN   r   r   r   loggerwarning_oncer   r
   rS   r   r   LASTr3   r/   shapelistr   )rG   rT   r9   r:   r;   r<   r=   r2   rU   rK   rL   rJ   
batch_sizerY   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.'<<OF1I6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booldictstrrE   r   r
   rS   r   FIRSTr   r   PILImagera   __classcell__)rI   s   @r*   r7   r7   <   s   . ((
 BF)-'9'B'B!"&3 5d3i"**!<=>3 	3
 tCH~&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 D>zC tCH~&	zC
 %zC tn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,   r7   )'re   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   rn   
get_loggerrb   r[   r+   r3   r7   __all__rC   r,   r*   <module>rz      s    * "  U U L L
 
 
 _ ^ *  
		H	%  
;pC/ pC  pCf $
$r,   