





import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
	import jax.numpy as jnp




class 	UpperCamelCase_							(  UpperCamelCase__     ):


							def __get__(				self     :Any				,					__A     :Dict				,					__A     :List[Any]=None		) -> List[Any]:



									"""simple docstring"""



									if obj is None:
											return self
									if self.fget is None:
											raise AttributeError("""unreadable attribute"""		)
									SCREAMING_SNAKE_CASE__								=   """__cached_""" + self.fget.__name__
									SCREAMING_SNAKE_CASE__								=   getattr(__A				,					__A				,					__A		)
									if cached is None:
											SCREAMING_SNAKE_CASE__								=   self.fget(__A		)
											setattr(__A				,					__A				,					__A		)
									return cached






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Optional[Any]     ):
		SCREAMING_SNAKE_CASE__								=   val.lower()
		if val in {"y", "yes", "t", "true", "on", "1"}:
				return 1
		if val in {"n", "no", "f", "false", "off", "0"}:
				return 0
		raise ValueError(f'''invalid truth value {val!r}'''     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				int     ):
		if is_torch_fx_proxy(UpperCamelCase__     ):
				return True
		if is_torch_available():
				import torch

				if isinstance(UpperCamelCase__       , torch.Tensor     ):
						return True
		if is_tf_available():
				import tensorflow as tf

				if isinstance(UpperCamelCase__       , tf.Tensor     ):
						return True

		if is_flax_available():
				import jax.numpy as jnp
				from jax.core import Tracer

				if isinstance(UpperCamelCase__       , (jnp.ndarray, Tracer)     ):
						return True

		return isinstance(UpperCamelCase__       , np.ndarray     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Tuple     ):
		return isinstance(UpperCamelCase__       , np.ndarray     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[str]     ):
		return _is_numpy(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Dict     ):
		import torch

		return isinstance(UpperCamelCase__       , torch.Tensor     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Union[str, Any]     ):
		return False if not is_torch_available() else _is_torch(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Dict     ):
		import torch

		return isinstance(UpperCamelCase__       , torch.device     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				str     ):
		return False if not is_torch_available() else _is_torch_device(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[str]     ):
		import torch

		if isinstance(UpperCamelCase__       , UpperCamelCase__     ):
				if hasattr(UpperCamelCase__       , UpperCamelCase__     ):
						SCREAMING_SNAKE_CASE__								=   getattr(UpperCamelCase__       , UpperCamelCase__     )
				else:
						return False
		return isinstance(UpperCamelCase__       , torch.dtype     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Tuple     ):
		return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[Any]     ):
		import tensorflow as tf

		return isinstance(UpperCamelCase__       , tf.Tensor     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				int     ):
		return False if not is_tf_available() else _is_tensorflow(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Tuple     ):
		import tensorflow as tf

		# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
		if hasattr(UpperCamelCase__       , """is_symbolic_tensor"""     ):
				return tf.is_symbolic_tensor(UpperCamelCase__     )
		return type(UpperCamelCase__     ) == tf.Tensor






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[Any]     ):
		return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Any     ):
		import jax.numpy as jnp  # noqa: F811

		return isinstance(UpperCamelCase__       , jnp.ndarray     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Union[str, Any]     ):
		return False if not is_flax_available() else _is_jax(UpperCamelCase__     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Optional[int]     ):
		if isinstance(UpperCamelCase__       , (dict, UserDict)     ):
				return {k: to_py_obj(UpperCamelCase__     ) for k, v in obj.items()}
		elif isinstance(UpperCamelCase__       , (list, tuple)     ):
				return [to_py_obj(UpperCamelCase__     ) for o in obj]
		elif is_tf_tensor(UpperCamelCase__     ):
				return obj.numpy().tolist()
		elif is_torch_tensor(UpperCamelCase__     ):
				return obj.detach().cpu().tolist()
		elif is_jax_tensor(UpperCamelCase__     ):
				return np.asarray(UpperCamelCase__     ).tolist()
		elif isinstance(UpperCamelCase__       , (np.ndarray, np.number)     ):  # tolist also works on 0d np arrays
				return obj.tolist()
		else:
				return obj






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Tuple     ):
		if isinstance(UpperCamelCase__       , (dict, UserDict)     ):
				return {k: to_numpy(UpperCamelCase__     ) for k, v in obj.items()}
		elif isinstance(UpperCamelCase__       , (list, tuple)     ):
				return np.array(UpperCamelCase__     )
		elif is_tf_tensor(UpperCamelCase__     ):
				return obj.numpy()
		elif is_torch_tensor(UpperCamelCase__     ):
				return obj.detach().cpu().numpy()
		elif is_jax_tensor(UpperCamelCase__     ):
				return np.asarray(UpperCamelCase__     )
		else:
				return obj




