



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_    (       a):







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

														'''simple docstring'''

														if obj is None:
																					return self
														if self.fget is None:
																					raise AttributeError("unreadable attribute")
														_lowerCAmelCase     :							List[Any]    =    "__cached_" + self.fget.__name__
														_lowerCAmelCase     :							Dict    =    getattr(__a,			__a,			__a)
														if cached is None:
																					_lowerCAmelCase     :							str    =    self.fget(__a)
																					setattr(__a,			__a,			__a)
														return cached






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							Any    =    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				(					_lowerCamelCase  ):





							'''simple docstring'''




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

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

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

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

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

							return isinstance(_lowerCamelCase				, np.ndarray  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							return isinstance(_lowerCamelCase				, np.ndarray  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							return _is_numpy(_lowerCamelCase  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							import torch

							return isinstance(_lowerCamelCase				, torch.Tensor  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							import torch

							return isinstance(_lowerCamelCase				, torch.device  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							import torch

							if isinstance(_lowerCamelCase				, _lowerCamelCase  ):
														if hasattr(_lowerCamelCase				, _lowerCamelCase  ):
																					_lowerCAmelCase     :							Optional[Any]    =    getattr(_lowerCamelCase				, _lowerCamelCase  )
														else:
																					return False
							return isinstance(_lowerCamelCase				, torch.dtype  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							import tensorflow as tf

							return isinstance(_lowerCamelCase				, tf.Tensor  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							import tensorflow as tf

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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							import jax.numpy as jnp  # noqa: F811

							return isinstance(_lowerCamelCase				, jnp.ndarray  )






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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



class   UpperCAmelCase_    (       a):







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    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.")

														_lowerCAmelCase     :							Dict    =    getattr(self,			class_fields[0].name)
														_lowerCAmelCase     :							str    =    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):
																												_lowerCAmelCase     :							Tuple    =    first_field.items()
																												_lowerCAmelCase     :							Dict    =    True
																					else:
																												try:
																																			_lowerCAmelCase     :							Dict    =    iter(__a)
																																			_lowerCAmelCase     :							Any    =    True
																												except TypeError:
																																			_lowerCAmelCase     :							Any    =    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
																																																	_lowerCAmelCase     :							Any    =    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     :							Any    =    element[1]
																					elif first_field is not None:
																												_lowerCAmelCase     :							Any    =    first_field
														else:
																					for field in class_fields:
																												_lowerCAmelCase     :							Dict    =    getattr(self,			field.name)
																												if v is not None:
																																			_lowerCAmelCase     :							Union[str, Any]    =    v







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

														'''simple docstring'''

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







							def    snake_case__      (   self,			*__a,			**__a):

														'''simple docstring'''

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







							def    snake_case__      (   self,			*__a,			**__a):

														'''simple docstring'''

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







							def    snake_case__      (   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(__a,			__a):
																					_lowerCAmelCase     :							Optional[int]    =    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__(__a,			__a)
														super().__setattr__(__a,			__a)







							def __setitem__(   self,			__a,			__a):

														'''simple docstring'''

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







							def    snake_case__      (   self):

														'''simple docstring'''

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



class   UpperCAmelCase_    (       a   ,					a):







							@classmethod
							def    snake_case__      (   cls,			__a):

														'''simple docstring'''

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



class   UpperCAmelCase_    (       a):
							lowerCamelCase__   			=		'longest'
							lowerCamelCase__   			=		'max_length'
							lowerCamelCase__   			=		'do_not_pad'



class   UpperCAmelCase_    (       a):
							lowerCamelCase__   			=		'pt'
							lowerCamelCase__   			=		'tf'
							lowerCamelCase__   			=		'np'
							lowerCamelCase__   			=		'jax'



class   UpperCAmelCase_    :







							def __init__(   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    context_managers
														_lowerCAmelCase     :							Dict    =    ExitStack()







							def __enter__(   self):

														'''simple docstring'''

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







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

														'''simple docstring'''

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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							str    =    infer_framework(_lowerCamelCase  )
							if framework == "tf":
														_lowerCAmelCase     :							Tuple    =    inspect.signature(model_class.call  )  # TensorFlow models
							elif framework == "pt":
														_lowerCAmelCase     :							str    =    inspect.signature(model_class.forward  )  # PyTorch models
							else:
														_lowerCAmelCase     :							Tuple    =    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				(					_lowerCamelCase  ):





							'''simple docstring'''




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





							'''simple docstring'''




							def _flatten_dict(_lowerCamelCase				, _lowerCamelCase=""				, _lowerCamelCase="."  ):
														for k, v in d.items():
																					_lowerCAmelCase     :							Dict    =    str(_lowerCamelCase  ) + delimiter + str(_lowerCamelCase  ) if parent_key else k
																					if v and isinstance(_lowerCamelCase				, _lowerCamelCase  ):
																												yield from flatten_dict(_lowerCamelCase				, _lowerCamelCase				, delimiter=_lowerCamelCase  ).items()
																					else:
																												yield key, v

							return dict(_flatten_dict(_lowerCamelCase				, _lowerCamelCase				, _lowerCamelCase  )  )






@contextmanager
def 				A				(					_lowerCamelCase				, _lowerCamelCase = False  ):





							'''simple docstring'''




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






def 				A				(					_lowerCamelCase				, _lowerCamelCase=None  ):





							'''simple docstring'''




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

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






def 				A				(					_lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




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

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






def 				A				(					_lowerCamelCase				, _lowerCamelCase=None  ):





							'''simple docstring'''




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

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






def 				A				(					_lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




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

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






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




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

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






def 				A				(					_lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




							for key, value in auto_map.items():
														if isinstance(_lowerCamelCase				, (tuple, list)  ):
																					_lowerCAmelCase     :							List[Any]    =    [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     :							Tuple    =    F"{repo_id}--{value}"

							return auto_map






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							for base_class in inspect.getmro(_lowerCamelCase  ):
														_lowerCAmelCase     :							Tuple    =    base_class.__module__
														_lowerCAmelCase     :							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}."  )







import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference





class  A__    (							__UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				Optional[int]         =  ShapEImgaImgPipeline
   __A   :				Tuple         =  ['''image''']
   __A   :				Any         =  ['''image''']
   __A   :				Optional[Any]         =  [
       '''num_images_per_prompt''',
       '''num_inference_steps''',
       '''generator''',
       '''latents''',
       '''guidance_scale''',
       '''frame_size''',
       '''output_type''',
       '''return_dict''',
   ]
   __A   :				Dict         =  False

   @property
   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          return 32

   @property
   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          return 32

   @property
   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          return self.time_input_dim * 4

   @property
   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          return 8

   @property
   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          torch.manual_seed(0)
          a__						:	Any =				CLIPVisionConfig(
              hidden_size=self.text_embedder_hidden_size					,  image_size=64					,  projection_dim=self.text_embedder_hidden_size					,  intermediate_size=37					,  num_attention_heads=4					,  num_channels=3					,  num_hidden_layers=5					,  patch_size=1					,  )

          a__						:	Dict =				CLIPVisionModel(lowercase)
          return model

   @property
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          a__						:	str =				CLIPImageProcessor(
              crop_size=224					,  do_center_crop=lowercase					,  do_normalize=lowercase					,  do_resize=lowercase					,  image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]					,  image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]					,  resample=3					,  size=224					,  )

          return image_processor

   @property
   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          torch.manual_seed(0)

          a__						:	str =				{
              'num_attention_heads': 2,
              'attention_head_dim': 16,
              'embedding_dim': self.time_input_dim,
              'num_embeddings': 32,
              'embedding_proj_dim': self.text_embedder_hidden_size,
              'time_embed_dim': self.time_embed_dim,
              'num_layers': 1,
              'clip_embed_dim': self.time_input_dim * 2,
              'additional_embeddings': 0,
              'time_embed_act_fn': 'gelu',
              'norm_in_type': 'layer',
              'embedding_proj_norm_type': 'layer',
              'encoder_hid_proj_type': None,
              'added_emb_type': None,
          }

          a__						:	Any =				PriorTransformer(**lowercase)
          return model

   @property
   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          torch.manual_seed(0)

          a__						:	List[Any] =				{
              'param_shapes': (
                  (self.renderer_dim, 93),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
              ),
              'd_latent': self.time_input_dim,
              'd_hidden': self.renderer_dim,
              'n_output': 12,
              'background': (
                  0.1,
                  0.1,
                  0.1,
              ),
          }
          a__						:	List[str] =				ShapERenderer(**lowercase)
          return model

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	Dict =				self.dummy_prior
          a__						:	List[str] =				self.dummy_image_encoder
          a__						:	int =				self.dummy_image_processor
          a__						:	str =				self.dummy_renderer

          a__						:	Optional[int] =				HeunDiscreteScheduler(
              beta_schedule='exp'					,  num_train_timesteps=1024					,  prediction_type='sample'					,  use_karras_sigmas=lowercase					,  clip_sample=lowercase					,  clip_sample_range=1.0					,  )
          a__						:	List[Any] =				{
              'prior': prior,
              'image_encoder': image_encoder,
              'image_processor': image_processor,
              'renderer': renderer,
              'scheduler': scheduler,
          }

          return components

   def 							__lowercase		(					self					,  lowercase					,  lowercase=0)			->						List[str]:







          '''simple docstring'''

          a__						:	List[str] =				floats_tensor((1, 3, 64, 64)					,  rng=random.Random(lowercase)).to(lowercase)

          if str(lowercase).startswith('mps'):
                 a__						:	List[str] =				torch.manual_seed(lowercase)
          else:
                 a__						:	str =				torch.Generator(device=lowercase).manual_seed(lowercase)
          a__						:	Tuple =				{
              'image': input_image,
              'generator': generator,
              'num_inference_steps': 1,
              'frame_size': 32,
              'output_type': 'np',
          }
          return inputs

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	int =				'cpu'

          a__						:	List[str] =				self.get_dummy_components()

          a__						:	Dict =				self.pipeline_class(**lowercase)
          a__						:	Optional[int] =				pipe.to(lowercase)

          pipe.set_progress_bar_config(disable=lowercase)

          a__						:	Tuple =				pipe(**self.get_dummy_inputs(lowercase))
          a__						:	Any =				output.images[0]
          a__						:	Any =				image[0, -3:, -3:, -1]

          assert image.shape == (20, 32, 32, 3)

          a__						:	List[str] =				np.array(
              [
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
              ])

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

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          self._test_inference_batch_consistent(batch_sizes=[1, 2])

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







          '''simple docstring'''

          a__						:	str =				torch_device == 'cpu'
          a__						:	Tuple =				True
          self._test_inference_batch_single_identical(
              batch_size=2					,  test_max_difference=lowercase					,  relax_max_difference=lowercase					,  )

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	List[str] =				self.get_dummy_components()
          a__						:	str =				self.pipeline_class(**lowercase)
          a__						:	List[str] =				pipe.to(lowercase)
          pipe.set_progress_bar_config(disable=lowercase)

          a__						:	Optional[Any] =				1
          a__						:	List[str] =				2

          a__						:	Optional[Any] =				self.get_dummy_inputs(lowercase)

          for key in inputs.keys():
                 if key in self.batch_params:
                        a__						:	Any =				batch_size * [inputs[key]]

          a__						:	int =				pipe(**lowercase					,  num_images_per_prompt=lowercase)[0]

          assert images.shape[0] == batch_size * num_images_per_prompt





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




   """simple docstring"""



   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__						:	str =				load_image(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png')
          a__						:	str =				load_numpy(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
              '/shap_e/test_shap_e_img2img_out.npy')
          a__						:	List[str] =				ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img')
          a__						:	Tuple =				pipe.to(lowercase)
          pipe.set_progress_bar_config(disable=lowercase)

          a__						:	List[Any] =				torch.Generator(device=lowercase).manual_seed(0)

          a__						:	Optional[int] =				pipe(
              lowercase					,  generator=lowercase					,  guidance_scale=3.0					,  num_inference_steps=64					,  frame_size=64					,  output_type='np'					,  ).images[0]

          assert images.shape == (20, 64, 64, 3)

          assert_mean_pixel_difference(lowercase					,  lowercase)


