
     `i^                        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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"  e j#        e$          Z% e"            rddl&Z& G d
 de          Z'dgZ(dS )z!Image processor class for Nougat.    )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_flat_list_of_imagesto_numpy_arrayvalid_imagesvalidate_preprocess_arguments)
TensorTypefilter_out_non_signature_kwargslogging)is_vision_availablec            %       h    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Zdej        fdZd Z	 	 	 d$dej        dedee         deee
ef                  dej        f
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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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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 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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#            Z! x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                 6    t                      j        di | ||nddd}t          |          }|| _        || _        || _        || _        || _        || _        || _	        || _
        |	| _        |
| _        ||nt          | _        ||n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__s                 /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/nougat/image_processing_nougat.pyr3   zNougatImageProcessor.__init__[   s      	""6"""'ttc-J-JT"","	 ("4$,((2(>**DY&/&;AU    imagec                     t          j        t          j        |                    }|ddddgf         }|                    ddd          }|S )zGThis is a reimplementation of a findNonZero function equivalent to cv2.N   r      )npcolumn_stacknonzeroreshape)r4   r9   non_zero_indicesidxvecs       r7   python_find_non_zeroz)NougatImageProcessor.python_find_non_zero}   sL    ?2:e+<+<==!!!!aV),Aq))r8   c                    t          j        |d                              t                    }t          j        |d                              t                    }|d         |d         }}|d         |z
  dz   }|d         |z
  dz   }||||fS )zHThis is a reimplementation of a BoundingRect function equivalent to cv2.r   r;   )axisr   r;   )r>   minastypeintmax)r4   coordinates
min_values
max_valuesx_miny_minr0   r/   s           r7   python_bounding_rectz)NougatImageProcessor.python_bounding_rect   s    VKf555<<SAA
VKf555<<SAA
!!}jmu1%)A&*eUF**r8      gray_thresholddata_formatinput_data_formatc                 @   |t          |          }t          ||          }t          j        |                    d                                        t          j                  }|                                }|                                }||k    rFt          j        |          }t          ||t          j                  }|t          |||          n|}|S ||z
  ||z
  z  dz  }||k     }|                     |          }	|                     |	          \  }
}}}|                    |
||
|z   ||z   f          }t          j        |                              t          j                  }t          ||t          j                  }|t          |||          n|}|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.ndarray`):
                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rU   L   )r   r   r>   arrayconvertrI   uint8rK   rH   r   r   LASTrD   rQ   crop)r4   r9   rS   rT   rU   datamax_valmin_valgraycoordsrO   rP   r0   r/   s                 r7   crop_marginz NougatImageProcessor.crop_margin   s   , $ >u E EU6GHHHxc**++2228<<((**((**gHUOOE/7HJZJ_``E * ,E;@QRRR 
 Lw7W#45;n$**400&*&?&?&G&G#ueV

E5%%-HII&&rx00+E3DFVF[\\ S^Ri'{<MNNNot 	 r8   c                 f   t          ||          \  }}|d         |d         }}|t          |          }|t          j        k    rd}	n%|t          j        k    rd}	nt          d|           ||k     r||k    s||k    r||k     rt          j        |d|		          }|t          |||
          }|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.
        channel_dimr/   r0   NrF   )r;   r=   zUnsupported data format: r   )axesinput_channel_dim)	r   r   r   r]   FIRST
ValueErrorr>   rot90r   )
r4   r9   r#   rT   rU   input_heightinput_widthoutput_heightoutput_widthrot_axess
             r7   align_long_axisz$NougatImageProcessor.align_long_axis   s    . %35FW$X$X$X!k&*8nd7m|$ >u E E 0 555HH"2"888HHL9JLLMMM=(([<-G-G=(([<-G-GHUAH555E"/{VghhhEr8   c                     |d         |d         }}t          ||          \  }}||z
  }	||z
  }
|
dz  }|	dz  }|
|z
  }|	|z
  }||f||ff}t          ||||          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   rf   r=   )rT   rU   )r   r
   )r4   r9   r#   rT   rU   rp   rq   rn   ro   delta_widthdelta_heightpad_toppad_left
pad_bottom	pad_rightpaddings                   r7   	pad_imagezNougatImageProcessor.pad_image   s    ( '+8nd7m|$25FW$X$X$X!k"[0$|3!#!#!G+
(*	Z(8Y*?@5'{N_````r8   c           	      >   t          ||          \  }}|d         |d         }
}	t          ||	          }t          ||
          }||k    r||k    r|S ||k    rt          ||z  |z            }n||k    rt          ||z  |z            }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.
        rf   r/   r0   g       @)r#   r$   reducing_gaprT   rU   )r   rH   rJ   r   )r4   r9   r#   r$   rT   rU   r5   rn   ro   rp   rq   r/   r0   s                r7   	thumbnailzNougatImageProcessor.thumbnail  s    2 %35FW$X$X$X!k&*8nd7m| \=11K..\!!e{&:&:L+%%f,|;<<EE<''-;<<F
