o
    Zh^                     @   s   d 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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" dd	l#m$Z$m%Z% e"&e'Z(e$ ra	 e% rhddl)Z)G d
d de	Z*dgZ+dS )z!Image processor class for Nougat.    )DictListOptionalUnionN   )BaseImageProcessorBatchFeatureget_size_dict)get_resize_output_image_sizepadresizeto_channel_dimension_formatto_pil_image)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STDChannelDimension
ImageInputPILImageResamplingget_image_size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logging)is_cv2_availableis_vision_availablec                %       s  e Zd ZdZdgZdddejddddddddfdeded	ee	e
ef  d
edede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df fddZdejfddZdd Z			d-dejdedee deee
ef  dejf
dd Z		d.dejd	e	e
ef deee
ef  deee
ef  dejf
d!d"Z		d.dejd	e	e
ef deee
ef  deee
ef  dejf
d#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%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'd(Ze 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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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 j!j!f"d+d,Z"  Z#S )/NougatImageProcessora	  
    Constructs a Nougat image processor.

    Args:
        do_crop_margin (`bool`, *optional*, defaults to `True`):
            Whether to crop the image margins.
        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": 896, "width": 672}`):
            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_thumbnail (`bool`, *optional*, defaults to `True`):
            Whether to resize the image using thumbnail method.
        do_align_long_axis (`bool`, *optional*, defaults to `False`):
            Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
        do_pad (`bool`, *optional*, defaults to `True`):
            Whether to pad the images to the largest image size in the batch.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
            parameter 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 the `rescale_factor` parameter in the
            `preprocess` method.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
        image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
            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 `IMAGENET_DEFAULT_STD`):
            Image standard deviation.
    pixel_valuesTNFgp?do_crop_margin	do_resizesizeresampledo_thumbnaildo_align_long_axisdo_pad
do_rescalerescale_factordo_normalize
image_mean	image_stdreturnc                    s   t  jdi | |d ur|nddd}t|}|| _|| _|| _|| _|| _|| _|| _	|| _
|	| _|
| _|d ur<|nt| _|d urH|| _d S t| _d S )Ni  i  )heightwidth )super__init__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-   kwargs	__class__r1   a/var/www/auris/lib/python3.10/site-packages/transformers/models/nougat/image_processing_nougat.pyr3   _   s   zNougatImageProcessor.__init__imagec                 C   s6   t t |}|ddddgf }|ddd}|S )zGThis is a reimplementation of a findNonZero function equivalent to cv2.N   r      )npZcolumn_stackZnonzeroZreshape)r4   r9   Znon_zero_indicesZidxvecr1   r1   r8   python_find_non_zero   s   z)NougatImageProcessor.python_find_non_zeroc                 C   sf   t j|ddt}t j|ddt}|d |d }}|d | d }|d | d }||||fS )zHThis is a reimplementation of a BoundingRect function equivalent to cv2.r   r:   )Zaxisr   r:   )r=   minastypeintmax)r4   ZcoordinatesZ
min_valuesZ
max_valuesx_miny_minr0   r/   r1   r1   r8   python_bounding_rect   s   z)NougatImageProcessor.python_bounding_rect   gray_thresholddata_formatinput_data_formatc                 C   s  |du rt |}t||d}t|dtj}| }| }||kr;t|}|dur7t	|||}|S |}|S || ||  d }||k }| 
|}	| |	\}
}}}||
||
| || f}t|tj}t	||tj}|durt	|||}|S |}|S )a  
        Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the
        threshold).

        Args:
            image (`np.array`):
                The image to be cropped.
            gray_threshold (`int`, *optional*, defaults to `200`)
                Value below which pixels are considered to be gray.
            data_format (`ChannelDimension`, *optional*):
                The channel dimension format of the output image. If unset, will use the inferred format from the
                input.
            input_data_format (`ChannelDimension`, *optional*):
                The channel dimension format of the input image. If unset, will use the inferred format from the input.
        NrJ   L   )r   r   r=   arrayconvertrA   Zuint8rC   r@   r   r>   rF   cropr   LAST)r4   r9   rH   rI   rJ   dataZmax_valZmin_valgrayZcoordsrD   rE   r0   r/   r1   r1   r8   crop_margin   s8   


z NougatImageProcessor.crop_marginc           
      C   s   t ||d\}}|d |d }}|du rt|}|tjkr!d}	n|tjkr)d}	ntd| ||k r8||ks@||krH||k rHtj|d|	d	}|durSt|||d
}|S )a  
        Align the long axis of the image to the longest axis of the specified size.

        Args:
            image (`np.ndarray`):
                The image to be aligned.
            size (`Dict[str, int]`):
                The size `{"height": h, "width": w}` to align the long axis to.
            data_format (`str` or `ChannelDimension`, *optional*):
                The data format of the output image. If unset, the same format as the input image is used.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.

        Returns:
            `np.ndarray`: The aligned image.
        Zchannel_dimr/   r0   Nr?   )r:   r<   zUnsupported data format: r   )ZaxesZinput_channel_dim)	r   r   r   rQ   FIRST
ValueErrorr=   Zrot90r   )
r4   r9   r$   rI   rJ   input_heightinput_widthoutput_heightoutput_widthZrot_axesr1   r1   r8   align_long_axis   s   

