o
    ZhN                     @   s   d Z ddlZddl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mZmZmZ ddlm Z m!Z!m"Z"m#Z# e#$e%Z&e" rbddl'Z'G d	d
 d
eZ(d
gZ)dS )z!Image processor class for Gemma3.    N)DictListOptionalUnion   )BaseImageProcessorBatchFeatureget_size_dict)convert_to_rgbresizeto_channel_dimension_format)IMAGENET_STANDARD_MEANIMAGENET_STANDARD_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filter_out_non_signature_kwargsis_vision_availableloggingc                &       s@  e Zd ZdZddgZddejd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e dee dee dee dee ddf fddZ		d"dejdedededeee
ef  deee
ef  fddZ		d"deej dededededeee
ef  deee
ef  fddZe dddddddddejddddddfdedee dee	e
ef  d	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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 dejjf$d d!Z  ZS )#Gemma3ImageProcessoraI
  
    Constructs a SigLIP image processor.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
            `do_resize` in the `preprocess` method.
        size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
            Size of the image after resizing. Can be overridden by `size` in the `preprocess` method.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
            the `preprocess` method.
        rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
            Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
            method.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image by the specified mean and standard deviation. Can be overridden by
            `do_normalize` in the `preprocess` method.
        image_mean (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
            Mean to use if normalizing the image. This is a float or list of floats the length of the number of
            channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
        image_std (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
            Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
            number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
            Can be overridden by the `image_std` parameter in the `preprocess` method.
        do_convert_rgb (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to RGB.
        do_pan_and_scan (`bool`, *optional*):
            Whether to apply `pan_and_scan` to images.
        pan_and_scan_min_crop_size (`int`, *optional*):
            Minimum size of each crop in pan and scan.
        pan_and_scan_max_num_crops (`int`, *optional*):
            Maximum number of crops per image in pan and scan.
        pan_and_scan_min_ratio_to_activate (`float`, *optional*):
            Minimum aspect ratio to activate pan and scan.
    pixel_values	num_cropsTNgp?	do_resizesizeresample
do_rescalerescale_factordo_normalize
image_mean	image_stddo_convert_rgbdo_pan_and_scanpan_and_scan_min_crop_sizepan_and_scan_max_num_crops"pan_and_scan_min_ratio_to_activatereturnc                    s   t  jdi | |d ur|nddd}t|dd}|d ur |nt}|d ur(|nt}|| _|| _|| _|| _|| _	|| _
|| _|| _|	| _|
| _|| _|| _|| _d S )N   )heightwidthT)default_to_square )super__init__r	   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   )selfr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   kwargs	__class__r2   a/var/www/auris/lib/python3.10/site-packages/transformers/models/gemma3/image_processing_gemma3.pyr4   _   s$   
zGemma3ImageProcessor.__init__imagedata_formatinput_data_formatc                    sr  t \}}||kr6|| |k rg S tt|| d }	ttt|| |	}	td|	}	t||	}	d}
n+|| |k r>g S tt|| d }
ttt|| |
}
td|
}
t||
}
d}	tt||	 tt||
  t |k r|g S fddt|	D } fddt|
D }|tj	kr fddt
||D }|S  fddt
||D }|S )	a  
        Pan and Scan and image, by cropping into smaller images when the aspect ratio exceeds
        minimum allowed ratio.

        Args:
            image (`np.ndarray`):
                Image to resize.
            pan_and_scan_min_crop_size (`int`, *optional*):
                Minimum size of each crop in pan and scan.
            pan_and_scan_max_num_crops (`int`, *optional*):
                Maximum number of crops per image in pan and scan.
            pan_and_scan_min_ratio_to_activate (`float`, *optional*):
                Minimum aspect ratio to activate pan and scan.
            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      ?      c                       g | ]} | qS r2   r2   .0i)crop_size_wr2   r9   