%#/
 
 
 
 	
r8   c                     t          |          }t          |d         |d                   }t          ||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#   default_to_squarerU   )r#   r$   rT   rU   )r   rH   r	   r   )
r4   r9   r#   r$   rT   rU   r5   shortest_edgeoutput_sizeresized_images
             r7   r   zNougatImageProcessor.resizeH  s    0 T""DNDM::2Rc
 
 
 
#/
 
 
 
 r8   imagesreturn_tensorsc           
         
 ||n j         }||n j        }n j        n j        ||n j        }||n j        }||n j        }|	|	n j        }	

n j        
||n j	        }n j
        n j        t          |          }t          |          st          d          t          |	
||           d |D             }|	r/t!          |d                   rt"                              d           t'          |d                   |r fd|D             }|r fd|D             }|r fd	|D             }|r fd
|D             }|r fd|D             }|	r
 fd|D             }|r fd|D             }fd|D             }d|i}t)          ||          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"   r#   r$   c                 ,    g | ]}t          |          S r1   )r   ).0r9   s     r7   
<listcomp>z3NougatImageProcessor.preprocess.<locals>.<listcomp>  s     <<<E.''<<<r8   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                 >    g | ]}                     |           S )rW   )rd   )r   r9   rU   r4   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  s.    gggW\d&&u@Q&RRgggr8   c                 @    g | ]}                     |           S ))r#   rU   )rs   r   r9   rU   r4   r#   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  s0    vvvfkd**5tO`*aavvvr8   c                 B    g | ]}                     |           S ))r9   r#   r$   rU   )r   )r   r9   rU   r$   r4   r#   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  s>        %dXYjkk  r8   c                 @    g | ]}                     |           S )r9   r#   rU   )r   r   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  -    vvvfkdnn5tO`naavvvr8   c                 @    g | ]}                     |           S r   )r|   r   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  r   r8   c                 @    g | ]}                     |           S ))r9   scalerU   )rescale)r   r9   rU   r)   r4   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  s<        5Rcdd  r8   c                 B    g | ]}                     |           S ))r9   meanstdrU   )	normalize)r   r9   r+   r,   rU   r4   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>  s>        U^opp  r8   c                 4    g | ]}t          |           S )ri   )r   )r   r9   rT   rU   s     r7   r   z3NougatImageProcessor.preprocess.<locals>.<listcomp>   s7     
 
 
ej'{N_```
 
 
r8   r    )r_   tensor_type)r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r   r   rl   r   r   loggerwarning_oncer   r   )r4   r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r   rT   rU   r_   s   `   ``    ` `` `` r7   
preprocesszNougatImageProcessor.preprocesso  sL   N ,:+E4K^!*!6IIDN	'ttTY'388'3'?||TEV3E3Q//W[Wn!-4;#-#9ZZt
+9+E4K^'3'?||TEV#-#9ZZt
!*!6IIDN	)&11F## 	:   	&!)%!		
 		
 		
 		
 =<V<<< 	/&)44 	s  
 $ >vay I I 	hggggg`fgggF 	wvvvvvvouvvvF 	      #  F
  	wvvvvvvouvvvF 	wvvvvvvouvvvF 	     #  F
  	      #  F

 
 
 
 
nt
 
 
 '>BBBBr8   )rR   NN)NN)#__name__
__module____qualname____doc__model_input_namesr   BILINEARboolr   dictstrrJ   r   floatlistr3   r>   ndarrayrD   rQ   r   rd   rs   r|   BICUBICr   r   r   rk   r   r   PILImager   __classcell__)r6   s   @r7   r   r   6   s          D ((  $)-'9'B!#(,3!:>9= V  V V  V tCH~&	 V
 % V  V ! V  V  V c5j) V  V U5$u+#567 V E%e"456 V 
 V  V  V  V  V  VD"*    + + + "26DH2 2z2 2 ./	2
 $E#/?*?$@A2 
2 2 2 2r ?CDH- -z- 38n- eC)9$9:;	-
 $E#/?*?$@A- 
- - - -f ?CDH!a !az!a 38n!a eC)9$9:;	!a
 $E#/?*?$@A!a 
!a !a !a !aP (:'A>BDH0
 0
z0
 38n0
 %	0

 eC)9$9:;0
 $E#/?*?$@A0
 
0
 0
 0
 0
n (:'A>BDH% %z% 38n% %	%
 eC)9$9:;% $E#/?*?$@A% 
% % % %N %$&& *.$()-15'+-1!%%)6:'+:>9=;?2B2HDH#UC UCUC !UC D>	UC
 tCH~&UC -.UC tnUC %TNUC UC TNUC !sEz!23UC tnUC U5$u+#567UC E%e"456UC !sJ!78UC  ./!UC" $E#/?*?$@A#UC$ 
%UC UC UC '&UC UC UC UC UCr8   r   ))r   typingr   r   numpyr>   image_processing_utilsr   r   r   image_transformsr	   r
   r   r   r   image_utilsr   r   r   r   r   r   r   r   r   r   r   r   utilsr   r   r   utils.import_utilsr   
get_loggerr   r   r   r   __all__r1   r8   r7   <module>r      s   ( ' " " " " " " " "     U U U U U U U U U U                                         J I I I I I I I I I 5 5 5 5 5 5 
	H	%	%  JJJOC OC OC OC OC- OC OC OCd "
"r8   