





"""simple docstring"""




from importlib import import_module

from .logging import get_logger


UpperCamelCase_									=get_logger(__name__)




class 			_a						:






				def __init__(			self		:   str,			lowerCAmelCase__		:   Optional[Any],			lowerCAmelCase__		:   Optional[Any]=None							)     ->				Tuple:




										'''simple docstring'''



										_UpperCamelCase      : Tuple         =   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__							)							)
										_UpperCamelCase      : Tuple         =   module._original_module if isinstance(lowerCAmelCase__,			_PatchedModuleObj							) else module




class 			_a						:
				UpperCamelCase								=   []






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




										'''simple docstring'''



										_UpperCamelCase      : List[str]         =   obj
										_UpperCamelCase      : str         =   target
										_UpperCamelCase      : Optional[int]         =   new
										_UpperCamelCase      : Tuple         =   target.split('''.'''							)[0]
										_UpperCamelCase      : Optional[int]         =   {}
										_UpperCamelCase      : Union[str, Any]         =   attrs or []






				def __enter__(			self		:   str							)     ->				List[Any]:




										'''simple docstring'''



										_UpperCamelCase      : Optional[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(lowerCAmelCase__							)							):
																try:
																						_UpperCamelCase      : List[str]         =   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__():
																						_UpperCamelCase      : 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)
																						):
																												_UpperCamelCase      : Optional[Any]         =   obj_attr
																												# patch at top level
																												setattr(self.obj,			lowerCAmelCase__,			_PatchedModuleObj(lowerCAmelCase__,			attrs=self.attrs							)							)
																												_UpperCamelCase      : Optional[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							)							)
																																		_UpperCamelCase      : List[Any]         =   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:
																						_UpperCamelCase      : List[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:
																												_UpperCamelCase      : List[str]         =   getattr(self.obj,			lowerCAmelCase__							)
																												setattr(self.obj,			lowerCAmelCase__,			self.new							)
										elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																_UpperCamelCase      : 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		:   List[str],			*lowerCAmelCase__		:   Union[str, Any]							)     ->				Union[str, Any]:




										'''simple docstring'''



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






				def     a     (			self		:   Union[str, Any]							)     ->				Dict:




										'''simple docstring'''



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






				def     a     (			self		:   Any							)     ->				Tuple:




										'''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 numpy as np
import torch
from imwatermark import WatermarkEncoder


# Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66
UpperCamelCase_									=0b1_0_1_1_0_0_1_1_1_1_1_0_1_1_0_0_1_0_0_1_0_0_0_0_0_1_1_1_1_0_1_1_1_0_1_1_0_0_0_1_1_0_0_1_1_1_1_0
# bin(x)[2:] gives bits of x as str, use int to convert them to 0/1
UpperCamelCase_									=[int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]]




class 			_a						:






				def __init__(			self		:   str							)     ->				str:




										'''simple docstring'''



										_UpperCamelCase      : str         =   WATERMARK_BITS
										_UpperCamelCase      : Optional[int]         =   WatermarkEncoder()

										self.encoder.set_watermark('''bits''',			self.watermark							)






				def     snake_case     (			self		:   Dict,			lowerCAmelCase__		:   torch.FloatTensor							)     ->				int:




										'''simple docstring'''



										if images.shape[-1] < 2_5_6:
																return images

										_UpperCamelCase      : Union[str, Any]         =   (2_5_5 * (images / 2 + 0.5)).cpu().permute(0,			2,			3,			1							).float().numpy()

										_UpperCamelCase      : List[str]         =   [self.encoder.encode(lowerCAmelCase__,			'''dwtDct'''							) for image in images]

										_UpperCamelCase      : Dict         =   torch.from_numpy(np.array(lowerCAmelCase__							)							).permute(0,			3,			1,			2							)

										_UpperCamelCase      : Optional[int]         =   torch.clamp(2 * (images / 2_5_5 - 0.5),			min=-1.0,			max=1.0							)
										return images



