

"""simple docstring"""





from importlib import import_module

from .logging import get_logger


_a       =							get_logger(__name__)




class 					_lowerCAmelCase  :







 """simple docstring"""







 def __init__(			self							:			Optional[int],					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			str=None	):
    __lowercase								=						attrs or []
    if module is not None:
       for key in module.__dict__:
          if key in attrs or not key.startswith("__"	):
             setattr(self,					UpperCAmelCase__,					getattr(UpperCAmelCase__,					UpperCAmelCase__	)	)
    __lowercase								=						module._original_module if isinstance(UpperCAmelCase__,					_PatchedModuleObj	) else module







class 					_lowerCAmelCase  :







 """simple docstring"""







 __UpperCAmelCase	:					Any   		=	[]


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


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


 def __exit__(			self							:			str,					*UpperCAmelCase__							:			Tuple	):
    for attr in list(self.original	):
       setattr(self.obj,					UpperCAmelCase__,					self.original.pop(UpperCAmelCase__	)	)


 def 					_lowercase (			self							:			Optional[int]	):
    self.__enter__()
    self._active_patches.append(self	)



 def 					_lowercase (			self							:			List[str]	):
    try:
       self._active_patches.remove(self	)
    except ValueError:
       # If the patch hasn't been started this will fail
       return None

    return self.__exit__()











from ...utils import is_torch_available, is_transformers_available


if is_transformers_available() and is_torch_available():
    from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline


