




'''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      A       (						_a       ):







							def __get__(    self			:    Tuple				,     lowerCAmelCase_			:    Dict				,     lowerCAmelCase_			:    Union[str, Any]=None   )     ->				Optional[Any]:


														"""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 						snake_case_       (UpperCamelCase			:    List[str] ):





							'''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 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    Optional[int] ):





							'''simple docstring'''


							return isinstance(UpperCamelCase					,		np.ndarray )
def 						snake_case_       (UpperCamelCase			:    Tuple ):





							'''simple docstring'''


							return _is_numpy(UpperCamelCase )
def 						snake_case_       (UpperCamelCase			:    List[Any] ):





							'''simple docstring'''


							import torch

							return isinstance(UpperCamelCase					,		torch.Tensor )
def 						snake_case_       (UpperCamelCase			:    Tuple ):





							'''simple docstring'''


							return False if not is_torch_available() else _is_torch(UpperCamelCase )
def 						snake_case_       (UpperCamelCase			:    Union[str, Any] ):





							'''simple docstring'''


							import torch

							return isinstance(UpperCamelCase					,		torch.device )
def 						snake_case_       (UpperCamelCase			:    Union[str, Any] ):





							'''simple docstring'''


							return False if not is_torch_available() else _is_torch_device(UpperCamelCase )
def 						snake_case_       (UpperCamelCase			:    List[Any] ):





							'''simple docstring'''


							import torch

							if isinstance(UpperCamelCase					,		UpperCamelCase ):
														if hasattr(UpperCamelCase					,		UpperCamelCase ):
																					_a      	=							getattr(UpperCamelCase					,		UpperCamelCase )
														else:
																					return False
							return isinstance(UpperCamelCase					,		torch.dtype )
def 						snake_case_       (UpperCamelCase			:    Tuple ):





							'''simple docstring'''


							return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase )
def 						snake_case_       (UpperCamelCase			:    Union[str, Any] ):





							'''simple docstring'''


							import tensorflow as tf

							return isinstance(UpperCamelCase					,		tf.Tensor )
def 						snake_case_       (UpperCamelCase			:    Union[str, Any] ):





							'''simple docstring'''


							return False if not is_tf_available() else _is_tensorflow(UpperCamelCase )
def 						snake_case_       (UpperCamelCase			:    Union[str, Any] ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


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





							'''simple docstring'''


							import jax.numpy as jnp  # noqa: F811

							return isinstance(UpperCamelCase					,		jnp.ndarray )
def 						snake_case_       (UpperCamelCase			:    Optional[Any] ):





							'''simple docstring'''


							return False if not is_flax_available() else _is_jax(UpperCamelCase )
def 						snake_case_       (UpperCamelCase			:    Union[str, Any] ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    Optional[int] ):





							'''simple docstring'''


							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      A       (						_a       ):







							def   __lowerCAmelCase     (    self			:    Tuple   )     ->				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			:    Any				,     *lowerCAmelCase_			:    List[str]				,     **lowerCAmelCase_			:    Any   )     ->				List[str]:


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







							def   __lowerCAmelCase     (    self			:    Union[str, Any]				,     *lowerCAmelCase_			:    Optional[Any]				,     **lowerCAmelCase_			:    str   )     ->				List[Any]:


														"""simple docstring"""


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







							def __getitem__(    self			:    Dict				,     lowerCAmelCase_			:    Optional[Any]   )     ->				int:


														"""simple docstring"""


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







							def __setattr__(    self			:    List[Any]				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    Union[str, Any]   )     ->				Optional[Any]:


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


														"""simple docstring"""


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







							def   __lowerCAmelCase     (    self			:    Optional[Any]   )     ->				Tuple[Any]:


														"""simple docstring"""


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



class      A       (						_a	,_a       ):







							@classmethod
							def   __lowerCAmelCase     (    cls			:    List[Any]				,     lowerCAmelCase_			:    Optional[Any]   )     ->				List[Any]:


														"""simple docstring"""


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



class      A       (						_a       ):
							lowercase_							     =							'longest'
							lowercase_							     =							'max_length'
							lowercase_							     =							'do_not_pad'



class      A       (						_a       ):
							lowercase_							     =							'pt'
							lowercase_							     =							'tf'
							lowercase_							     =							'np'
							lowercase_							     =							'jax'



class      A       :







							def __init__(    self			:    str				,     lowerCAmelCase_			:    List[ContextManager]   )     ->				Tuple:


														"""simple docstring"""


														_a      	=							context_managers
														_a      	=							ExitStack()







							def __enter__(    self			:    str   )     ->				List[str]:


														"""simple docstring"""


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







							def __exit__(    self			:    List[Any]				,     *lowerCAmelCase_			:    List[str]				,     **lowerCAmelCase_			:    List[Any]   )     ->				str:


														"""simple docstring"""


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



def 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


							_a      	=							infer_framework(UpperCamelCase )
							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 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


							_a      	=							model_class.__name__
							_a      	=							infer_framework(UpperCamelCase )
							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 						snake_case_       (UpperCamelCase			:    MutableMapping					,		UpperCamelCase			:    str = ""					,		UpperCamelCase			:    str = "." ):





							'''simple docstring'''


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





							'''simple docstring'''


							if use_temp_dir:
														with tempfile.TemporaryDirectory() as tmp_dir:
																					yield tmp_dir
							else:
														yield working_dir
def 						snake_case_       (UpperCamelCase			:    Optional[Any]					,		UpperCamelCase			:    Any=None ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    Union[str, Any]					,		UpperCamelCase			:    List[Any] ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    Optional[Any]					,		UpperCamelCase			:    Optional[int]=None ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    Optional[Any]					,		UpperCamelCase			:    Any ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


							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 						snake_case_       (UpperCamelCase			:    Optional[int]					,		UpperCamelCase			:    List[Any] ):





							'''simple docstring'''


							for key, value in auto_map.items():
														if isinstance(UpperCamelCase					,		(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 						snake_case_       (UpperCamelCase			:    Optional[int] ):





							'''simple docstring'''


							for base_class in inspect.getmro(UpperCamelCase ):
														_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}.' )






"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available


A		=						{}

try:
			if not is_sentencepiece_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						['GPTSw3Tokenizer']


if TYPE_CHECKING:
			try:
						if not is_sentencepiece_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .tokenization_gpt_swa import GPTSwaTokenizer

else:
			import sys

			A		=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



