o
    i^                     @   s   d Z ddlZddlmZmZ ddlZddl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mZmZmZ ddlmZmZ dd	lmZ e e!Z"	
			dde#de#de#de#de#de#de#fddZ$G dd deZ%dgZ&dS )z#Image processor class for GLM-4.1V.    N)OptionalUnion   )BaseImageProcessorBatchFeature)convert_to_rgbresizeto_channel_dimension_format)OPENAI_CLIP_MEANOPENAI_CLIP_STDChannelDimension
ImageInputPILImageResamplingget_image_sizeinfer_channel_dimension_formatis_scaled_imagemake_flat_list_of_imagesto_numpy_arrayvalid_imagesvalidate_preprocess_arguments)
TensorTypelogging)
VideoInput       1     
num_framesheightwidthtemporal_factorfactor
min_pixels
max_pixelsc                 C   sl  | |k rt d|  d| ||k s||k r#t d| d| d| t||t|| dkr>t dt||t||  t|| | }t|| | }t| | | }	|	| | |krt| | | | }
t|t||
 | | }t|t||
 | | }||fS |	| | |k rt|| | |  }
t||
 | | }t||
 | | }||fS )Nzt:z% must be larger than temporal_factor:zheight:z
 or width:z must be larger than factor:   z4absolute aspect ratio must be smaller than 200, got )
ValueErrormaxminroundmathsqrtfloorceil)r   r   r   r    r!   r"   r#   h_barw_bart_barbeta r1   d/home/ubuntu/.local/lib/python3.10/site-packages/transformers/models/glm4v/image_processing_glm4v.pysmart_resize1   s*   	r3   c                &       sr  e Zd ZdZddgZddejdddddddddfd	ed
ee	e
ef  dededeeef dedeeeee f  deeeee f  dededededdf fddZddddddddddddejdfdeeef d	ee d
ee	e
ef  dee dee dee dee deeeee f  deeeee f  dee dee dee dee dee deee
ef  fddZddddddddddddddejdfdedee d	ee d
ee	e
ef  dee dee dee dee deeeee f  deeeee f  dee dee dee dee deee
ef  dee deee
ef  f"dd Zd%d!ed"efd#d$Z  ZS )&Glm4vImageProcessora
  
    Constructs a GLM-4V image processor that dynamically resizes images based on the original images.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image's (height, width) dimensions.
        size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 15000}`):
            Size of the image's `(height, width)` dimensions after resizing. Can be overridden by the `size` parameter
            in the `preprocess` method. Available options are:
                - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
                    Do NOT keep the aspect ratio.
                - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
                    the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
                    less or equal to `longest_edge`.
                - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
                    aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
                    `max_width`.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
            Resampling filter to use when resizing the image.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Whether to rescale the image by the specified scale `rescale_factor`.
        rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
            Scale factor to use if rescaling the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image.
        image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
            Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
        image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
            Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
        do_convert_rgb (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to RGB.
        patch_size (`int`, *optional*, defaults to 14):
            The spatial patch size of the vision encoder.
        temporal_patch_size (`int`, *optional*, defaults to 2):
            The temporal patch size of the vision encoder.
        merge_size (`int`, *optional*, defaults to 2):
            The merge size of the vision encoder to llm encoder.
    pixel_valuesimage_grid_thwTNgp?   r   	do_resizesizeresample
do_rescalerescale_factordo_normalize
image_mean	image_stddo_convert_rgb
patch_sizetemporal_patch_size
merge_sizereturnc                    s   t  jdi | |d urd|vsd|vrtd|d u r"ddd}|| _|| _|| _|| _|| _|| _|d ur:|nt	| _
|d urC|nt| _|
| _|| _|| _|	| _d S )Nshortest_edgelongest_edge:size must contain 'shortest_edge' and 'longest_edge' keys.r   q rE   rF   r1   )super__init__r%   r9   r8   r:   r;   r<   r=   r
   r>   r   r?   rA   rB   rC   r@   )selfr8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   kwargs	__class__r1   r2   rK   |   s"   

zGlm4vImageProcessor.__init__imagesdata_formatinput_data_formatc                 C   s  t |}|rdd |D }dd |D }|r!t|d r!td |du r+t|d }t|d |d\}}||}}g }|D ]B}|r_t|||||
| |d |d	 d
\}}t|||f||d}|ri| j|||d}|rt| j	|||	|d}t
|||d}|| q>t|}|tjkr|dddd}|jd | dkrtj|d tj ||jd |  dd}tj||gdd}|jd }|jd | }||
 ||
 }}|||||| ||
|| ||
	}|ddddddddd	}||| | || |
 |
 }||||ffS )a~  
        Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.

        Args:
            images (`ImageInput`):
                Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`.
            vision_info (`List[Dict]`, *optional*):
                Optional list of dictionaries containing additional information about vision inputs.
            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. `shortest_edge` and `longest_edge` keys must be present.
            resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
                Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image.
            rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
                Scale factor to use if rescaling the image.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
                Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
            patch_size (`int`, *optional*, defaults to `self.patch_size`):
                The spatial patch size of the vision encoder.
            temporal_patch_size (`int`, *optional*, defaults to `self.temporal_patch_size`):
                The temporal patch size of the vision encoder.
            merge_size (`int`, *optional*, defaults to `self.merge_size`):
                The merge size of the vision encoder to llm encoder.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to convert the image to RGB.
            data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output 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.
                - Unset: Use the channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for 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.   - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        c                 S      g | ]}t |qS r1   )r   .0imager1   r1   r2   
