



"""simple docstring"""






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 (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


lowerCAmelCase__        =				logging.get_logger(__name__)


if is_vision_available():
   import PIL






class        __snake_case       (	_UpperCAmelCase):
  snake_case__				:   Any  			=						['pixel_values']




  def __init__( self     :						Union[str, Any]						,					__lowerCAmelCase     :						Optional[Any] = True						,					__lowerCAmelCase     :						Optional[int] = None						,					__lowerCAmelCase     :						str = PILImageResampling.BICUBIC						,					__lowerCAmelCase     :						List[str] = True						,					__lowerCAmelCase     :						Union[str, Any] = None						,					__lowerCAmelCase     :						Optional[int] = True						,					__lowerCAmelCase     :						Optional[int] = 1 / 2_5_5						,					__lowerCAmelCase     :						List[str] = True						,					__lowerCAmelCase     :						Any = None						,					__lowerCAmelCase     :						str = None						,					__lowerCAmelCase     :						Optional[int] = True						,					**__lowerCAmelCase     :						int						,					):






         """simple docstring"""






         super().__init__(**SCREAMING_SNAKE_CASE_		)
         _lowerCamelCase						:				int    			= size if size is not None else {'shortest_edge': 2_2_4}
         _lowerCamelCase						:				Tuple    			= get_size_dict(SCREAMING_SNAKE_CASE_						,					default_to_square=SCREAMING_SNAKE_CASE_		)
         _lowerCamelCase						:				List[Any]    			= crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
         _lowerCamelCase						:				Any    			= get_size_dict(SCREAMING_SNAKE_CASE_						,					default_to_square=SCREAMING_SNAKE_CASE_						,					param_name='''crop_size'''		)

         _lowerCamelCase						:				str    			= do_resize
         _lowerCamelCase						:				Optional[Any]    			= size
         _lowerCamelCase						:				str    			= resample
         _lowerCamelCase						:				Union[str, Any]    			= do_center_crop
         _lowerCamelCase						:				int    			= crop_size
         _lowerCamelCase						:				Dict    			= do_rescale
         _lowerCamelCase						:				Any    			= rescale_factor
         _lowerCamelCase						:				Any    			= do_normalize
         _lowerCamelCase						:				Tuple    			= image_mean if image_mean is not None else OPENAI_CLIP_MEAN
         _lowerCamelCase						:				List[Any]    			= image_std if image_std is not None else OPENAI_CLIP_STD
         _lowerCamelCase						:				List[Any]    			= do_convert_rgb




  def 						SCREAMING_SNAKE_CASE				( self     :						Optional[Any]						,					__lowerCAmelCase     :						Dict						,					__lowerCAmelCase     :						Tuple						,					__lowerCAmelCase     :						Union[str, Any] = PILImageResampling.BICUBIC						,					__lowerCAmelCase     :						int = None						,					**__lowerCAmelCase     :						List[str]						,					):






         """simple docstring"""






         _lowerCamelCase						:				Union[str, Any]    			= get_size_dict(SCREAMING_SNAKE_CASE_						,					default_to_square=SCREAMING_SNAKE_CASE_		)
         if "shortest_edge" not in size:
                raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''		)
         _lowerCamelCase						:				List[str]    			= get_resize_output_image_size(SCREAMING_SNAKE_CASE_						,					size=size['''shortest_edge''']						,					default_to_square=SCREAMING_SNAKE_CASE_		)
         return resize(SCREAMING_SNAKE_CASE_						,					size=SCREAMING_SNAKE_CASE_						,					resample=SCREAMING_SNAKE_CASE_						,					data_format=SCREAMING_SNAKE_CASE_						,					**SCREAMING_SNAKE_CASE_		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Optional[Any]						,					__lowerCAmelCase     :						Union[str, Any]						,					__lowerCAmelCase     :						Optional[Any]						,					__lowerCAmelCase     :						Union[str, Any] = None						,					**__lowerCAmelCase     :						Tuple						,					):






         """simple docstring"""






         _lowerCamelCase						:				Tuple    			= get_size_dict(SCREAMING_SNAKE_CASE_		)
         if "height" not in size or "width" not in size:
                raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''		)
         return center_crop(SCREAMING_SNAKE_CASE_						,					size=(size['''height'''], size['''width'''])						,					data_format=SCREAMING_SNAKE_CASE_						,					**SCREAMING_SNAKE_CASE_		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Optional[int]						,					__lowerCAmelCase     :						Dict						,					__lowerCAmelCase     :						str						,					__lowerCAmelCase     :						Any = None						,					**__lowerCAmelCase     :						Dict						,					):






         """simple docstring"""






         return rescale(SCREAMING_SNAKE_CASE_						,					scale=SCREAMING_SNAKE_CASE_						,					data_format=SCREAMING_SNAKE_CASE_						,					**SCREAMING_SNAKE_CASE_		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Union[str, Any]						,					__lowerCAmelCase     :						Optional[Any]						,					__lowerCAmelCase     :						List[Any]						,					__lowerCAmelCase     :						Optional[int]						,					__lowerCAmelCase     :						List[Any] = None						,					**__lowerCAmelCase     :						Any						,					):






         """simple docstring"""






         return normalize(SCREAMING_SNAKE_CASE_						,					mean=SCREAMING_SNAKE_CASE_						,					std=SCREAMING_SNAKE_CASE_						,					data_format=SCREAMING_SNAKE_CASE_						,					**SCREAMING_SNAKE_CASE_		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Optional[int]						,					__lowerCAmelCase     :						Optional[Any]						,					__lowerCAmelCase     :						int = None						,					__lowerCAmelCase     :						str = None						,					__lowerCAmelCase     :						Tuple = None						,					__lowerCAmelCase     :						int = None						,					__lowerCAmelCase     :						str = None						,					__lowerCAmelCase     :						Union[str, Any] = None						,					__lowerCAmelCase     :						Any = None						,					__lowerCAmelCase     :						Optional[int] = None						,					__lowerCAmelCase     :						Any = None						,					__lowerCAmelCase     :						Union[str, Any] = None						,					__lowerCAmelCase     :						int = None						,					__lowerCAmelCase     :						str = None						,					__lowerCAmelCase     :						str = ChannelDimension.FIRST						,					**__lowerCAmelCase     :						List[Any]						,					):






         """simple docstring"""






         _lowerCamelCase						:				Optional[Any]    			= do_resize if do_resize is not None else self.do_resize
         _lowerCamelCase						:				Union[str, Any]    			= size if size is not None else self.size
         _lowerCamelCase						:				Any    			= get_size_dict(SCREAMING_SNAKE_CASE_						,					param_name='''size'''						,					default_to_square=SCREAMING_SNAKE_CASE_		)
         _lowerCamelCase						:				int    			= resample if resample is not None else self.resample
         _lowerCamelCase						:				Tuple    			= do_center_crop if do_center_crop is not None else self.do_center_crop
         _lowerCamelCase						:				Tuple    			= crop_size if crop_size is not None else self.crop_size
         _lowerCamelCase						:				Tuple    			= get_size_dict(SCREAMING_SNAKE_CASE_						,					param_name='''crop_size'''						,					default_to_square=SCREAMING_SNAKE_CASE_		)
         _lowerCamelCase						:				Dict    			= do_rescale if do_rescale is not None else self.do_rescale
         _lowerCamelCase						:				Union[str, Any]    			= rescale_factor if rescale_factor is not None else self.rescale_factor
         _lowerCamelCase						:				List[str]    			= do_normalize if do_normalize is not None else self.do_normalize
         _lowerCamelCase						:				int    			= image_mean if image_mean is not None else self.image_mean
         _lowerCamelCase						:				Dict    			= image_std if image_std is not None else self.image_std
         _lowerCamelCase						:				List[str]    			= do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

         _lowerCamelCase						:				int    			= make_list_of_images(SCREAMING_SNAKE_CASE_		)

         if not valid_images(SCREAMING_SNAKE_CASE_		):
                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_center_crop and crop_size is None:
                raise ValueError('''Crop size must be specified if do_center_crop is True.'''		)

         if do_rescale and rescale_factor is None:
                raise ValueError('''Rescale factor must be specified if do_rescale 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.'''		)

         # PIL RGBA images are converted to RGB
         if do_convert_rgb:
                _lowerCamelCase						:				Union[str, Any]    			= [convert_to_rgb(SCREAMING_SNAKE_CASE_		) for image in images]

         # All transformations expect numpy arrays.
         _lowerCamelCase						:				List[str]    			= [to_numpy_array(SCREAMING_SNAKE_CASE_		) for image in images]

         if do_resize:
                _lowerCamelCase						:				Any    			= [self.resize(image=SCREAMING_SNAKE_CASE_						,					size=SCREAMING_SNAKE_CASE_						,					resample=SCREAMING_SNAKE_CASE_		) for image in images]

         if do_center_crop:
                _lowerCamelCase						:				Optional[int]    			= [self.center_crop(image=SCREAMING_SNAKE_CASE_						,					size=SCREAMING_SNAKE_CASE_		) for image in images]

         if do_rescale:
                _lowerCamelCase						:				str    			= [self.rescale(image=SCREAMING_SNAKE_CASE_						,					scale=SCREAMING_SNAKE_CASE_		) for image in images]

         if do_normalize:
                _lowerCamelCase						:				Optional[Any]    			= [self.normalize(image=SCREAMING_SNAKE_CASE_						,					mean=SCREAMING_SNAKE_CASE_						,					std=SCREAMING_SNAKE_CASE_		) for image in images]

         _lowerCamelCase						:				Dict    			= [to_channel_dimension_format(SCREAMING_SNAKE_CASE_						,					SCREAMING_SNAKE_CASE_		) for image in images]

         _lowerCamelCase						:				Optional[Any]    			= {'pixel_values': images}
         return BatchFeature(data=SCREAMING_SNAKE_CASE_						,					tensor_type=SCREAMING_SNAKE_CASE_		)