class 	UpperCamelCase_							(  UpperCamelCase__     ):


							def   _snake_case	(				self     :List[Any]		) -> Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   fields(self		)

									# Safety and consistency checks
									if not len(__A		):
											raise ValueError(f'''{self.__class__.__name__} has no fields.'''		)
									if not all(field.default is None for field in class_fields[1:]		):
											raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.'''		)

									SCREAMING_SNAKE_CASE__								=   getattr(self				,					class_fields[0].name		)
									SCREAMING_SNAKE_CASE__								=   all(getattr(self				,					field.name		) is None for field in class_fields[1:]		)

									if other_fields_are_none and not is_tensor(__A		):
											if isinstance(__A				,					__A		):
													SCREAMING_SNAKE_CASE__								=   first_field.items()
													SCREAMING_SNAKE_CASE__								=   True
											else:
													try:
															SCREAMING_SNAKE_CASE__								=   iter(__A		)
															SCREAMING_SNAKE_CASE__								=   True
													except TypeError:
															SCREAMING_SNAKE_CASE__								=   False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
											if first_field_iterator:
													for idx, element in enumerate(__A		):
															if (
															    not isinstance(__A				,					(list, tuple)		)
															    or not len(__A		) == 2
															    or not isinstance(element[0]				,					__A		)
															):
																	if idx == 0:
																			# If we do not have an iterator of key/values, set it as attribute
																			SCREAMING_SNAKE_CASE__								=   first_field
																	else:
																			# If we have a mixed iterator, raise an error
																			raise ValueError(
																			    f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).'''		)
																	break
															setattr(self				,					element[0]				,					element[1]		)
															if element[1] is not None:
																	SCREAMING_SNAKE_CASE__								=   element[1]
											elif first_field is not None:
													SCREAMING_SNAKE_CASE__								=   first_field
									else:
											for field in class_fields:
													SCREAMING_SNAKE_CASE__								=   getattr(self				,					field.name		)
													if v is not None:
															SCREAMING_SNAKE_CASE__								=   v


							def __delitem__(				self     :List[str]				,					*__A     :Tuple				,					**__A     :str		) -> List[str]:



									"""simple docstring"""



									raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''		)


							def   _snake_case	(				self     :Union[str, Any]				,					*__A     :Union[str, Any]				,					**__A     :List[Any]		) -> Optional[Any]:



									"""simple docstring"""



									raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''		)


							def   _snake_case	(				self     :Union[str, Any]				,					*__A     :List[Any]				,					**__A     :Union[str, Any]		) -> Tuple:



									"""simple docstring"""



									raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''		)


							def   _snake_case	(				self     :Optional[Any]				,					*__A     :Union[str, Any]				,					**__A     :Optional[int]		) -> int:



									"""simple docstring"""



									raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''		)


							def __getitem__(				self     :List[str]				,					__A     :List[str]		) -> str:



									"""simple docstring"""



									if isinstance(__A				,					__A		):
											SCREAMING_SNAKE_CASE__								=   dict(self.items()		)
											return inner_dict[k]
									else:
											return self.to_tuple()[k]


							def __setattr__(				self     :List[str]				,					__A     :Dict				,					__A     :Union[str, Any]		) -> Any:



									"""simple docstring"""



									if name in self.keys() and value is not None:
											# Don't call self.__setitem__ to avoid recursion errors
											super().__setitem__(__A				,					__A		)
									super().__setattr__(__A				,					__A		)


							def __setitem__(				self     :Optional[int]				,					__A     :int				,					__A     :Any		) -> Tuple:



									"""simple docstring"""



									super().__setitem__(__A				,					__A		)
									# Don't call self.__setattr__ to avoid recursion errors
									super().__setattr__(__A				,					__A		)


							def   _snake_case	(				self     :Union[str, Any]		) -> Tuple[Any]:



									"""simple docstring"""



									return tuple(self[k] for k in self.keys()		)




