




"""simple docstring"""




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        __magic_name__				(			UpperCAmelCase__							):






				'''simple docstring'''





				def __get__(			self						,					_a						,					_a=None					):





							"""simple docstring"""
							# See docs.python.org/3/howto/descriptor.html#properties
							if obj is None:
										return self
							if self.fget is None:
										raise AttributeError("""unreadable attribute"""					)
							lowerCamelCase      =   """__cached_""" + self.fget.__name__
							lowerCamelCase      =   getattr(_UpperCamelCase						,					_UpperCamelCase						,					_UpperCamelCase					)
							if cached is None:
										lowerCamelCase      =   self.fget(_UpperCamelCase					)
										setattr(_UpperCamelCase						,					_UpperCamelCase						,					_UpperCamelCase					)
							return cached




def        a__					(							snake_case__							)		->   Tuple:
			lowerCamelCase      =   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        a__					(							snake_case__							)		->   str:
			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        a__					(							snake_case__							)		->   Dict:
			return isinstance(__UpperCamelCase			,					np.ndarray							)



def        a__					(							snake_case__							)		->   List[Any]:
			return _is_numpy(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   Any:
			import torch

			return isinstance(__UpperCamelCase			,					torch.Tensor							)



def        a__					(							snake_case__							)		->   Any:
			return False if not is_torch_available() else _is_torch(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   Optional[Any]:
			import torch

			return isinstance(__UpperCamelCase			,					torch.device							)



def        a__					(							snake_case__							)		->   Tuple:
			return False if not is_torch_available() else _is_torch_device(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   Dict:
			import torch

			if isinstance(__UpperCamelCase			,					__UpperCamelCase							):
						if hasattr(__UpperCamelCase			,					__UpperCamelCase							):
									lowerCamelCase      =   getattr(__UpperCamelCase			,					__UpperCamelCase							)
						else:
									return False
			return isinstance(__UpperCamelCase			,					torch.dtype							)



def        a__					(							snake_case__							)		->   List[str]:
			return False if not is_torch_available() else _is_torch_dtype(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   Dict:
			import tensorflow as tf

			return isinstance(__UpperCamelCase			,					tf.Tensor							)



def        a__					(							snake_case__							)		->   str:
			return False if not is_tf_available() else _is_tensorflow(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   str:
			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        a__					(							snake_case__							)		->   List[Any]:
			return False if not is_tf_available() else _is_tf_symbolic_tensor(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   Union[str, Any]:
			import jax.numpy as jnp  # noqa: F811

			return isinstance(__UpperCamelCase			,					jnp.ndarray							)



def        a__					(							snake_case__							)		->   List[str]:
			return False if not is_flax_available() else _is_jax(__UpperCamelCase							)



def        a__					(							snake_case__							)		->   Any:
			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        a__					(							snake_case__							)		->   Union[str, Any]:
			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        __magic_name__				(			UpperCAmelCase__							):






				'''simple docstring'''





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   fields(self					)

							# Safety and consistency checks
							if not len(_UpperCamelCase					):
										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.'					)

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

							if other_fields_are_none and not is_tensor(_UpperCamelCase					):
										if isinstance(_UpperCamelCase						,					_UpperCamelCase					):
													lowerCamelCase      =   first_field.items()
													lowerCamelCase      =   True
										else:
													try:
																lowerCamelCase      =   iter(_UpperCamelCase					)
																lowerCamelCase      =   True
													except TypeError:
																lowerCamelCase      =   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(_UpperCamelCase					):
																if (
																    not isinstance(_UpperCamelCase						,					(list, tuple)					)
																    or not len(_UpperCamelCase					) == 2
																    or not isinstance(element[0]						,					_UpperCamelCase					)
																):
																			if idx == 0:
																						# If we do not have an iterator of key/values, set it as attribute
																						lowerCamelCase      =   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:
																			lowerCamelCase      =   element[1]
										elif first_field is not None:
													lowerCamelCase      =   first_field
							else:
										for field in class_fields:
													lowerCamelCase      =   getattr(self						,					field.name					)
													if v is not None:
																lowerCamelCase      =   v





				def __delitem__(			self						,					*_a						,					**_a					):





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





				def   _lowerCAmelCase							(			self						,					*_a						,					**_a					):





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





				def   _lowerCAmelCase							(			self						,					*_a						,					**_a					):





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





				def   _lowerCAmelCase							(			self						,					*_a						,					**_a					):





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





				def __getitem__(			self						,					_a					):





							"""simple docstring"""
							if isinstance(_UpperCamelCase						,					_UpperCamelCase					):
										lowerCamelCase      =   dict(self.items()					)
										return inner_dict[k]
							else:
										return self.to_tuple()[k]





				def __setattr__(			self						,					_a						,					_a					):





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





				def __setitem__(			self						,					_a						,					_a					):





							"""simple docstring"""
							# Will raise a KeyException if needed
							super().__setitem__(_UpperCamelCase						,					_UpperCamelCase					)
							# Don't call self.__setattr__ to avoid recursion errors
							super().__setattr__(_UpperCamelCase						,					_UpperCamelCase					)





				def   _lowerCAmelCase							(			self					):





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






class        __magic_name__				(			UpperCAmelCase__		,   UpperCAmelCase__							):






				'''simple docstring'''





				@classmethod
				def   _lowerCAmelCase							(			cls						,					_a					):





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






class        __magic_name__				(			UpperCAmelCase__							):






				'''simple docstring'''
				__UpperCamelCase         =		"longest"
				__UpperCamelCase         =		"max_length"
				__UpperCamelCase         =		"do_not_pad"






class        __magic_name__				(			UpperCAmelCase__							):






				'''simple docstring'''
				__UpperCamelCase         =		"pt"
				__UpperCamelCase         =		"tf"
				__UpperCamelCase         =		"np"
				__UpperCamelCase         =		"jax"






class        __magic_name__				:






				'''simple docstring'''





				def __init__(			self						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   context_managers
							lowerCamelCase      =   ExitStack()





				def __enter__(			self					):





							"""simple docstring"""
							for context_manager in self.context_managers:
										self.stack.enter_context(_UpperCamelCase					)





				def __exit__(			self						,					*_a						,					**_a					):





							"""simple docstring"""
							self.stack.__exit__(*_UpperCamelCase						,					**_UpperCamelCase					)




def        a__					(							snake_case__							)		->   List[Any]:
			lowerCamelCase      =   infer_framework(__UpperCamelCase							)
			if framework == "tf":
						lowerCamelCase      =   inspect.signature(model_class.call							)  # TensorFlow models
			elif framework == "pt":
						lowerCamelCase      =   inspect.signature(model_class.forward							)  # PyTorch models
			else:
						lowerCamelCase      =   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        a__					(							snake_case__							)		->   Union[str, Any]:
			lowerCamelCase      =   model_class.__name__
			lowerCamelCase      =   infer_framework(__UpperCamelCase							)
			if framework == "tf":
						lowerCamelCase      =   inspect.signature(model_class.call							)  # TensorFlow models
			elif framework == "pt":
						lowerCamelCase      =   inspect.signature(model_class.forward							)  # PyTorch models
			else:
						lowerCamelCase      =   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        a__					(							snake_case__			,					snake_case__ = ""			,					snake_case__ = "."							)		->   int:

			def _flatten_dict(snake_case__			,					snake_case__=""			,					snake_case__="."							):
						for k, v in d.items():
									lowerCamelCase      =   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        a__					(							snake_case__			,					snake_case__ = False							)		->   List[Any]:
			if use_temp_dir:
						with tempfile.TemporaryDirectory() as tmp_dir:
									yield tmp_dir
			else:
						yield working_dir



def        a__					(							snake_case__			,					snake_case__=None							)		->   int:
			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        a__					(							snake_case__			,					snake_case__							)		->   Any:
			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        a__					(							snake_case__			,					snake_case__=None							)		->   Any:
			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        a__					(							snake_case__			,					snake_case__							)		->   Optional[Any]:
			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        a__					(							snake_case__							)		->   Optional[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        a__					(							snake_case__			,					snake_case__							)		->   Dict:
			for key, value in auto_map.items():
						if isinstance(__UpperCamelCase			,					(tuple, list)							):
									lowerCamelCase      =   [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:
									lowerCamelCase      =   F'{repo_id}--{value}'

			return auto_map



def        a__					(							snake_case__							)		->   Any:
			for base_class in inspect.getmro(__UpperCamelCase							):
						lowerCamelCase      =   base_class.__module__
						lowerCamelCase      =   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}.'							)







'''simple docstring'''
import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






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






       def   UpperCamelCase						( self   )->      Optional[int]:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()






       def   UpperCamelCase						( self   )->      Union[str, Any]:
            _A				=							StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'   )
            _A				=							sd_pipe.to(_UpperCamelCase   )
            sd_pipe.set_progress_bar_config(disable=_UpperCamelCase   )

            sd_pipe.set_scheduler('sample_euler'   )

            _A				=							'A painting of a squirrel eating a burger'
            _A				=							torch.manual_seed(0   )
            _A				=							sd_pipe([prompt]			,     generator=_UpperCamelCase			,     guidance_scale=9.0			,     num_inference_steps=20			,     output_type='np'   )

            _A				=							output.images

            _A				=							image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            _A				=							np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339]   )

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






       def   UpperCamelCase						( self   )->      Optional[Any]:
            _A				=							StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'   )
            _A				=							sd_pipe.to(_UpperCamelCase   )
            sd_pipe.set_progress_bar_config(disable=_UpperCamelCase   )

            sd_pipe.set_scheduler('sample_euler'   )

            _A				=							'A painting of a squirrel eating a burger'
            _A				=							torch.manual_seed(0   )
            _A				=							sd_pipe([prompt]			,     generator=_UpperCamelCase			,     guidance_scale=9.0			,     num_inference_steps=20			,     output_type='np'   )

            _A				=							output.images

            _A				=							image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            _A				=							np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112]   )

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






       def   UpperCamelCase						( self   )->      Optional[int]:
            _A				=							StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'   )
            _A				=							sd_pipe.to(_UpperCamelCase   )
            sd_pipe.set_progress_bar_config(disable=_UpperCamelCase   )

            sd_pipe.set_scheduler('sample_dpmpp_2m'   )

            _A				=							'A painting of a squirrel eating a burger'
            _A				=							torch.manual_seed(0   )
            _A				=							sd_pipe(
                [prompt]			,     generator=_UpperCamelCase			,     guidance_scale=7.5			,     num_inference_steps=15			,     output_type='np'			,     use_karras_sigmas=_UpperCamelCase			,     )

            _A				=							output.images

            _A				=							image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            _A				=							np.array(
                [0.1138_1689, 0.1211_2921, 0.138_9457, 0.1254_9606, 0.124_4964, 0.1083_1517, 0.1156_2866, 0.1086_7816, 0.1049_9048]   )

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