'''simple docstring'''



from importlib import import_module

from .logging import get_logger


A__		:					str												=  get_logger(__name__)





class    UpperCAmelCase_  :





    """simple docstring"""






    def __init__(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=None	)				->     List[Any]:
         __lowerCamelCase   :	List[str]								=		attrs or []
         if module is not None:
              for key in module.__dict__:
                   if key in attrs or not key.startswith('__'	):
                        setattr(self			,     SCREAMING_SNAKE_CASE_			,     getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)	)
         __lowerCamelCase   :	Optional[int]								=		module._original_module if isinstance(SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj	) else module







class    UpperCAmelCase_  :





    """simple docstring"""






    lowerCamelCase  :					Tuple							     =			[]







    def __init__(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=None	)				->     Union[str, Any]:
         __lowerCamelCase   :	Optional[int]								=		obj
         __lowerCamelCase   :	List[Any]								=		target
         __lowerCamelCase   :	Union[str, Any]								=		new
         __lowerCamelCase   :	Union[str, Any]								=		target.split('.'	)[0]
         __lowerCamelCase   :	Dict								=		{}
         __lowerCamelCase   :	Dict								=		attrs or []







    def __enter__(							self	)				->     Optional[int]:
         *__lowerCamelCase				,       __lowerCamelCase   :	int								=		self.target.split('.'	)

         # Patch modules:
         # it's used to patch attributes of submodules like "os.path.join";
         # in this case we need to patch "os" and "os.path"

         for i in range(len(SCREAMING_SNAKE_CASE_	)	):
              try:
                   __lowerCamelCase   :	Optional[int]								=		import_module('.'.join(submodules[: i + 1]	)	)
              except ModuleNotFoundError:
                   continue
              # We iterate over all the globals in self.obj in case we find "os" or "os.path"
              for attr in self.obj.__dir__():
                   __lowerCamelCase   :	List[Any]								=		getattr(self.obj			,     SCREAMING_SNAKE_CASE_	)
                   # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
                   # This allows to patch renamed modules like "from os import path as ospath".
                   if obj_attr is submodule or (
                       (isinstance(SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj	) and obj_attr._original_module is submodule)
                   ):
                        __lowerCamelCase   :	Optional[Any]								=		obj_attr
                        # patch at top level
                        setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj(SCREAMING_SNAKE_CASE_			,     attrs=self.attrs	)	)
                        __lowerCamelCase   :	str								=		getattr(self.obj			,     SCREAMING_SNAKE_CASE_	)
                        # construct lower levels patches
                        for key in submodules[i + 1 :]:
                             setattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj(getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)			,     attrs=self.attrs	)	)
                             __lowerCamelCase   :	List[Any]								=		getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)
                        # finally set the target attribute
                        setattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     self.new	)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

         if submodules:  # if it's an attribute of a submodule like "os.path.join"
              try:
                   __lowerCamelCase   :	Union[str, Any]								=		getattr(import_module('.'.join(SCREAMING_SNAKE_CASE_	)	)			,     SCREAMING_SNAKE_CASE_	)
              except (AttributeError, ModuleNotFoundError):
                   return
              # We iterate over all the globals in self.obj in case we find "os.path.join"
              for attr in self.obj.__dir__():
                   # We don't check for the name of the global, but rather if its value *is* "os.path.join".
                   # This allows to patch renamed attributes like "from os.path import join as pjoin".
                   if getattr(self.obj			,     SCREAMING_SNAKE_CASE_	) is attr_value:
                        __lowerCamelCase   :	Optional[int]								=		getattr(self.obj			,     SCREAMING_SNAKE_CASE_	)
                        setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     self.new	)
         elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
              __lowerCamelCase   :	List[Any]								=		globals()['__builtins__'][target_attr]
              setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     self.new	)
         else:
              raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.'	)







    def __exit__(							self			,     *SCREAMING_SNAKE_CASE_	)				->     Optional[Any]:
         for attr in list(self.original	):
              setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     self.original.pop(SCREAMING_SNAKE_CASE_	)	)







    def       lowercase_				(							self	)				->     Optional[int]:
         self.__enter__()
         self._active_patches.append(self	)







    def       lowercase_				(							self	)				->     str:
         try:
              self._active_patches.remove(self	)
         except ValueError:
              # If the patch hasn't been started this will fail
              return None

         return self.__exit__()






