





import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


@skip_mps
class     A     (SCREAMING_SNAKE_CASE  ,	unittest.TestCase       ):
			'''simple docstring'''




			__lowerCamelCase      :			Tuple							     =       VideoToVideoSDPipeline
			__lowerCamelCase      :			Tuple							     =       TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'''video'''}       ) - {'''image''', '''width''', '''height'''}
			__lowerCamelCase      :			Dict							     =       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''video'''}       ) - {'''image'''}
			__lowerCamelCase      :			Tuple							     =       PipelineTesterMixin.required_optional_params - {'''latents'''}
			__lowerCamelCase      :			Optional[int]							     =       False

			# No `output_type`.
			__lowerCamelCase      :			List[str]							     =       frozenset(
			    [
			        '''num_inference_steps''',
			        '''generator''',
			        '''latents''',
			        '''return_dict''',
			        '''callback''',
			        '''callback_steps''',
			    ]       )






			def   a_			(     self  :       List[str]  )      ->      Optional[int]:







					"""simple docstring"""






					torch.manual_seed(0  )
					A__     =  UNetaDConditionModel(
					    block_out_channels=(32, 64, 64, 64)				,      layers_per_block=2				,      sample_size=32				,      in_channels=4				,      out_channels=4				,      down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""")				,      up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""")				,      cross_attention_dim=32				,      attention_head_dim=4				,      )
					A__     =  DDIMScheduler(
					    beta_start=0.0_0_0_8_5				,      beta_end=0.0_1_2				,      beta_schedule="""scaled_linear"""				,      clip_sample=__lowerCAmelCase				,      set_alpha_to_one=__lowerCAmelCase				,      )
					torch.manual_seed(0  )
					A__     =  AutoencoderKL(
					    block_out_channels=[32, 64]				,      in_channels=3				,      out_channels=3				,      down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]				,      up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]				,      latent_channels=4				,      sample_size=1_28				,      )
					torch.manual_seed(0  )
					A__     =  CLIPTextConfig(
					    bos_token_id=0				,      eos_token_id=2				,      hidden_size=32				,      intermediate_size=37				,      layer_norm_eps=1e-05				,      num_attention_heads=4				,      num_hidden_layers=5				,      pad_token_id=1				,      vocab_size=10_00				,      hidden_act="""gelu"""				,      projection_dim=5_12				,      )
					A__     =  CLIPTextModel(__lowerCAmelCase  )
					A__     =  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""  )

					A__     =  {
					    """unet""": unet,
					    """scheduler""": scheduler,
					    """vae""": vae,
					    """text_encoder""": text_encoder,
					    """tokenizer""": tokenizer,
					}
					return components






			def   a_			(     self  :       str				,      __lowerCAmelCase  :       Optional[Any]				,      __lowerCAmelCase  :       Tuple=0  )      ->      Dict:







					"""simple docstring"""






					A__     =  floats_tensor((1, 3, 3, 32, 32)				,      rng=random.Random(__lowerCAmelCase  )  ).to(__lowerCAmelCase  )

					if str(__lowerCAmelCase  ).startswith("""mps"""  ):
							A__     =  torch.manual_seed(__lowerCAmelCase  )
					else:
							A__     =  torch.Generator(device=__lowerCAmelCase  ).manual_seed(__lowerCAmelCase  )
					A__     =  {
					    """prompt""": """A painting of a squirrel eating a burger""",
					    """video""": video,
					    """generator""": generator,
					    """num_inference_steps""": 2,
					    """guidance_scale""": 6.0,
					    """output_type""": """pt""",
					}
					return inputs






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







					"""simple docstring"""






					A__     =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
					A__     =  self.get_dummy_components()
					A__     =  VideoToVideoSDPipeline(**__lowerCAmelCase  )
					A__     =  sd_pipe.to(__lowerCAmelCase  )
					sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase  )

					A__     =  self.get_dummy_inputs(__lowerCAmelCase  )
					A__     =  """np"""
					A__     =  sd_pipe(**__lowerCAmelCase  ).frames
					A__     =  frames[0][-3:, -3:, -1]

					assert frames[0].shape == (32, 32, 3)
					A__     =  np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31]  )

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






			@unittest.skipIf(
			    torch_device != """cuda""" or not is_xformers_available()				,      reason="""XFormers attention is only available with CUDA and `xformers` installed"""				,      )
			def   a_			(     self  :       Optional[int]  )      ->      Optional[Any]:







					"""simple docstring"""






					self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowerCAmelCase				,      expected_max_diff=5e-3  )






			@unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""  )
			def   a_			(     self  :       Optional[int]  )      ->      str:







					"""simple docstring"""






					pass






			@unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""  )
			def   a_			(     self  :       Any  )      ->      Optional[Any]:







					"""simple docstring"""






					pass






			@unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline."""  )
			def   a_			(     self  :       Tuple  )      ->      Union[str, Any]:







					"""simple docstring"""






					pass







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







					"""simple docstring"""






					return super().test_progress_bar()


@slow
@skip_mps
class     A     (unittest.TestCase       ):
			'''simple docstring'''




			def   a_			(     self  :       List[Any]  )      ->      int:







					"""simple docstring"""






					A__     =  VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL"""				,      torch_dtype=torch.floataa  )
					pipe.enable_model_cpu_offload()

					# 10 frames
					A__     =  torch.Generator(device="""cpu"""  ).manual_seed(0  )
					A__     =  torch.randn((1, 10, 3, 10_24, 5_76)				,      generator=__lowerCAmelCase  )
					A__     =  video.to("""cuda"""  )

					A__     =  """Spiderman is surfing"""

					A__     =  pipe(__lowerCAmelCase				,      video=__lowerCAmelCase				,      generator=__lowerCAmelCase				,      num_inference_steps=3				,      output_type="""pt"""  ).frames

					A__     =  np.array([-1.0_4_5_8_9_8_4, -1.1_2_7_9_2_9_7, -0.9_6_6_3_0_8_6, -0.9_1_5_0_3_9_0_6, -0.7_5_0_9_7_6_5_6]  )
					assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array  ).sum() < 1e-2










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     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			def __get__(     self  :       List[Any]				,      __lowerCAmelCase  :       List[Any]				,      __lowerCAmelCase  :       str=None  )      ->      List[str]:







					"""simple docstring"""






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







def   __lowerCamelCase   (				__a  :Dict       )						->							Optional[int]:






		"""simple docstring"""

		A__     =  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  :Any       )						->							Any:






		"""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  :Optional[Any]       )						->							Union[str, Any]:






		"""simple docstring"""

		return isinstance(__a       ,	np.ndarray       )







def   __lowerCamelCase   (				__a  :int       )						->							List[Any]:






		"""simple docstring"""

		return _is_numpy(__a       )







def   __lowerCamelCase   (				__a  :Dict       )						->							Union[str, Any]:






		"""simple docstring"""

		import torch

		return isinstance(__a       ,	torch.Tensor       )







def   __lowerCamelCase   (				__a  :Dict       )						->							Any:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :List[str]       )						->							Any:






		"""simple docstring"""

		import torch

		return isinstance(__a       ,	torch.device       )







def   __lowerCamelCase   (				__a  :Any       )						->							int:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :str       )						->							List[str]:






		"""simple docstring"""

		import torch

		if isinstance(__a       ,	__a       ):
				if hasattr(__a       ,	__a       ):
						A__     =  getattr(__a       ,	__a       )
				else:
						return False
		return isinstance(__a       ,	torch.dtype       )







def   __lowerCamelCase   (				__a  :str       )						->							List[str]:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :Any       )						->							Optional[int]:






		"""simple docstring"""

		import tensorflow as tf

		return isinstance(__a       ,	tf.Tensor       )







def   __lowerCamelCase   (				__a  :int       )						->							Optional[int]:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :Tuple       )						->							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  :Optional[Any]       )						->							List[Any]:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :Any       )						->							int:






		"""simple docstring"""

		import jax.numpy as jnp  # noqa: F811

		return isinstance(__a       ,	jnp.ndarray       )







def   __lowerCamelCase   (				__a  :Union[str, Any]       )						->							int:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :str       )						->							Dict:






		"""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  :Tuple       )						->							int:






		"""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     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




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







					"""simple docstring"""






					A__     =  fields(self  )

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

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

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






			def __delitem__(     self  :       int				,      *__lowerCAmelCase  :       Tuple				,      **__lowerCAmelCase  :       List[str]  )      ->      Optional[int]:







					"""simple docstring"""






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






			def   a_			(     self  :       List[Any]				,      *__lowerCAmelCase  :       List[str]				,      **__lowerCAmelCase  :       List[Any]  )      ->      List[str]:







					"""simple docstring"""






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






			def   a_			(     self  :       Dict				,      *__lowerCAmelCase  :       Tuple				,      **__lowerCAmelCase  :       Union[str, Any]  )      ->      Optional[Any]:







					"""simple docstring"""






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






			def   a_			(     self  :       Tuple				,      *__lowerCAmelCase  :       int				,      **__lowerCAmelCase  :       List[str]  )      ->      Optional[Any]:







					"""simple docstring"""






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






			def __getitem__(     self  :       Tuple				,      __lowerCAmelCase  :       Tuple  )      ->      int:







					"""simple docstring"""






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






			def __setattr__(     self  :       Optional[Any]				,      __lowerCAmelCase  :       List[str]				,      __lowerCAmelCase  :       Tuple  )      ->      Dict:







					"""simple docstring"""






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






			def __setitem__(     self  :       Any				,      __lowerCAmelCase  :       int				,      __lowerCAmelCase  :       Dict  )      ->      List[Any]:







					"""simple docstring"""






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







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







					"""simple docstring"""






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


class     A     (SCREAMING_SNAKE_CASE  ,	SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			@classmethod
			def   a_			(     cls  :       str				,      __lowerCAmelCase  :       Optional[Any]  )      ->      Any:







					"""simple docstring"""






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


class     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			__lowerCamelCase      :			Optional[int]							     =       '''longest'''
			__lowerCamelCase      :			str							     =       '''max_length'''
			__lowerCamelCase      :			List[str]							     =       '''do_not_pad'''


class     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			__lowerCamelCase      :			str							     =       '''pt'''
			__lowerCamelCase      :			int							     =       '''tf'''
			__lowerCamelCase      :			Dict							     =       '''np'''
			__lowerCamelCase      :			Union[str, Any]							     =       '''jax'''


class     A     :
			'''simple docstring'''




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







					"""simple docstring"""






					A__     =  context_managers
					A__     =  ExitStack()






			def __enter__(     self  :       Dict  )      ->      int:







					"""simple docstring"""






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







			def __exit__(     self  :       Any				,      *__lowerCAmelCase  :       Dict				,      **__lowerCAmelCase  :       Dict  )      ->      Any:







					"""simple docstring"""






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







def   __lowerCamelCase   (				__a  :List[str]       )						->							Dict:






		"""simple docstring"""

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






		"""simple docstring"""

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






		"""simple docstring"""

		def _flatten_dict(__a  :Any       ,	__a  :Optional[int]=""       ,	__a  :Optional[int]="."       ):
				for k, v in d.items():
						A__     =  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  :Dict       ,	__a  :bool = False       )						->							List[Any]:






		"""simple docstring"""

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







def   __lowerCamelCase   (				__a  :Optional[Any]       ,	__a  :Optional[Any]=None       )						->							List[str]:






		"""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  :Optional[Any]       ,	__a  :Optional[Any]       )						->							List[str]:






		"""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  :Optional[Any]       ,	__a  :List[Any]=None       )						->							Union[str, 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  :Tuple       ,	__a  :Any       )						->							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  :Optional[int]       )						->							Dict:






		"""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  :Union[str, Any]       ,	__a  :List[Any]       )						->							Optional[int]:






		"""simple docstring"""

		for key, value in auto_map.items():
				if isinstance(__a       ,	(tuple, list)       ):
						A__     =  [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:
						A__     =  F'{repo_id}--{value}'

		return auto_map







def   __lowerCamelCase   (				__a  :List[str]       )						->							Union[str, Any]:






		"""simple docstring"""

		for base_class in inspect.getmro(__a       ):
				A__     =  base_class.__module__
				A__     =  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}.'       )



