'''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 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    def __get__(       self    ,							lowercase__    ,							lowercase__=None )							-> Any:
         # See docs.python.org/3/howto/descriptor.html#properties
         if obj is None:
              return self
         if self.fget is None:
              raise AttributeError('unreadable attribute' )
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       '__cached_' + self.fget.__name__
         SCREAMING_SNAKE_CASE					:			Tuple    	=       getattr(lowercase__    ,							lowercase__    ,							lowercase__ )
         if cached is None:
              SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       self.fget(lowercase__ )
              setattr(lowercase__    ,							lowercase__    ,							lowercase__ )
         return cached






def     __lowerCAmelCase						(       a_		)      ->	List[Any]:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			Dict    	=       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     __lowerCAmelCase						(       a_		)      ->	Dict:





     '''simple docstring'''





     if is_torch_fx_proxy(a_		):
          return True
     if is_torch_available():
          import torch

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

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

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

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

     return isinstance(a_       ,      np.ndarray		)


def     __lowerCAmelCase						(       a_		)      ->	List[Any]:





     '''simple docstring'''





     return isinstance(a_       ,      np.ndarray		)


def     __lowerCAmelCase						(       a_		)      ->	List[Any]:





     '''simple docstring'''





     return _is_numpy(a_		)


def     __lowerCAmelCase						(       a_		)      ->	Dict:





     '''simple docstring'''





     import torch

     return isinstance(a_       ,      torch.Tensor		)


def     __lowerCAmelCase						(       a_		)      ->	Optional[int]:





     '''simple docstring'''





     return False if not is_torch_available() else _is_torch(a_		)


def     __lowerCAmelCase						(       a_		)      ->	int:





     '''simple docstring'''





     import torch

     return isinstance(a_       ,      torch.device		)


def     __lowerCAmelCase						(       a_		)      ->	List[str]:





     '''simple docstring'''





     return False if not is_torch_available() else _is_torch_device(a_		)


def     __lowerCAmelCase						(       a_		)      ->	str:





     '''simple docstring'''





     import torch

     if isinstance(a_       ,      a_		):
          if hasattr(a_       ,      a_		):
               SCREAMING_SNAKE_CASE					:			List[Any]    	=       getattr(a_       ,      a_		)
          else:
               return False
     return isinstance(a_       ,      torch.dtype		)


def     __lowerCAmelCase						(       a_		)      ->	Any:





     '''simple docstring'''





     return False if not is_torch_available() else _is_torch_dtype(a_		)


def     __lowerCAmelCase						(       a_		)      ->	str:





     '''simple docstring'''





     import tensorflow as tf

     return isinstance(a_       ,      tf.Tensor		)


def     __lowerCAmelCase						(       a_		)      ->	Union[str, Any]:





     '''simple docstring'''





     return False if not is_tf_available() else _is_tensorflow(a_		)


def     __lowerCAmelCase						(       a_		)      ->	Optional[Any]:





     '''simple docstring'''





     import tensorflow as tf

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


def     __lowerCAmelCase						(       a_		)      ->	Tuple:





     '''simple docstring'''





     return False if not is_tf_available() else _is_tf_symbolic_tensor(a_		)


def     __lowerCAmelCase						(       a_		)      ->	Tuple:





     '''simple docstring'''





     import jax.numpy as jnp  # noqa: F811

     return isinstance(a_       ,      jnp.ndarray		)


def     __lowerCAmelCase						(       a_		)      ->	Optional[int]:





     '''simple docstring'''





     return False if not is_flax_available() else _is_jax(a_		)


def     __lowerCAmelCase						(       a_		)      ->	Any:





     '''simple docstring'''





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


def     __lowerCAmelCase						(       a_		)      ->	List[Any]:





     '''simple docstring'''





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






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    def       _UpperCamelCase    (       self )							-> int:
         SCREAMING_SNAKE_CASE					:			Any    	=       fields(self )

         # Safety and consistency checks
         if not len(lowercase__ ):
              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					:			Optional[Any]    	=       getattr(self    ,							class_fields[0].name )
         SCREAMING_SNAKE_CASE					:			Dict    	=       all(getattr(self    ,							field.name ) is None for field in class_fields[1:] )

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






    def __delitem__(       self    ,							*lowercase__    ,							**lowercase__ )							-> Dict:
         raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.""" )






    def       _UpperCamelCase    (       self    ,							*lowercase__    ,							**lowercase__ )							-> str:
         raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance.""" )






    def       _UpperCamelCase    (       self    ,							*lowercase__    ,							**lowercase__ )							-> Optional[int]:
         raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance.""" )






    def       _UpperCamelCase    (       self    ,							*lowercase__    ,							**lowercase__ )							-> int:
         raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance.""" )






    def __getitem__(       self    ,							lowercase__ )							-> Optional[Any]:
         if isinstance(lowercase__    ,							lowercase__ ):
              SCREAMING_SNAKE_CASE					:			List[str]    	=       dict(self.items() )
              return inner_dict[k]
         else:
              return self.to_tuple()[k]






    def __setattr__(       self    ,							lowercase__    ,							lowercase__ )							-> Optional[int]:
         if name in self.keys() and value is not None:
              # Don't call self.__setitem__ to avoid recursion errors
              super().__setitem__(lowercase__    ,							lowercase__ )
         super().__setattr__(lowercase__    ,							lowercase__ )






    def __setitem__(       self    ,							lowercase__    ,							lowercase__ )							-> Dict:
         # Will raise a KeyException if needed
         super().__setitem__(lowercase__    ,							lowercase__ )
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(lowercase__    ,							lowercase__ )






    def       _UpperCamelCase    (       self )							-> Tuple[Any]:
         return tuple(self[k] for k in self.keys() )






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE   ,    _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    @classmethod
    def       _UpperCamelCase    (       cls    ,							lowercase__ )							-> Optional[int]:
         raise ValueError(
             F"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}""" )






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    snake_case__							:   List[str]							=						"longest"
    snake_case__							:   Optional[Any]							=						"max_length"
    snake_case__							:   Tuple							=						"do_not_pad"






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    snake_case__							:   List[str]							=						"pt"
    snake_case__							:   Optional[int]							=						"tf"
    snake_case__							:   Optional[Any]							=						"np"
    snake_case__							:   Dict							=						"jax"






class 				UpperCAmelCase :




    '''simple docstring'''







    def __init__(       self    ,							lowercase__ )							-> Optional[int]:
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       context_managers
         SCREAMING_SNAKE_CASE					:			Dict    	=       ExitStack()






    def __enter__(       self )							-> str:
         for context_manager in self.context_managers:
              self.stack.enter_context(lowercase__ )






    def __exit__(       self    ,							*lowercase__    ,							**lowercase__ )							-> List[str]:
         self.stack.__exit__(*lowercase__    ,							**lowercase__ )






def     __lowerCAmelCase						(       a_		)      ->	Any:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       infer_framework(a_		)
     if framework == "tf":
          SCREAMING_SNAKE_CASE					:			int    	=       inspect.signature(model_class.call		)  # TensorFlow models
     elif framework == "pt":
          SCREAMING_SNAKE_CASE					:			int    	=       inspect.signature(model_class.forward		)  # PyTorch models
     else:
          SCREAMING_SNAKE_CASE					:			Optional[int]    	=       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     __lowerCAmelCase						(       a_		)      ->	Union[str, Any]:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			Tuple    	=       model_class.__name__
     SCREAMING_SNAKE_CASE					:			Tuple    	=       infer_framework(a_		)
     if framework == "tf":
          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       inspect.signature(model_class.call		)  # TensorFlow models
     elif framework == "pt":
          SCREAMING_SNAKE_CASE					:			List[str]    	=       inspect.signature(model_class.forward		)  # PyTorch models
     else:
          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       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     __lowerCAmelCase						(       a_       ,      a_ = ""       ,      a_ = "."		)      ->	Optional[int]:





     '''simple docstring'''





     def _flatten_dict(a_       ,      a_=""       ,      a_="."		):
          for k, v in d.items():
               SCREAMING_SNAKE_CASE					:			List[str]    	=       str(a_		) + delimiter + str(a_		) if parent_key else k
               if v and isinstance(a_       ,      a_		):
                    yield from flatten_dict(a_       ,      a_       ,      delimiter=a_		).items()
               else:
                    yield key, v

     return dict(_flatten_dict(a_       ,      a_       ,      a_		)		)


@contextmanager
def     __lowerCAmelCase						(       a_       ,      a_ = False		)      ->	Optional[Any]:





     '''simple docstring'''





     if use_temp_dir:
          with tempfile.TemporaryDirectory() as tmp_dir:
               yield tmp_dir
     else:
          yield working_dir


def     __lowerCAmelCase						(       a_       ,      a_=None		)      ->	Optional[int]:





     '''simple docstring'''





     if is_numpy_array(a_		):
          return np.transpose(a_       ,      axes=a_		)
     elif is_torch_tensor(a_		):
          return array.T if axes is None else array.permute(*a_		)
     elif is_tf_tensor(a_		):
          import tensorflow as tf

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


def     __lowerCAmelCase						(       a_       ,      a_		)      ->	Dict:





     '''simple docstring'''





     if is_numpy_array(a_		):
          return np.reshape(a_       ,      a_		)
     elif is_torch_tensor(a_		):
          return array.reshape(*a_		)
     elif is_tf_tensor(a_		):
          import tensorflow as tf

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


def     __lowerCAmelCase						(       a_       ,      a_=None		)      ->	Optional[Any]:





     '''simple docstring'''





     if is_numpy_array(a_		):
          return np.squeeze(a_       ,      axis=a_		)
     elif is_torch_tensor(a_		):
          return array.squeeze() if axis is None else array.squeeze(dim=a_		)
     elif is_tf_tensor(a_		):
          import tensorflow as tf

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


def     __lowerCAmelCase						(       a_       ,      a_		)      ->	Optional[Any]:





     '''simple docstring'''





     if is_numpy_array(a_		):
          return np.expand_dims(a_       ,      a_		)
     elif is_torch_tensor(a_		):
          return array.unsqueeze(dim=a_		)
     elif is_tf_tensor(a_		):
          import tensorflow as tf

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


def     __lowerCAmelCase						(       a_		)      ->	Tuple:





     '''simple docstring'''





     if is_numpy_array(a_		):
          return np.size(a_		)
     elif is_torch_tensor(a_		):
          return array.numel()
     elif is_tf_tensor(a_		):
          import tensorflow as tf

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


def     __lowerCAmelCase						(       a_       ,      a_		)      ->	Optional[Any]:





     '''simple docstring'''





     for key, value in auto_map.items():
          if isinstance(a_       ,      (tuple, list)		):
               SCREAMING_SNAKE_CASE					:			Optional[int]    	=       [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					:			List[Any]    	=       f"""{repo_id}--{value}"""

     return auto_map


def     __lowerCAmelCase						(       a_		)      ->	Optional[int]:





     '''simple docstring'''





     for base_class in inspect.getmro(a_		):
          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       base_class.__module__
          SCREAMING_SNAKE_CASE					:			Optional[int]    	=       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 tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


_lowerCAmelCase  :List[Any]  				=    False






class 				UpperCAmelCase (       unittest.TestCase ):




    '''simple docstring'''







    pass






@nightly
@require_torch_gpu
class 				UpperCAmelCase (       unittest.TestCase ):




    '''simple docstring'''







    def       _UpperCamelCase    (       self )							-> Any:
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()






    def       _UpperCamelCase    (       self )							-> Tuple:
         SCREAMING_SNAKE_CASE					:			Dict    	=       VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' )
         # remove text_unet
         pipe.remove_unused_weights()
         pipe.to(lowercase__ )
         pipe.set_progress_bar_config(disable=lowercase__ )

         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       'A painting of a squirrel eating a burger '
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       torch.manual_seed(0 )
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       pipe(
             prompt=lowercase__    ,							generator=lowercase__    ,							guidance_scale=7.5    ,							num_inference_steps=2    ,							output_type='numpy' ).images

         with tempfile.TemporaryDirectory() as tmpdirname:
              pipe.save_pretrained(lowercase__ )
              SCREAMING_SNAKE_CASE					:			int    	=       VersatileDiffusionTextToImagePipeline.from_pretrained(lowercase__ )
         pipe.to(lowercase__ )
         pipe.set_progress_bar_config(disable=lowercase__ )

         SCREAMING_SNAKE_CASE					:			List[str]    	=       generator.manual_seed(0 )
         SCREAMING_SNAKE_CASE					:			List[str]    	=       pipe(
             prompt=lowercase__    ,							generator=lowercase__    ,							guidance_scale=7.5    ,							num_inference_steps=2    ,							output_type='numpy' ).images

         assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"






    def       _UpperCamelCase    (       self )							-> Any:
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       VersatileDiffusionTextToImagePipeline.from_pretrained(
             'shi-labs/versatile-diffusion'    ,							torch_dtype=torch.floataa )
         pipe.to(lowercase__ )
         pipe.set_progress_bar_config(disable=lowercase__ )

         SCREAMING_SNAKE_CASE					:			int    	=       'A painting of a squirrel eating a burger '
         SCREAMING_SNAKE_CASE					:			Tuple    	=       torch.manual_seed(0 )
         SCREAMING_SNAKE_CASE					:			Tuple    	=       pipe(
             prompt=lowercase__    ,							generator=lowercase__    ,							guidance_scale=7.5    ,							num_inference_steps=50    ,							output_type='numpy' ).images

         SCREAMING_SNAKE_CASE					:			Dict    	=       image[0, 253:256, 253:256, -1]

         assert image.shape == (1, 512, 512, 3)
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] )

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