<listcomp>       z3Glm4vImageProcessor._preprocess.<locals>.<listcomp>c                 S   rS   r1   )r   rT   r1   r1   r2   rW      rX   r   zIt looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.N)channel_dimrE   rF   )r   r   r   r    r!   r"   r#   )r9   r:   rR   )scalerR   )rV   meanstdrR   )input_channel_dimr      r   )axis               )r   r   loggerwarning_oncer   r   r3   r   rescale	normalizer	   appendnparrayr   LAST	transposeshaperepeatnewaxisconcatenatereshape)rL   rP   r8   r9   r:   r;   r<   r=   r>   r?   rA   rB   rC   r@   rQ   rR   r   r   resized_heightresized_widthprocessed_imagesrV   patchesrepeatschannelgrid_tgrid_hgrid_wflatten_patchesr1   r1   r2   _preprocess   s|   =

	


zGlm4vImageProcessor._preprocessvideosreturn_tensorsc                 C   s  |dur|n| j }|durd|vsd|vrtd|du r"ddd}|dur(|n| j}|dur1|n| j}|dur:|n| j}|durC|n| j}|durL|n| j}|	durU|	n| j}	|
dur^|
n| j}
|durg|n| j	}|durp|n| j
}|dury|n| j}|dur|n| j}|dur| |}t|}|durt|stdt|||	|
|||d	 i }|durg g }}|D ]"}| j||||||||	|
||||||d
\}}|| || qt|}t|}|||d t||dS )a  
        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_rescale=False`.
            videos (`VideoInput`):
                Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
                passing in videos with pixel values between 0 and 1, set `do_rescale=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. Shortest edge of the image is resized to size["shortest_edge"], with
                the longest edge resized to keep the input aspect ratio.
            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_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image.
            rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to rescale the image by if `do_rescale` is set to `True`.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
                Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
                `True`.
                The max pixels of the image to resize the image.
            patch_size (`int`, *optional*, defaults to `self.patch_size`):
                The spatial patch size of the vision encoder.
            temporal_patch_size (`int`, *optional*, defaults to `self.temporal_patch_size`):
                The temporal patch size of the vision encoder.
            merge_size (`int`, *optional*, defaults to `self.merge_size`):
                The merge size of the vision encoder to llm encoder.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to convert the image to RGB.
            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:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - Unset: Use the channel dimension format of the input image.
            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.

        NrE   rF   rG   r   rH   rI   zkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)r<   r=   r>   r?   r8   r9   r:   )r8   r9   r:   r;   r<   r=   r>   r?   rA   rB   rC   rQ   r@   rR   )r5   r6   )datatensor_type)r9   r%   r8   r:   r;   r<   r=   r>   r?   rA   rB   rC   r@   fetch_imagesr   r   r   r~   extendrj   rk   rl   updater   )rL   rP   r   r8   r9   r:   r;   r<   r=   r>   r?   rA   rB   rC   r@   r   rQ   rR   r   r5   vision_grid_thwsrV   rw   r6   r1   r1   r2   
preprocess(  sv   M







zGlm4vImageProcessor.preprocessr   r   c              	   C   sv   | d| j}| d| j}| dddd}|| }t| j||||d |d | jd	\}}	|| |	| }
}|
| S )
a  
        A utility that returns number of image patches for a given image size.

        Args:
            height (`int`):
                Height of the input image.
            width (`int`):
                Width of the input image.
            images_kwargs (`dict`, *optional*)
                Any kwargs to override defaults of the image processor.
        Returns:
            `int`: Number of image patches per image.
        rA   rC   r9   r   rH   rI   rE   rF   )r   r   r   r!   r"   r#   r    )getrA   rC   r3   rB   )rL   r   r   images_kwargsrA   rC   r9   r!   rt   ru   r{   r|   r1   r1   r2   get_number_of_image_patches  s   
	z/Glm4vImageProcessor.get_number_of_image_patches)N)__name__
__module____qualname____doc__model_input_namesr   BICUBICboolr   dictstrintr   floatlistrK   r   FIRSTr   r   r~   r   r   r   __classcell__r1   r1   rN   r2   r4   R   s   '
	
'
	

 	

 r4   )r   r   r   r   )'r   r)   typingr   r   numpyrk   image_processing_utilsr   r   image_transformsr   r   r	   image_utilsr
   r   r   r   r   r   r   r   r   r   r   r   utilsr   r   video_utilsr   
get_loggerr   rf   r   r3   r4   __all__r1   r1   r1   r2   <module>   sD   8

!   
	