


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


SCREAMING_SNAKE_CASE				:						int			   = logging.get_logger(__name__)


if is_vision_available():
   import PIL






class    UpperCamelCase    (						UpperCamelCase__   ):


   '''simple docstring'''







   lowercase    :		Union[str, Any]	  =["""pixel_values"""]
   def __init__(   self      ,							UpperCamelCase_ = True      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = PILImageResampling.BILINEAR      ,							UpperCamelCase_ = True      ,							UpperCamelCase_ = False      ,							UpperCamelCase_ = True      ,							UpperCamelCase_ = True      ,							UpperCamelCase_ = 1 / 255      ,							UpperCamelCase_ = True      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							**UpperCamelCase_      ,							):
        super().__init__(**__A						)

        lowercase_				:List[str]       			=				size if size is not None else {'''height''': 2560, '''width''': 1920}
        if isinstance(__A      ,							(tuple, list)						):
             # The previous feature extractor size parameter was in (width, height) format
             lowercase_				:Optional[int]       			=				size[::-1]
        lowercase_				:str       			=				get_size_dict(__A						)

        lowercase_				:Optional[int]       			=				do_resize
        lowercase_				:Optional[Any]       			=				size
        lowercase_				:str       			=				resample
        lowercase_				:Optional[int]       			=				do_thumbnail
        lowercase_				:Optional[int]       			=				do_align_long_axis
        lowercase_				:Optional[int]       			=				do_pad
        lowercase_				:Any       			=				do_rescale
        lowercase_				:int       			=				rescale_factor
        lowercase_				:int       			=				do_normalize
        lowercase_				:List[Any]       			=				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        lowercase_				:Union[str, Any]       			=				image_std if image_std is not None else IMAGENET_STANDARD_STD
   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_ = None						):
        lowercase_			,					lowercase_				:List[Any]       			=				get_image_size(__A						)
        lowercase_			,					lowercase_				:Dict       			=				size['''height'''], size['''width''']

        if (output_width < output_height and input_width > input_height) or (
            output_width > output_height and input_width < input_height
        ):
             lowercase_				:Union[str, Any]       			=				np.rotaa(__A      ,							3						)

        if data_format is not None:
             lowercase_				:Tuple       			=				to_channel_dimension_format(__A      ,							__A						)

        return image
   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_ = False      ,							UpperCamelCase_ = None      ,							):
        lowercase_			,					lowercase_				:Optional[Any]       			=				size['''height'''], size['''width''']
        lowercase_			,					lowercase_				:List[str]       			=				get_image_size(__A						)

        lowercase_				:str       			=				output_width - input_width
        lowercase_				:Union[str, Any]       			=				output_height - input_height

        if random_padding:
             lowercase_				:Tuple       			=				np.random.randint(low=0      ,							high=delta_height + 1						)
             lowercase_				:str       			=				np.random.randint(low=0      ,							high=delta_width + 1						)
        else:
             lowercase_				:Tuple       			=				delta_height // 2
             lowercase_				:Optional[int]       			=				delta_width // 2

        lowercase_				:Any       			=				delta_height - pad_top
        lowercase_				:Optional[int]       			=				delta_width - pad_left

        lowercase_				:Dict       			=				((pad_top, pad_bottom), (pad_left, pad_right))
        return pad(__A      ,							__A      ,							data_format=__A						)
   def 						UpperCamelCase     (   self      ,							*UpperCamelCase_      ,							**UpperCamelCase_						):
        logger.info('''pad is deprecated and will be removed in version 4.27. Please use pad_image instead.'''						)
        return self.pad_image(*__A      ,							**__A						)
   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_ = PILImageResampling.BICUBIC      ,							UpperCamelCase_ = None      ,							**UpperCamelCase_      ,							):
        lowercase_			,					lowercase_				:Optional[Any]       			=				get_image_size(__A						)
        lowercase_			,					lowercase_				:Optional[Any]       			=				size['''height'''], size['''width''']

        # We always resize to the smallest of either the input or output size.
        lowercase_				:Dict       			=				min(__A      ,							__A						)
        lowercase_				:Optional[int]       			=				min(__A      ,							__A						)

        if height == input_height and width == input_width:
             return image

        if input_height > input_width:
             lowercase_				:Optional[int]       			=				int(input_width * height / input_height						)
        elif input_width > input_height:
             lowercase_				:List[Any]       			=				int(input_height * width / input_width						)

        return resize(
            __A      ,							size=(height, width)      ,							resample=__A      ,							reducing_gap=2.0      ,							data_format=__A      ,							**__A						)
   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_ = PILImageResampling.BICUBIC      ,							UpperCamelCase_ = None      ,							**UpperCamelCase_      ,							):
        lowercase_				:str       			=				get_size_dict(__A						)
        lowercase_				:Dict       			=				min(size['''height''']      ,							size['''width''']						)
        lowercase_				:Optional[Any]       			=				get_resize_output_image_size(__A      ,							size=__A      ,							default_to_square=__A						)
        lowercase_				:Optional[int]       			=				resize(__A      ,							size=__A      ,							resample=__A      ,							data_format=__A      ,							**__A						)
        return resized_image
   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_ = None      ,							**UpperCamelCase_      ,							):
        return rescale(__A      ,							scale=__A      ,							data_format=__A      ,							**__A						)
   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_      ,							UpperCamelCase_ = None      ,							**UpperCamelCase_      ,							):
        return normalize(__A      ,							mean=__A      ,							std=__A      ,							data_format=__A      ,							**__A						)




   def 						UpperCamelCase     (   self      ,							UpperCamelCase_      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = False      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = None      ,							UpperCamelCase_ = ChannelDimension.FIRST      ,							**UpperCamelCase_      ,							):
        lowercase_				:Any       			=				do_resize if do_resize is not None else self.do_resize
        lowercase_				:int       			=				size if size is not None else self.size
        if isinstance(__A      ,							(tuple, list)						):
             # Previous feature extractor had size in (width, height) format
             lowercase_				:Tuple       			=				size[::-1]
        lowercase_				:Optional[int]       			=				get_size_dict(__A						)
        lowercase_				:int       			=				resample if resample is not None else self.resample
        lowercase_				:List[Any]       			=				do_thumbnail if do_thumbnail is not None else self.do_thumbnail
        lowercase_				:Union[str, Any]       			=				do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
        lowercase_				:Optional[Any]       			=				do_pad if do_pad is not None else self.do_pad
        lowercase_				:Tuple       			=				do_rescale if do_rescale is not None else self.do_rescale
        lowercase_				:Optional[int]       			=				rescale_factor if rescale_factor is not None else self.rescale_factor
        lowercase_				:Any       			=				do_normalize if do_normalize is not None else self.do_normalize
        lowercase_				:List[str]       			=				image_mean if image_mean is not None else self.image_mean
        lowercase_				:List[str]       			=				image_std if image_std is not None else self.image_std

        lowercase_				:List[Any]       			=				make_list_of_images(__A						)

        if not valid_images(__A						):
             raise ValueError(
                 '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                 '''torch.Tensor, tf.Tensor or jax.ndarray.'''						)

        if do_resize and size is None:
             raise ValueError('''Size must be specified if do_resize is True.'''						)

        if do_rescale and rescale_factor is None:
             raise ValueError('''Rescale factor must be specified if do_rescale is True.'''						)

        if do_pad and size is None:
             raise ValueError('''Size must be specified if do_pad is True.'''						)

        if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('''Image mean and std must be specified if do_normalize is True.'''						)

        # All transformations expect numpy arrays.
        lowercase_				:Optional[Any]       			=				[to_numpy_array(__A						) for image in images]

        if do_align_long_axis:
             lowercase_				:List[Any]       			=				[self.align_long_axis(__A      ,							size=__A						) for image in images]

        if do_resize:
             lowercase_				:str       			=				[self.resize(image=__A      ,							size=__A      ,							resample=__A						) for image in images]

        if do_thumbnail:
             lowercase_				:str       			=				[self.thumbnail(image=__A      ,							size=__A						) for image in images]

        if do_pad:
             lowercase_				:str       			=				[self.pad_image(image=__A      ,							size=__A      ,							random_padding=__A						) for image in images]

        if do_rescale:
             lowercase_				:Optional[Any]       			=				[self.rescale(image=__A      ,							scale=__A						) for image in images]

        if do_normalize:
             lowercase_				:Tuple       			=				[self.normalize(image=__A      ,							mean=__A      ,							std=__A						) for image in images]

        lowercase_				:int       			=				[to_channel_dimension_format(__A      ,							__A						) for image in images]

        lowercase_				:Tuple       			=				{'''pixel_values''': images}
        return BatchFeature(data=__A      ,							tensor_type=__A						)








import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin




class      UpperCamelCase_				(   UpperCamelCase__			):
							lowerCamelCase_							=    ["image_processor", "tokenizer"]
							lowerCamelCase_							=    "AutoImageProcessor"
							lowerCamelCase_							=    "AutoTokenizer"


							def __init__(							self			:Any							, __A			:List[str]=None							, __A			:Dict=None							, **__A			:List[str]						)      ->      List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					None
									if "feature_extractor" in kwargs:
											warnings.warn(
											    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
											    """ instead."""							, __A							, )
											SCREAMING_SNAKE_CASE__								=					kwargs.pop("""feature_extractor"""						)

									SCREAMING_SNAKE_CASE__								=					image_processor if image_processor is not None else feature_extractor
									if image_processor is None:
											raise ValueError("""You need to specify an `image_processor`."""						)
									if tokenizer is None:
											raise ValueError("""You need to specify a `tokenizer`."""						)

									super().__init__(__A							, __A						)
									SCREAMING_SNAKE_CASE__								=					self.image_processor
									SCREAMING_SNAKE_CASE__								=					False


							def __call__(							self			:List[str]							, *__A			:int							, **__A			:Optional[int]						)      ->      Optional[Any]:



									"""simple docstring"""



									if self._in_target_context_manager:
											return self.current_processor(*__A							, **__A						)

									SCREAMING_SNAKE_CASE__								=					kwargs.pop("""images"""							, __A						)
									SCREAMING_SNAKE_CASE__								=					kwargs.pop("""text"""							, __A						)
									if len(__A						) > 0:
											SCREAMING_SNAKE_CASE__								=					args[0]
											SCREAMING_SNAKE_CASE__								=					args[1:]

									if images is None and text is None:
											raise ValueError("""You need to specify either an `images` or `text` input to process."""						)

									if images is not None:
											SCREAMING_SNAKE_CASE__								=					self.image_processor(__A							, *__A							, **__A						)
									if text is not None:
											SCREAMING_SNAKE_CASE__								=					self.tokenizer(__A							, **__A						)

									if text is None:
											return inputs
									elif images is None:
											return encodings
									else:
											SCREAMING_SNAKE_CASE__								=					encodings["""input_ids"""]
											return inputs


							def    _snake_case     (							self			:Any							, *__A			:Optional[Any]							, **__A			:int						)      ->      List[Any]:



									"""simple docstring"""



									return self.tokenizer.batch_decode(*__A							, **__A						)


							def    _snake_case     (							self			:str							, *__A			:Optional[int]							, **__A			:List[Any]						)      ->      List[str]:



									"""simple docstring"""



									return self.tokenizer.decode(*__A							, **__A						)


							@contextmanager
							def    _snake_case     (							self			:Dict						)      ->      List[str]:



									"""simple docstring"""



									warnings.warn(
									    """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
									    """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
									    """your images inputs, or in a separate call."""						)
									SCREAMING_SNAKE_CASE__								=					True
									SCREAMING_SNAKE_CASE__								=					self.tokenizer
									yield
									SCREAMING_SNAKE_CASE__								=					self.image_processor
									SCREAMING_SNAKE_CASE__								=					False


							@property
							def    _snake_case     (							self			:List[str]						)      ->      int:



									"""simple docstring"""



									warnings.warn(
									    """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""							, __A							, )
									return self.image_processor_class


							@property
							def    _snake_case     (							self			:str						)      ->      List[Any]:



									"""simple docstring"""



									warnings.warn(
									    """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""							, __A							, )
									return self.image_processor