





from importlib import import_module

from .logging import get_logger


UpperCAmelCase	:	int		     =       get_logger(__name__)







class 				__lowerCAmelCase       :







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__=None							)   ->						Tuple:



        '''simple docstring'''




        a__	:					int										=attrs or []
        if module is not None:
          for key in module.__dict__:
            if key in attrs or not key.startswith("__"							):
              setattr(self		,      lowerCAmelCase__		,      getattr(lowerCAmelCase__		,      lowerCAmelCase__							)							)
        a__	:					Any										=module._original_module if isinstance(lowerCAmelCase__		,      _PatchedModuleObj							) else module







class 				__lowerCAmelCase       :
      _lowercase				:					List[Any]						=			[]







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__=None							)   ->						List[str]:



        '''simple docstring'''




        a__	:					Optional[int]										=obj
        a__	:					Tuple										=target
        a__	:					Tuple										=new
        a__	:					str										=target.split("."							)[0]
        a__	:					str										={}
        a__	:					int										=attrs or []







      def __enter__(    self							)   ->						str:



        '''simple docstring'''




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







      def __exit__(    self		,      *lowerCAmelCase__							)   ->						str:



        '''simple docstring'''




        for attr in list(self.original							):
          setattr(self.obj		,      lowerCAmelCase__		,      self.original.pop(lowerCAmelCase__							)							)







      def    _lowercase  (    self							)   ->						Optional[Any]:



        '''simple docstring'''




        self.__enter__()
        self._active_patches.append(self							)







      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




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

        return self.__exit__()














'''simple docstring'''







import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


_A	:			Union[str, Any]         =False

class _lowercase	(				unittest.TestCase		):
							pass



@slow
@require_torch_gpu
class _lowercase	(				unittest.TestCase		):




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Tuple         =       VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion"""     )
														pipe.to(UpperCamelCase__     )
														pipe.set_progress_bar_config(disable=UpperCamelCase__     )

														lowerCamelCase__					:	Optional[int]         =       load_image(
														    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""     )
														lowerCamelCase__					:	List[Any]         =       torch.manual_seed(0     )
														lowerCamelCase__					:	List[Any]         =       pipe(
														    image=UpperCamelCase__			,							generator=UpperCamelCase__			,							guidance_scale=7.5			,							num_inference_steps=50			,							output_type="""numpy"""			,							).images

														lowerCamelCase__					:	List[str]         =       image[0, 253:256, 253:256, -1]

														assert image.shape == (1, 512, 512, 3)
														lowerCamelCase__					:	Tuple         =       np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945]     )

														assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1e-2

