
    qi]                     $   d Z ddl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 ddlmZmZ dd	lmZ  ej>                  e       Z! G d
 ded      Z"	 	 	 	 dde#de#de#de#de#de#de#fdZ$ G d de      Z%dgZ&y)z#Image processor class for GLM-4.1V.    N   )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)ImagesKwargs)
TensorTypelogging)
VideoInputc                   0    e Zd ZU dZeed<   eed<   eed<   y)Glm4vImageProcessorKwargsaR  
    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.
    
patch_sizetemporal_patch_size
merge_sizeN)__name__
__module____qualname____doc__int__annotations__     b/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/glm4v/image_processing_glm4v.pyr   r   0   s     OOr%   r   F)total
num_framesheightwidthtemporal_factorfactor
min_pixels
max_pixelsc                 R   | |k  rt        d|  d|       ||k  s||k  r.t        ||z  ||z        }t        ||z        }t        ||z        }t        ||      t        ||      z  dkD  r%t        dt        ||      t        ||      z         t	        ||z        |z  }t	        ||z        |z  }	t	        | |z        |z  }
|
|z  |	z  |kD  rrt        j                  | |z  |z  |z        }t        |t        j                  ||z  |z        |z        }t        |t        j                  ||z  |z        |z        }	||	fS |
|z  |	z  |k  rZt        j                  || |z  |z  z        }t        j                  ||z  |z        |z  }t        j                  ||z  |z        |z  }	||	fS )Nzt:z% must be larger than temporal_factor:   z4absolute aspect ratio must be smaller than 200, got )	
ValueErrormaxr"   minroundmathsqrtfloorceil)r(   r)   r*   r+   r,   r-   r.   scaleh_barw_bart_barbetas               r&   smart_resizer>   ?   s    O#2j\)NN_`aa%&.FVOVe^4Ve^$EEM"
65C..4B3vuCUX[\bdiXjCjBkl
 	
 &6/"V+E%&.!F*E*.//AEu}uz)yy*v-5CDFDJJv}v'=>GHFDJJut|f'<=FG %< 
		+yyzF':U'BCD		&4-&01F:		%$,/069%<r%   c            "           e Zd ZdZddgZeZddej                  dddddddddfd	e	d
e
eef   dz  dede	deez  de	deee   z  dz  deee   z  dz  de	dedededdf fdZddddddddddddej"                  dfdeez  d	e	dz  d
e
eef   dz  dedz  de	dz  dedz  de	dz  deee   z  dz  deee   z  dz  dedz  dedz  dedz  de	dz  dedz  deez  dz  fdZdddddddddddddej"                  dfded	e	dz  d
e
eef   dz  dedz  de	dz  dedz  de	dz  deee   z  dz  deee   z  dz  dedz  dedz  dedz  de	dz  deez  dz  dedz  deez  dz  f dZd dedefdZ x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?      	do_resizesizeresample
do_rescalerescale_factordo_normalize
image_mean	image_stddo_convert_rgbr   r   r   returnc                 $   t        |   di | |d|vsd|vrt        d      |ddd}|| _        || _        || _        || _        || _        || _        ||nt        | _
        ||nt        | _        |
| _        || _        || _        |	| _        y )Nshortest_edgelongest_edge:size must contain 'shortest_edge' and 'longest_edge' keys. 1  iq )rP   rQ   r$   )super__init__r1   rF   rE   rG   rH   rI   rJ   r	   rK   r
   rL   r   r   r   rM   )selfrE   rF   rG   rH   rI   rJ   rK   rL   rM   r   r   r   kwargs	__class__s                 r&   rU   zGlm4vImageProcessor.__init__   s      	"6"!<VZ@ZYZZ\%.PD	" $,((2(>*DT&/&;$#6 $,r%   imagesdata_formatinput_data_formatc                    t        |      }|r|D cg c]  }t        |       }}|D cg c]  }t        |       }}|r#t        |d         rt        j                  d       |t        |d         }t        |d   |      \  }}||}}g }|D ]  }|r/t        |||||
|z  |d   |d         \  }}t        |||f||      }|r| j                  |||      }|r| j                  |||	|	      }t        |||
      }|j                  |        t        j                  |      }|t         j"                  k(  r|j%                  dddd      }|j&                  d   |z  dk7  rXt        j(                  |d   t        j*                     ||j&                  d   |z  z
  d      }t        j,                  ||gd      }|j&                  d   }|j&                  d   |z  }||
z  ||
z  }}|j/                  |||||z  ||
||z  ||
	      }|j%                  ddddddddd	      }|j/                  ||z  |z  ||z  |