<listcomp>       z5Gemma3ImageProcessor.pan_and_scan.<locals>.<listcomp>c                    r?   r2   r2   r@   )crop_size_hr2   r9   rD      rE   c                    s,   g | ]\}}||  || f qS r2   r2   rA   Zpos_hZpos_wrF   rC   r:   r2   r9   rD      s    c                    s2   g | ]\}}d d ||  || f qS )Nr2   rG   rH   r2   r9   rD      s     )r   intmathfloorminmaxceilranger   ZLAST	itertoolsproduct)r5   r:   r*   r+   r,   r;   r<   r/   r0   Znum_crops_wZnum_crops_hZcrop_positions_wZcrop_positions_hZimage_cropsr2   rH   r9   pan_and_scan   s>   







z!Gemma3ImageProcessor.pan_and_scanimagesc              	   C   sN   g }g }	|D ]}
| j |
|||||d}||
g|  |	t| q||	fS )N)r:   r*   r+   r,   r;   r<   )rR   extendappendlen)r5   rS   r)   r*   r+   r,   r;   r<   Zpas_images_listr   r:   Z
pas_imagesr2   r2   r9    _process_images_for_pan_and_scan   s   
z5Gemma3ImageProcessor._process_images_for_pan_and_scanreturn_tensorsc              
   C   s8  |dur|n| j }|dur|n| j}t|ddd}|dur|n| j}|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}t|}t|stdt|||||	|||d |rdd |D }d	d |D }|rt|d
 rtd |du rt|d
 }|r| j|||||||d\}}ndd |D }g }|D ]9}|r|d |d }}t|||f||d}|r| j|||d}|r| j|||	|d}t|||d}|| q||d}t||
dS )a  
        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_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.
            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`.
            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.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to convert the image to RGB.
            do_pan_and_scan (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to apply `pan_and_scan` to images.
            pan_and_scan_min_crop_size (`int`, *optional*, defaults to `self.pan_and_scan_min_crop_size`):
                Minimum size of each crop in pan and scan.
            pan_and_scan_max_num_crops (`int`, *optional*, defaults to `self.pan_and_scan_max_num_crops`):
                Maximum number of crops per image in pan and scan.
            pan_and_scan_min_ratio_to_activate (`float`, *optional*, defaults to `self.pan_and_scan_min_ratio_to_activate`):
                Minimum aspect ratio to activate pan and scan.
        Nr!   F)
param_namer1   zkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)r#   r$   r%   r&   r'   r    r!   r"   c                 S      g | ]}t |qS r2   )r
   rA   r:   r2   r2   r9   rD   d  rE   z3Gemma3ImageProcessor.preprocess.<locals>.<listcomp>c                 S   rZ   r2   )r   r[   r2   r2   r9   rD   g  rE   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.)rS   r)   r*   r+   r,   r;   r<   c                 S   s   g | ]}d qS )r   r2   )rA   _r2   r2   r9   rD     s    r/   r0   )r:   r!   r"   r<   )r:   scaler<   )r:   meanZstdr<   )Zinput_channel_dim)r   r   )dataZtensor_type)r    r!   r	   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r   r   
ValueErrorr   r   loggerZwarning_oncer   rW   r   Zrescale	normalizer   rU   r   )r5   rS   r    r!   r"   r#   r$   r%   r&   r'   rX   r;   r<   r(   r)   r*   r+   r,   r   Zprocessed_imagesr:   r/   r0   r_   r2   r2   r9   
preprocess   s   K

zGemma3ImageProcessor.preprocess)NN)__name__
__module____qualname____doc__Zmodel_input_namesr   ZBILINEARboolr   r   strrI   r   floatr   r4   npZndarrayr   rR   rW   r   ZFIRSTr   r   PILZImagerc   __classcell__r2   r2   r7   r9   r   5   s   '
	
+
Y
	
r   )*rg   rP   rJ   typingr   r   r   r   numpyrk   Zimage_processing_utilsr   r   r	   Zimage_transformsr
   r   r   Zimage_utilsr   r   r   r   r   r   r   r   r   r   r   r   utilsr   r   r   r   Z
get_loggerrd   ra   rl   r   __all__r2   r2   r2   r9   <module>   s    8
  
e