





from importlib import import_module

from .logging import get_logger


__UpperCAmelCase       :   Dict				       =							get_logger(__name__)







class     __snake_case       :





       '''simple docstring'''







       def __init__(  self :    Dict							,				A :    List[Any]							,				A :    List[str]=None		):
         __snake_case:						int   =						attrs or []
         if module is not None:
           for key in module.__dict__:
             if key in attrs or not key.startswith("""__"""		):
               setattr(self							,				A							,				getattr(A							,				A		)		)
         __snake_case:						str   =						module._original_module if isinstance(A							,				_PatchedModuleObj		) else module







class     __snake_case       :





       '''simple docstring'''







       lowerCAmelCase__      		=     []




       def __init__(  self :    str							,				A :    str							,				A :    Any							,				A :    int							,				A :    Optional[int]=None		):
         __snake_case:						Tuple   =						obj
         __snake_case:						int   =						target
         __snake_case:						str   =						new
         __snake_case:						Union[str, Any]   =						target.split("""."""		)[0]
         __snake_case:						List[Any]   =						{}
         __snake_case:						List[Any]   =						attrs or []




       def __enter__(  self :    Any		):
         __snake_case:						Any   =						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(A		)		):
           try:
             __snake_case:						Optional[Any]   =						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__():
             __snake_case:						List[Any]   =						getattr(self.obj							,				A		)
             # 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(A							,				_PatchedModuleObj		) and obj_attr._original_module is submodule)
             ):
               __snake_case:						str   =						obj_attr
               # patch at top level
               setattr(self.obj							,				A							,				_PatchedModuleObj(A							,				attrs=self.attrs		)		)
               __snake_case:						List[Any]   =						getattr(self.obj							,				A		)
               # construct lower levels patches
               for key in submodules[i + 1 :]:
                 setattr(A							,				A							,				_PatchedModuleObj(getattr(A							,				A							,				A		)							,				attrs=self.attrs		)		)
                 __snake_case:						int   =						getattr(A							,				A		)
               # finally set the target attribute
               setattr(A							,				A							,				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:
             __snake_case:						Dict   =						getattr(import_module(""".""".join(A		)		)							,				A		)
           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							,				A		) is attr_value:
               __snake_case:						Dict   =						getattr(self.obj							,				A		)
               setattr(self.obj							,				A							,				self.new		)
         elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
           __snake_case:						Tuple   =						globals()['''__builtins__'''][target_attr]
           setattr(self.obj							,				A							,				self.new		)
         else:
           raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''		)




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




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         self.__enter__()
         self._active_patches.append(self		)






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

         return self.__exit__()













from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCAmelCase_     							= logging.get_logger(__name__)






class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   a						:							str   		=		["pixel_values"]




   def __init__(    self,		__magic_name__ = True,		__magic_name__ = 32,		__magic_name__=PILImageResampling.BILINEAR,		__magic_name__ = True,		**__magic_name__,		) ->      None:






       """simple docstring"""
       UpperCamelCase__							:				int          =      do_resize
       UpperCamelCase__							:				Tuple          =      do_rescale
       UpperCamelCase__							:				Any          =      size_divisor
       UpperCamelCase__							:				List[Any]          =      resample
       super().__init__(**__magic_name__							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__ = None,		**__magic_name__							) ->      np.ndarray:






       """simple docstring"""
       UpperCamelCase__   ,UpperCamelCase__							:				List[Any]          =      get_image_size(__magic_name__							)
       # Rounds the height and width down to the closest multiple of size_divisor
       UpperCamelCase__							:				Any          =      height // size_divisor * size_divisor
       UpperCamelCase__							:				Optional[int]          =      width // size_divisor * size_divisor
       UpperCamelCase__							:				str          =      resize(__magic_name__,		(new_h, new_w),		resample=__magic_name__,		data_format=__magic_name__,		**__magic_name__							)
       return image




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__ = None,		**__magic_name__							) ->      np.ndarray:






       """simple docstring"""
       return rescale(image=__magic_name__,		scale=__magic_name__,		data_format=__magic_name__,		**__magic_name__							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__=None,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = ChannelDimension.FIRST,		**__magic_name__,		) ->      BatchFeature:






       """simple docstring"""
       UpperCamelCase__							:				str          =      do_resize if do_resize is not None else self.do_resize
       UpperCamelCase__							:				Union[str, Any]          =      do_rescale if do_rescale is not None else self.do_rescale
       UpperCamelCase__							:				Any          =      size_divisor if size_divisor is not None else self.size_divisor
       UpperCamelCase__							:				str          =      resample if resample is not None else self.resample

       if do_resize and size_divisor is None:
           raise ValueError('''size_divisor is required for resizing'''							)

       UpperCamelCase__							:				Union[str, Any]          =      make_list_of_images(__magic_name__							)

       if not valid_images(__magic_name__							):
           raise ValueError('''Invalid image(s)'''							)

       # All transformations expect numpy arrays.
       UpperCamelCase__							:				Optional[Any]          =      [to_numpy_array(__magic_name__							) for img in images]

       if do_resize:
           UpperCamelCase__							:				str          =      [self.resize(__magic_name__,		size_divisor=__magic_name__,		resample=__magic_name__							) for image in images]

       if do_rescale:
           UpperCamelCase__							:				List[Any]          =      [self.rescale(__magic_name__,		scale=1 / 255							) for image in images]

       UpperCamelCase__							:				Optional[Any]          =      [to_channel_dimension_format(__magic_name__,		__magic_name__							) for image in images]

       UpperCamelCase__							:				Tuple          =      {'''pixel_values''': images}
       return BatchFeature(data=__magic_name__,		tensor_type=__magic_name__							)

