

'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available


lowerCAmelCase__     :   Union[str, Any]										= {
    "configuration_audio_spectrogram_transformer": [
        "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "ASTConfig",
    ]
}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowerCAmelCase__     :   List[Any]										= [
						    "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
						    "ASTForAudioClassification",
						    "ASTModel",
						    "ASTPreTrainedModel",
						]

try:
						if not is_speech_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowerCAmelCase__     :   Union[str, Any]										= ["ASTFeatureExtractor"]

if TYPE_CHECKING:
						from .configuration_audio_spectrogram_transformer import (
						    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
						    ASTConfig,
						)

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_audio_spectrogram_transformer import (
												    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
												    ASTForAudioClassification,
												    ASTModel,
												    ASTPreTrainedModel,
												)

						try:
												if not is_speech_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor


else:
						import sys

						lowerCAmelCase__     :   int										= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)









'''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 					lowercase						(  a_ ):


							def __get__(			self    ,			_snake_case    ,			_snake_case=None)							->				List[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')
								UpperCAmelCase_		:      str       	=					'__cached_' + self.fget.__name__
								UpperCAmelCase_		:      Union[str, Any]       	=					getattr(_snake_case    ,			_snake_case    ,			_snake_case)
								if cached is None:
									UpperCAmelCase_		:      Union[str, Any]       	=					self.fget(_snake_case)
									setattr(_snake_case    ,			_snake_case    ,			_snake_case)
								return cached







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[Any]:
	UpperCAmelCase_		:      List[str]       	=					val.lower()
	if val in {"y", "yes", "t", "true", "on", "1"}:
		return 1
	if val in {"n", "no", "f", "false", "off", "0"}:
		return 0
	raise ValueError(f"""invalid truth value {val!r}"""  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    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 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[Any]:
	return isinstance(UpperCamelCase   ,np.ndarray  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Union[str, Any]:
	return _is_numpy(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    List[Any]:
	import torch

	return isinstance(UpperCamelCase   ,torch.Tensor  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[int]:
	return False if not is_torch_available() else _is_torch(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    str:
	import torch

	return isinstance(UpperCamelCase   ,torch.device  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    str:
	return False if not is_torch_available() else _is_torch_device(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[Any]:
	import torch

	if isinstance(UpperCamelCase   ,UpperCamelCase  ):
		if hasattr(UpperCamelCase   ,UpperCamelCase  ):
			UpperCAmelCase_		:      Any       	=					getattr(UpperCamelCase   ,UpperCamelCase  )
		else:
			return False
	return isinstance(UpperCamelCase   ,torch.dtype  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    List[Any]:
	return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    List[Any]:
	import tensorflow as tf

	return isinstance(UpperCamelCase   ,tf.Tensor  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Tuple:
	return False if not is_tf_available() else _is_tensorflow(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Tuple:
	import tensorflow as tf

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







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    List[Any]:
	return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[Any]:
	import jax.numpy as jnp  # noqa: F811

	return isinstance(UpperCamelCase   ,jnp.ndarray  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Tuple:
	return False if not is_flax_available() else _is_jax(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    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 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[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 					lowercase						(  a_ ):


							def 						_snake_case							(			self)							->				Any:
								UpperCAmelCase_		:      Dict       	=					fields(self)

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

								UpperCAmelCase_		:      int       	=					getattr(self    ,			class_fields[0].name)
								UpperCAmelCase_		:      Union[str, Any]       	=					all(getattr(self    ,			field.name) is None for field in class_fields[1:])

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


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


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


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


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


							def __getitem__(			self    ,			_snake_case)							->				Optional[Any]:
								if isinstance(_snake_case    ,			_snake_case):
									UpperCAmelCase_		:      Dict       	=					dict(self.items())
									return inner_dict[k]
								else:
									return self.to_tuple()[k]


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


							def __setitem__(			self    ,			_snake_case    ,			_snake_case)							->				List[Any]:
								# Will raise a KeyException if needed
								super().__setitem__(_snake_case    ,			_snake_case)
								# Don't call self.__setattr__ to avoid recursion errors
								super().__setattr__(_snake_case    ,			_snake_case)





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



class 					lowercase						(  a_,					a_ ):


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



class 					lowercase						(  a_ ):
							_lowerCamelCase		:      Tuple=   "longest"
							_lowerCamelCase		:      Tuple=   "max_length"
							_lowerCamelCase		:      int=   "do_not_pad"



class 					lowercase						(  a_ ):
							_lowerCamelCase		:      Union[str, Any]=   "pt"
							_lowerCamelCase		:      Any=   "tf"
							_lowerCamelCase		:      Dict=   "np"
							_lowerCamelCase		:      Tuple=   "jax"



class 					lowercase						:


							def __init__(			self    ,			_snake_case)							->				Tuple:
								UpperCAmelCase_		:      int       	=					context_managers
								UpperCAmelCase_		:      Any       	=					ExitStack()


							def __enter__(			self)							->				Optional[Any]:
								for context_manager in self.context_managers:
									self.stack.enter_context(_snake_case)





							def __exit__(			self    ,			*_snake_case    ,			**_snake_case)							->				List[Any]:
								self.stack.__exit__(*_snake_case    ,			**_snake_case)







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    int:
	UpperCAmelCase_		:      Dict       	=					infer_framework(UpperCamelCase  )
	if framework == "tf":
		UpperCAmelCase_		:      Optional[int]       	=					inspect.signature(model_class.call  )  # TensorFlow models
	elif framework == "pt":
		UpperCAmelCase_		:      Tuple       	=					inspect.signature(model_class.forward  )  # PyTorch models
	else:
		UpperCAmelCase_		:      str       	=					inspect.signature(model_class.__call__  )  # Flax models

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

	return False







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Optional[int]:
	UpperCAmelCase_		:      Optional[Any]       	=					model_class.__name__
	UpperCAmelCase_		:      Optional[int]       	=					infer_framework(UpperCamelCase  )
	if framework == "tf":
		UpperCAmelCase_		:      Any       	=					inspect.signature(model_class.call  )  # TensorFlow models
	elif framework == "pt":
		UpperCAmelCase_		:      Optional[int]       	=					inspect.signature(model_class.forward  )  # PyTorch models
	else:
		UpperCAmelCase_		:      str       	=					inspect.signature(model_class.__call__  )  # Flax models

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







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase = ""   ,UpperCamelCase = "."  )    ->    List[Any]:

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

	return dict(_flatten_dict(UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )  )







@contextmanager
def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase = False  )    ->    Any:
	if use_temp_dir:
		with tempfile.TemporaryDirectory() as tmp_dir:
			yield tmp_dir
	else:
		yield working_dir







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase=None  )    ->    Optional[Any]:
	if is_numpy_array(UpperCamelCase  ):
		return np.transpose(UpperCamelCase   ,axes=UpperCamelCase  )
	elif is_torch_tensor(UpperCamelCase  ):
		return array.T if axes is None else array.permute(*UpperCamelCase  )
	elif is_tf_tensor(UpperCamelCase  ):
		import tensorflow as tf

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







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    int:
	if is_numpy_array(UpperCamelCase  ):
		return np.reshape(UpperCamelCase   ,UpperCamelCase  )
	elif is_torch_tensor(UpperCamelCase  ):
		return array.reshape(*UpperCamelCase  )
	elif is_tf_tensor(UpperCamelCase  ):
		import tensorflow as tf

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







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase=None  )    ->    Optional[int]:
	if is_numpy_array(UpperCamelCase  ):
		return np.squeeze(UpperCamelCase   ,axis=UpperCamelCase  )
	elif is_torch_tensor(UpperCamelCase  ):
		return array.squeeze() if axis is None else array.squeeze(dim=UpperCamelCase  )
	elif is_tf_tensor(UpperCamelCase  ):
		import tensorflow as tf

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







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    Optional[int]:
	if is_numpy_array(UpperCamelCase  ):
		return np.expand_dims(UpperCamelCase   ,UpperCamelCase  )
	elif is_torch_tensor(UpperCamelCase  ):
		return array.unsqueeze(dim=UpperCamelCase  )
	elif is_tf_tensor(UpperCamelCase  ):
		import tensorflow as tf

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







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    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 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    Dict:
	for key, value in auto_map.items():
		if isinstance(UpperCamelCase   ,(tuple, list)  ):
			UpperCAmelCase_		:      Union[str, 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:
			UpperCAmelCase_		:      Any       	=					f"""{repo_id}--{value}"""

	return auto_map







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase  )    ->    Union[str, Any]:
	for base_class in inspect.getmro(UpperCamelCase  ):
		UpperCAmelCase_		:      int       	=					base_class.__module__
		UpperCAmelCase_		:      Dict       	=					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}."""  )