z$NougatImageProcessor.align_long_axisc                 C   sr   |d |d }}t ||d\}}|| }	|| }
|
d }|	d }|
| }|	| }||f||ff}t||||dS )a  
        Pad the image to the specified size at the top, bottom, left and right.

        Args:
            image (`np.ndarray`):
                The image to be padded.
            size (`Dict[str, int]`):
                The size `{"height": h, "width": w}` to pad the image to.
            data_format (`str` or `ChannelDimension`, *optional*):
                The data format of the output image. If unset, the same format as the input image is used.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        r/   r0   rU   r<   rI   rJ   )r   r   )r4   r9   r$   rI   rJ   r[   r\   rY   rZ   Zdelta_widthZdelta_heightpad_toppad_leftZ
pad_bottom	pad_rightpaddingr1   r1   r8   	pad_image   s   zNougatImageProcessor.pad_imagec                 K   s   t ||d\}}|d |d }	}
t||	}t||
}||kr%||kr%|S ||kr2t|| | }n||kr>t|| | }t|f||f|d||d|S )as  
        Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
        corresponding dimension of the specified size.

        Args:
            image (`np.ndarray`):
                The image to be resized.
            size (`Dict[str, int]`):
                The size `{"height": h, "width": w}` to resize the image to.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
                The resampling filter to use.
            data_format (`Optional[Union[str, ChannelDimension]]`, *optional*):
                The data format of the output image. If unset, the same format as the input image is used.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        rU   r/   r0   g       @)r$   r%   Zreducing_gaprI   rJ   )r   r@   rB   r   )r4   r9   r$   r%   rI   rJ   r5   rY   rZ   r[   r\   r/   r0   r1   r1   r8   	thumbnail  s*   

zNougatImageProcessor.thumbnailc           
      K   sH   t |}t|d |d }t||d|d}t|f||||d|}	|	S )a  
        Resizes `image` to `(height, width)` specified by `size` using the PIL library.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Size of the output image.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
                Resampling filter to use when resiizing the image.
            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.
        r/   r0   F)r$   Zdefault_to_squarerJ   )r$   r%   rI   rJ   )r	   r@   r
   r   )
r4   r9   r$   r%   rI   rJ   r5   Zshortest_edgeZoutput_sizeZresized_imager1   r1   r8   r   K  s    zNougatImageProcessor.resizeimagesreturn_tensorsc                    s*  |dur|nj }|dur|nj}durnjdur!nj|dur*|nj}|dur3|nj}|dur<|nj}|	durE|	nj}	durNnj|durW|nj	}dur`nj
durinjt|}t|sxtdt|	|||d
 dd |D }|	rt|d rtd du rt|d |rfdd|D }|rfd	d|D }|rˇfd
d|D }|r؇fdd|D }|rfdd|D }|	rfdd|D }|rfdd|D } fdd|D }d|i}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.
            do_crop_margin (`bool`, *optional*, defaults to `self.do_crop_margin`):
                Whether to crop the image margins.
            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 min(size["height"],
                size["width"]) 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_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
                Whether to resize the image using thumbnail method.
            do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
                Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
            do_pad (`bool`, *optional*, defaults to `self.do_pad`):
                Whether to pad the images to the largest image size in the batch.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image by the specified scale `rescale_factor`.
            rescale_factor (`int` or `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`):
                Image mean to use for normalization.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Image standard deviation to use for normalization.
            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.
                - Unset: defaults to 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.
        NzkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)
r)   r*   r+   r,   r-   r(   Zsize_divisibilityr#   r$   r%   c                 S   s   g | ]}t |qS r1   )r   .0r9   r1   r1   r8   
<listcomp>  s    z3NougatImageProcessor.preprocess.<locals>.<listcomp>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.c                    s   g | ]	}j | d qS )rK   )rT   rg   )rJ   r4   r1   r8   ri     s    c                       g | ]
}j | d qS ))r$   rJ   )r]   rg   rJ   r4   r$   r1   r8   ri         c                    s   g | ]}j | d qS ))r9   r$   r%   rJ   )r   rg   )rJ   r%   r4   r$   r1   r8   ri         c                    rj   )r9   r$   rJ   )rd   rg   rk   r1   r8   ri     rl   c                    rj   rn   )rc   rg   rk   r1   r8   ri     rl   c                    s   g | ]
}j | d qS ))r9   scalerJ   )Zrescalerg   )rJ   r*   r4   r1   r8   ri     s    c                    s   g | ]}j | d qS ))r9   meanZstdrJ   )	normalizerg   )r,   r-   rJ   r4   r1   r8   ri      rm   c                    s   g | ]	}t | d qS )rV   )r   rg   r^   r1   r8   ri     s    r!   )rR   Ztensor_type)r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r   r   rX   r   r   loggerZwarning_oncer   r   )r4   re   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   rf   rI   rJ   rR   r1   )rI   r,   r-   rJ   r%   r*   r4   r$   r8   
preprocessr  sz   GzNougatImageProcessor.preprocess)rG   NN)NN)$__name__
__module____qualname____doc__Zmodel_input_namesr   ZBILINEARboolr   r   strrB   r   floatr   r3   r=   rN   r>   rF   r   rT   Zndarrayr]   rc   ZBICUBICrd   r   r   rW   r   r   PILZImagers   __classcell__r1   r1   r6   r8   r    :   sN   "	

"
8

3

(

7

'	
r    ),rw   typingr   r   r   r   numpyr=   Zimage_processing_utilsr   r   r	   Zimage_transformsr
   r   r   r   r   Zimage_utilsr   r   r   r   r   r   r   r   r   r   r   r   utilsr   r   r   Zutils.import_utilsr   r   Z
get_loggerrt   rr   r{   r    __all__r1   r1   r1   r8   <module>   s$   8
   
V