z  |
z        }||||ffS c c}w c c}w )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.
        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.)channel_dimrP   rQ   )r(   r)   r*   r+   r,   r-   r.   )rF   rG   r[   )r9   r[   )imagemeanstdr[   )input_channel_dimr      rD   )axis               )r   r   r   r   loggerwarning_oncer   r   r>   r   rescale	normalizer   appendnparrayr   LAST	transposeshaperepeatnewaxisconcatenatereshape)rV   rY   rE   rF   rG   rH   rI   rJ   rK   rL   r   r   r   rM   rZ   r[   r^   r)   r*   resized_heightresized_widthprocessed_imagespatchesrepeatschannelgrid_tgrid_hgrid_wflatten_patchess                                r&   _preprocesszGlm4vImageProcessor._preprocess   s   z *&19?@nU+@F@ 6<<E.'<</&)4s $ >vay I&vay>OP(. 	+E0<2!$7%
2#O4#N31-  ?(fw U.TefjiSd '  0{VghE##E*1	+4 ((+,*///''1a3G==11Q6iiBJJ')<a@PSf@f)gnoG nngw%7a@G--"q!%88':5}
7R//j j 

 ##Aq!Q1aA>!//VOf$g0C&Cj&PS]&]
  888M A =s
   II	return_tensorsc                 z   ||n| j                   }|d|vsd|vrt        d      ||n| j                  }||n| j                  }||n| j                  }||n| j
                  }||n| j                  }||n| j                  }|	|	n| j                  }	|
|
n| j                  }
||n| j                  }||n| j                  }||n| j                  }|| j                  |      }t        |      }|t        |      st        d      t!        ||||	|||       i }|g g }}|D ]G  }| j#                  |||||||||	|
|||||      \  }}|j%                  |       |j'                  |       I t)        j*                  |      }t)        j*                  |      }|j-                  ||d       t/        ||      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`.
            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`.
            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.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.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.

        rP   rQ   rR   zSInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor)rI   rJ   rK   rL   rE   rF   rG   )rE   rF   rG   rH   rI   rJ   rK   rL   r   r   r   rZ   rM   r[   )rA   rB   )datatensor_type)rF   r1   rE   rG   rH   rI   rJ   rK   rL   r   r   r   rM   fetch_imagesr   r   r   r   extendrn   ro   rp   updater   )rV   rY   rE   rF   rG   rH   rI   rJ   rK   rL   r   r   r   rM   r   rZ   r[   r   rA   vision_grid_thwsr^   r{   rB   s                          r&   
preprocesszGlm4vImageProcessor.preprocess:  s   J 'tTYY!<VZ@ZYZZ!*!6IDNN	'38#-#9Zt
+9+E4K^K^'3'?|TEVEV#-#9Zt
!*!6IDNN	#-#9Zt
5H5T1Z^ZrZr#-#9Zt
+9+E4K^K^&&v.F-f5Fl6&:rss%)%!	
 -/*L 8*.*:*:'%)#1!-)')(;) +#1&7 +; +'" ##G, ''7'8( 88L1L!xx(89KKIYZ[>BBr%   r)   r*   c           	      0   |j                  d| j                        }|j                  d| j                        }|j                  d| j                        }||z  }t	        | j
                  ||||d   |d   | j
                        \  }}	||z  |	|z  }}
|
|z  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.
        r   r   rF   rP   rQ   )r(   r)   r*   r,   r-   r.   r+   )getr   r   rF   r>   r   )rV   r)   r*   images_kwargsr   r   rF   r,   rx   ry   r   r   s               r&   get_number_of_image_patchesz/Glm4vImageProcessor.get_number_of_image_patches  s     #&&|T__E
"&&|T__E
  3j((4//O,N+ 44)
% (:5}
7Rr%   )N)r   r   r    r!   model_input_namesr   valid_kwargsr   BICUBICbooldictstrr"   floatlistrU   r   FIRSTr   r   r   r   r   r   __classcell__)rX   s   @r&   r@   r@   c   s   %N ()9:,L &*'9'A'A&-!1504##$"-"- 38nt#"- %	"-
 "- e"- "- DK'$."- 4;&-"- "- "- !"- "- 
"-N "&&*.2"&'+$(1504!%*.!%&*/?/E/E;?!F9Z'F9 $;F9 38nt#	F9
 %t+F9 4KF9 F9 TkF9 DK'$.F9 4;&-F9 $JF9 !4ZF9 $JF9 tF9 &,F9  !11D8!F9V "&&*.2"&'+$(1504!%*.!%&*26/?/E/E;?#ACAC $;AC 38nt#	AC
 %t+AC 4KAC AC TkAC DK'$.AC 4;&-AC $JAC !4ZAC $JAC tAC j(4/AC  &,!AC" !11D8#ACF# c r%   r@   )rD      rS   i   )'r!   r5   numpyro   image_processing_utilsr   r   image_transformsr   r   r   image_utilsr	   r
   r   r   r   r   r   r   r   r   r   r   processing_utilsr   utilsr   r   video_utilsr   
get_loggerr   rj   r   r"   r>   r@   __all__r$   r%   r&   <module>r      s    *   F 
    - ( % 
		H	%E & 0!!! ! 	!
 ! ! !Hw, wt !
!r%   