





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					(					lowerCAmelCase				):

			'''simple docstring'''







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



				'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   Union[str, Any]:







	'''simple docstring'''







	lowerCamelCase__              =	val.lower()
	if val in {"y", "yes", "t", "true", "on", "1"}:
		return 1
	if val in {"n", "no", "f", "false", "off", "0"}:
		return 0
	raise ValueError(F'invalid truth value {val!r}'							)





def lowerCAmelCase__(__snake_case							)       ->   List[str]:







	'''simple docstring'''







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

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

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

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

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

	return isinstance(__snake_case ,np.ndarray							)





def lowerCAmelCase__(__snake_case							)       ->   Any:







	'''simple docstring'''







	return isinstance(__snake_case ,np.ndarray							)





def lowerCAmelCase__(__snake_case							)       ->   Dict:







	'''simple docstring'''







	return _is_numpy(__snake_case							)





def lowerCAmelCase__(__snake_case							)       ->   int:







	'''simple docstring'''







	import torch

	return isinstance(__snake_case ,torch.Tensor							)





def lowerCAmelCase__(__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   str:







	'''simple docstring'''







	import torch

	return isinstance(__snake_case ,torch.device							)





def lowerCAmelCase__(__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   List[Any]:







	'''simple docstring'''







	import torch

	if isinstance(__snake_case ,__snake_case							):
		if hasattr(__snake_case ,__snake_case							):
			lowerCamelCase__              =	getattr(__snake_case ,__snake_case							)
		else:
			return False
	return isinstance(__snake_case ,torch.dtype							)





def lowerCAmelCase__(__snake_case							)       ->   Any:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   Optional[Any]:







	'''simple docstring'''







	import tensorflow as tf

	return isinstance(__snake_case ,tf.Tensor							)





def lowerCAmelCase__(__snake_case							)       ->   Union[str, Any]:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







	import tensorflow as tf

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





def lowerCAmelCase__(__snake_case							)       ->   str:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   List[str]:







	'''simple docstring'''







	import jax.numpy as jnp  # noqa: F811

	return isinstance(__snake_case ,jnp.ndarray							)





def lowerCAmelCase__(__snake_case							)       ->   str:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   Optional[Any]:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   Any:







	'''simple docstring'''







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






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				lowerCamelCase__              =	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.'							)

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

				if other_fields_are_none and not is_tensor(__lowerCAmelCase							):
					if isinstance(__lowerCAmelCase ,						__lowerCAmelCase							):
						lowerCamelCase__              =	first_field.items()
						lowerCamelCase__              =	True
					else:
						try:
							lowerCamelCase__              =	iter(__lowerCAmelCase							)
							lowerCamelCase__              =	True
						except TypeError:
							lowerCamelCase__              =	False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
					if first_field_iterator:
						for idx, element in enumerate(__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
									lowerCamelCase__              =	first_field
								else:
									# If we have a mixed iterator, raise an error
									raise ValueError(
									    F'Cannot set key/value for {element}. It needs to be a tuple (key, value).'							)
								break
							setattr(self ,						element[0] ,						element[1]							)
							if element[1] is not None:
								lowerCamelCase__              =	element[1]
					elif first_field is not None:
						lowerCamelCase__              =	first_field
				else:
					for field in class_fields:
						lowerCamelCase__              =	getattr(self ,						field.name							)
						if v is not None:
							lowerCamelCase__              =	v





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



				'''simple docstring'''







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





			def 	__lowerCamelCase       (					self ,						*__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







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





			def 	__lowerCamelCase       (					self ,						*__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







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





			def 	__lowerCamelCase       (					self ,						*__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







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





			def __getitem__(					self ,						__lowerCAmelCase							):



				'''simple docstring'''







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





			def __setattr__(					self ,						__lowerCAmelCase ,						__lowerCAmelCase							):



				'''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 ,						__lowerCAmelCase ,						__lowerCAmelCase							):



				'''simple docstring'''







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





			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







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






class       __A					(					lowerCAmelCase    ,       lowerCAmelCase				):

			'''simple docstring'''







			@classmethod
			def 	__lowerCamelCase       (					cls ,						__lowerCAmelCase							):



				'''simple docstring'''







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






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		"""longest"""
			lowerCAmelCase_							  =		"""max_length"""
			lowerCAmelCase_							  =		"""do_not_pad"""






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		"""pt"""
			lowerCAmelCase_							  =		"""tf"""
			lowerCAmelCase_							  =		"""np"""
			lowerCAmelCase_							  =		"""jax"""






class       __A					:

			'''simple docstring'''







			def __init__(					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	context_managers
				lowerCamelCase__              =	ExitStack()





			def __enter__(					self							):



				'''simple docstring'''







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





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



				'''simple docstring'''







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





def lowerCAmelCase__(__snake_case							)       ->   str:







	'''simple docstring'''







	lowerCamelCase__              =	infer_framework(__snake_case							)
	if framework == "tf":
		lowerCamelCase__              =	inspect.signature(model_class.call							)  # TensorFlow models
	elif framework == "pt":
		lowerCamelCase__              =	inspect.signature(model_class.forward							)  # PyTorch models
	else:
		lowerCamelCase__              =	inspect.signature(model_class.__call__							)  # Flax models

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

	return False





def lowerCAmelCase__(__snake_case							)       ->   Optional[Any]:







	'''simple docstring'''







	lowerCamelCase__              =	model_class.__name__
	lowerCamelCase__              =	infer_framework(__snake_case							)
	if framework == "tf":
		lowerCamelCase__              =	inspect.signature(model_class.call							)  # TensorFlow models
	elif framework == "pt":
		lowerCamelCase__              =	inspect.signature(model_class.forward							)  # PyTorch models
	else:
		lowerCamelCase__              =	inspect.signature(model_class.__call__							)  # Flax models

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





def lowerCAmelCase__(__snake_case ,__snake_case = "" ,__snake_case = "."							)       ->   Union[str, Any]:







	'''simple docstring'''







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

	return dict(_flatten_dict(__snake_case ,__snake_case ,__snake_case							)							)





@contextmanager
def lowerCAmelCase__(__snake_case ,__snake_case = False							)       ->   List[Any]:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case ,__snake_case=None							)       ->   List[Any]:







	'''simple docstring'''







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

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





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   List[str]:







	'''simple docstring'''







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

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





def lowerCAmelCase__(__snake_case ,__snake_case=None							)       ->   Union[str, Any]:







	'''simple docstring'''







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

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





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   int:







	'''simple docstring'''







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

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





def lowerCAmelCase__(__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







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

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





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   Optional[Any]:







	'''simple docstring'''







	for key, value in auto_map.items():
		if isinstance(__snake_case ,(tuple, list)							):
			lowerCamelCase__              =	[F'{repo_id}--{v}' if (v is not None and '''--''' not in v) else v for v in value]
		elif value is not None and "--" not in value:
			lowerCamelCase__              =	F'{repo_id}--{value}'

	return auto_map





def lowerCAmelCase__(__snake_case							)       ->   Dict:







	'''simple docstring'''







	for base_class in inspect.getmro(__snake_case							):
		lowerCamelCase__              =	base_class.__module__
		lowerCamelCase__              =	base_class.__name__
		if module.startswith('''tensorflow'''							) or module.startswith('''keras'''							) or name == "TFPreTrainedModel":
			return "tf"
		elif module.startswith('''torch'''							) or name == "PreTrainedModel":
			return "pt"
		elif module.startswith('''flax'''							) or module.startswith('''jax'''							) or name == "FlaxPreTrainedModel":
			return "flax"
	else:
		raise TypeError(F'Could not infer framework from class {model_class}.'							)










import string
from math import logaa





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   int:







	'''simple docstring'''







	lowerCamelCase__              =	document.translate(
	    str.maketrans('''''' ,'''''' ,string.punctuation							)							).replace('''\n''' ,''''''							)
	lowerCamelCase__              =	document_without_punctuation.split(''' '''							)  # word tokenization
	return len([word for word in tokenize_document if word.lower() == term.lower()]							)





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   tuple[int, int]:







	'''simple docstring'''







	lowerCamelCase__              =	corpus.lower().translate(
	    str.maketrans('''''' ,'''''' ,string.punctuation							)							)  # strip all punctuation and replace it with ''
	lowerCamelCase__              =	corpus_without_punctuation.split('''\n'''							)
	lowerCamelCase__              =	term.lower()
	return (len([doc for doc in docs if term in doc]							), len(__snake_case							))





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case=False							)       ->   float:







	'''simple docstring'''







	if smoothing:
		if n == 0:
			raise ValueError('''log10(0) is undefined.'''							)
		return round(1 + logaa(n / (1 + df)							) ,3							)

	if df == 0:
		raise ZeroDivisionError('''df must be > 0'''							)
	elif n == 0:
		raise ValueError('''log10(0) is undefined.'''							)
	return round(logaa(n / df							) ,3							)





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   float:







	'''simple docstring'''







	return round(tf * idf ,3							)