class 	UpperCamelCase_							(  UpperCamelCase__					,	UpperCamelCase__     ):


							@classmethod
							def   _snake_case	(				cls     :Union[str, Any]				,					__A     :str		) -> str:



									"""simple docstring"""



									raise ValueError(
									    f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()		)}'''		)




class 	UpperCamelCase_							(  UpperCamelCase__     ):
							lowerCamelCase_							     =       "longest"
							lowerCamelCase_							     =       "max_length"
							lowerCamelCase_							     =       "do_not_pad"




class 	UpperCamelCase_							(  UpperCamelCase__     ):
							lowerCamelCase_							     =       "pt"
							lowerCamelCase_							     =       "tf"
							lowerCamelCase_							     =       "np"
							lowerCamelCase_							     =       "jax"




class 	UpperCamelCase_							:


							def __init__(				self     :Union[str, Any]				,					__A     :List[ContextManager]		) -> Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   context_managers
									SCREAMING_SNAKE_CASE__								=   ExitStack()


							def __enter__(				self     :Any		) -> Any:



									"""simple docstring"""



									for context_manager in self.context_managers:
											self.stack.enter_context(__A		)


							def __exit__(				self     :Any				,					*__A     :Union[str, Any]				,					**__A     :Dict		) -> Tuple:



									"""simple docstring"""



									self.stack.__exit__(*__A				,					**__A		)






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[Any]     ):
		SCREAMING_SNAKE_CASE__								=   infer_framework(UpperCamelCase__     )
		if framework == "tf":
				SCREAMING_SNAKE_CASE__								=   inspect.signature(model_class.call     )  # TensorFlow models
		elif framework == "pt":
				SCREAMING_SNAKE_CASE__								=   inspect.signature(model_class.forward     )  # PyTorch models
		else:
				SCREAMING_SNAKE_CASE__								=   inspect.signature(model_class.__call__     )  # Flax models

		for p in signature.parameters:
				if p == "return_loss" and signature.parameters[p].default is True:
						return True

		return False






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				int     ):
		SCREAMING_SNAKE_CASE__								=   model_class.__name__
		SCREAMING_SNAKE_CASE__								=   infer_framework(UpperCamelCase__     )
		if framework == "tf":
				SCREAMING_SNAKE_CASE__								=   inspect.signature(model_class.call     )  # TensorFlow models
		elif framework == "pt":
				SCREAMING_SNAKE_CASE__								=   inspect.signature(model_class.forward     )  # PyTorch models
		else:
				SCREAMING_SNAKE_CASE__								=   inspect.signature(model_class.__call__     )  # Flax models

		if "QuestionAnswering" in model_name:
				return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
		else:
				return [p for p in signature.parameters if "label" in p]






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				MutableMapping       , UpperCamelCase__:				str = ""       , UpperCamelCase__:				str = "."     ):

		def _flatten_dict(UpperCamelCase__:				Union[str, Any]       , UpperCamelCase__:				Tuple=""       , UpperCamelCase__:				Optional[Any]="."     ):
				for k, v in d.items():
						SCREAMING_SNAKE_CASE__								=   str(UpperCamelCase__     ) + delimiter + str(UpperCamelCase__     ) if parent_key else k
						if v and isinstance(UpperCamelCase__       , UpperCamelCase__     ):
								yield from flatten_dict(UpperCamelCase__       , UpperCamelCase__       , delimiter=UpperCamelCase__     ).items()
						else:
								yield key, v

		return dict(_flatten_dict(UpperCamelCase__       , UpperCamelCase__       , UpperCamelCase__     )     )






@contextmanager
def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Optional[Any]       , UpperCamelCase__:				bool = False     ):
		if use_temp_dir:
				with tempfile.TemporaryDirectory() as tmp_dir:
						yield tmp_dir
		else:
				yield working_dir






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				str       , UpperCamelCase__:				Optional[int]=None     ):
		if is_numpy_array(UpperCamelCase__     ):
				return np.transpose(UpperCamelCase__       , axes=UpperCamelCase__     )
		elif is_torch_tensor(UpperCamelCase__     ):
				return array.T if axes is None else array.permute(*UpperCamelCase__     )
		elif is_tf_tensor(UpperCamelCase__     ):
				import tensorflow as tf

				return tf.transpose(UpperCamelCase__       , perm=UpperCamelCase__     )
		elif is_jax_tensor(UpperCamelCase__     ):
				return jnp.transpose(UpperCamelCase__       , axes=UpperCamelCase__     )
		else:
				raise ValueError(f'''Type not supported for transpose: {type(UpperCamelCase__     )}.'''     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Tuple       , UpperCamelCase__:				str     ):
		if is_numpy_array(UpperCamelCase__     ):
				return np.reshape(UpperCamelCase__       , UpperCamelCase__     )
		elif is_torch_tensor(UpperCamelCase__     ):
				return array.reshape(*UpperCamelCase__     )
		elif is_tf_tensor(UpperCamelCase__     ):
				import tensorflow as tf

				return tf.reshape(UpperCamelCase__       , UpperCamelCase__     )
		elif is_jax_tensor(UpperCamelCase__     ):
				return jnp.reshape(UpperCamelCase__       , UpperCamelCase__     )
		else:
				raise ValueError(f'''Type not supported for reshape: {type(UpperCamelCase__     )}.'''     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[Any]       , UpperCamelCase__:				Optional[Any]=None     ):
		if is_numpy_array(UpperCamelCase__     ):
				return np.squeeze(UpperCamelCase__       , axis=UpperCamelCase__     )
		elif is_torch_tensor(UpperCamelCase__     ):
				return array.squeeze() if axis is None else array.squeeze(dim=UpperCamelCase__     )
		elif is_tf_tensor(UpperCamelCase__     ):
				import tensorflow as tf

				return tf.squeeze(UpperCamelCase__       , axis=UpperCamelCase__     )
		elif is_jax_tensor(UpperCamelCase__     ):
				return jnp.squeeze(UpperCamelCase__       , axis=UpperCamelCase__     )
		else:
				raise ValueError(f'''Type not supported for squeeze: {type(UpperCamelCase__     )}.'''     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Dict       , UpperCamelCase__:				str     ):
		if is_numpy_array(UpperCamelCase__     ):
				return np.expand_dims(UpperCamelCase__       , UpperCamelCase__     )
		elif is_torch_tensor(UpperCamelCase__     ):
				return array.unsqueeze(dim=UpperCamelCase__     )
		elif is_tf_tensor(UpperCamelCase__     ):
				import tensorflow as tf

				return tf.expand_dims(UpperCamelCase__       , axis=UpperCamelCase__     )
		elif is_jax_tensor(UpperCamelCase__     ):
				return jnp.expand_dims(UpperCamelCase__       , axis=UpperCamelCase__     )
		else:
				raise ValueError(f'''Type not supported for expand_dims: {type(UpperCamelCase__     )}.'''     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Union[str, Any]     ):
		if is_numpy_array(UpperCamelCase__     ):
				return np.size(UpperCamelCase__     )
		elif is_torch_tensor(UpperCamelCase__     ):
				return array.numel()
		elif is_tf_tensor(UpperCamelCase__     ):
				import tensorflow as tf

				return tf.size(UpperCamelCase__     )
		elif is_jax_tensor(UpperCamelCase__     ):
				return array.size
		else:
				raise ValueError(f'''Type not supported for expand_dims: {type(UpperCamelCase__     )}.'''     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Any       , UpperCamelCase__:				Optional[Any]     ):
		for key, value in auto_map.items():
				if isinstance(UpperCamelCase__       , (tuple, list)     ):
						SCREAMING_SNAKE_CASE__								=   [f'''{repo_id}--{v}''' if (v is not None and """--""" not in v) else v for v in value]
				elif value is not None and "--" not in value:
						SCREAMING_SNAKE_CASE__								=   f'''{repo_id}--{value}'''

		return auto_map






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Dict     ):
		for base_class in inspect.getmro(UpperCamelCase__     ):
				SCREAMING_SNAKE_CASE__								=   base_class.__module__
				SCREAMING_SNAKE_CASE__								=   base_class.__name__
				if module.startswith("""tensorflow"""     ) or module.startswith("""keras"""     ) or name == "TFPreTrainedModel":
						return "tf"
				elif module.startswith("""torch"""     ) or name == "PreTrainedModel":
						return "pt"
				elif module.startswith("""flax"""     ) or module.startswith("""jax"""     ) or name == "FlaxPreTrainedModel":
						return "flax"
		else:
				raise TypeError(f'''Could not infer framework from class {model_class}.'''     )


from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
   if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_torch_and_transformers_objects import (
       VersatileDiffusionDualGuidedPipeline,
       VersatileDiffusionImageVariationPipeline,
       VersatileDiffusionPipeline,
       VersatileDiffusionTextToImagePipeline,
   )
else:
   from .modeling_text_unet import UNetFlatConditionModel
   from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
   from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
   from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
   from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline


