





'''simple docstring'''




from __future__ import annotations






def 	_lowerCAmelCase      (  __snake_case  :			int			,							__snake_case  :			int      )					->					tuple[int, int]:
     if b == 0:
          return (1, 0)
     ((__A)			,(__A))						:			Tuple								=	extended_euclid(__snake_case			,							a % b      )
     __A						:			Dict								=	a // b
     return (y, x - k * y)






def 	_lowerCAmelCase      (  __snake_case  :			int			,							__snake_case  :			int			,							__snake_case  :			int			,							__snake_case  :			int      )					->					int:
     ((__A)			,(__A))						:			Optional[Any]								=	extended_euclid(__snake_case			,							__snake_case      )
     __A						:			List[str]								=	na * na
     __A						:			List[str]								=	ra * x * na + ra * y * na
     return (n % m + m) % m






def 	_lowerCAmelCase      (  __snake_case  :			int			,							__snake_case  :			int      )					->					int:
     ((__A)			,(__A))						:			Tuple								=	extended_euclid(__snake_case			,							__snake_case      )
     if b < 0:
          __A						:			Optional[int]								=	(b % n + n) % n
     return b






def 	_lowerCAmelCase      (  __snake_case  :			int			,							__snake_case  :			int			,							__snake_case  :			int			,							__snake_case  :			int      )					->					int:
     __A			,__A						:			int								=	invert_modulo(__snake_case			,							__snake_case      ), invert_modulo(__snake_case			,							__snake_case      )
     __A						:			List[Any]								=	na * na
     __A						:			str								=	ra * x * na + ra * y * na
     return (n % m + m) % m


if __name__ == "__main__":
  from doctest import testmod

  testmod(name='''chinese_remainder_theorem''', verbose=True)
  testmod(name='''chinese_remainder_theorem2''', verbose=True)
  testmod(name='''invert_modulo''', verbose=True)
  testmod(name='''extended_euclid''', verbose=True)






'''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 			SCREAMING_SNAKE_CASE   (a__							):


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

          '''simple docstring'''






          if obj is None:
               return self
          if self.fget is None:
               raise AttributeError('unreadable attribute')
          __A						:			Optional[Any]								=	'__cached_' + self.fget.__name__
          __A						:			Union[str, Any]								=	getattr(_UpperCAmelCase						,     _UpperCAmelCase						,     _UpperCAmelCase)
          if cached is None:
               __A						:			int								=	self.fget(_UpperCAmelCase)
               setattr(_UpperCAmelCase						,     _UpperCAmelCase						,     _UpperCAmelCase)
          return cached






def 	_lowerCAmelCase      (  __snake_case  :			Optional[Any]      )					->					Tuple:
     __A						:			Dict								=	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  :			int      )					->					Tuple:
     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  :			Dict      )					->					List[str]:
     return isinstance(__snake_case			,							np.ndarray      )






def 	_lowerCAmelCase      (  __snake_case  :			Optional[int]      )					->					Any:
     return _is_numpy(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			int      )					->					Union[str, Any]:
     import torch

     return isinstance(__snake_case			,							torch.Tensor      )






def 	_lowerCAmelCase      (  __snake_case  :			str      )					->					Optional[int]:
     return False if not is_torch_available() else _is_torch(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			Any      )					->					List[Any]:
     import torch

     return isinstance(__snake_case			,							torch.device      )






def 	_lowerCAmelCase      (  __snake_case  :			List[Any]      )					->					Dict:
     return False if not is_torch_available() else _is_torch_device(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			Union[str, Any]      )					->					Optional[int]:
     import torch

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






def 	_lowerCAmelCase      (  __snake_case  :			Optional[Any]      )					->					Any:
     return False if not is_torch_available() else _is_torch_dtype(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			List[str]      )					->					int:
     import tensorflow as tf

     return isinstance(__snake_case			,							tf.Tensor      )






def 	_lowerCAmelCase      (  __snake_case  :			Dict      )					->					List[Any]:
     return False if not is_tf_available() else _is_tensorflow(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			str      )					->					List[str]:
     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  :			Dict      )					->					Tuple:
     return False if not is_tf_available() else _is_tf_symbolic_tensor(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			int      )					->					Union[str, Any]:
     import jax.numpy as jnp  # noqa: F811

     return isinstance(__snake_case			,							jnp.ndarray      )






def 	_lowerCAmelCase      (  __snake_case  :			int      )					->					List[str]:
     return False if not is_flax_available() else _is_jax(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			Optional[Any]      )					->					Dict:
     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  :			Tuple      )					->					Optional[int]:
     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 			SCREAMING_SNAKE_CASE   (a__							):


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						:			List[str]								=	fields(self)

          # Safety and consistency checks
          if not len(_UpperCAmelCase):
               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						:			Tuple								=	getattr(self						,     class_fields[0].name)
          __A						:			Tuple								=	all(getattr(self						,     field.name) is None for field in class_fields[1:])

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


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

          '''simple docstring'''






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


     def 							SCREAMING_SNAKE_CASE  (						self						,     *_UpperCAmelCase						,     **_UpperCAmelCase):

          '''simple docstring'''






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


     def 							SCREAMING_SNAKE_CASE  (						self						,     *_UpperCAmelCase						,     **_UpperCAmelCase):

          '''simple docstring'''






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


     def 							SCREAMING_SNAKE_CASE  (						self						,     *_UpperCAmelCase						,     **_UpperCAmelCase):

          '''simple docstring'''






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


     def __getitem__(						self						,     _UpperCAmelCase):

          '''simple docstring'''






          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase):
               __A						:			List[Any]								=	dict(self.items())
               return inner_dict[k]
          else:
               return self.to_tuple()[k]


     def __setattr__(						self						,     _UpperCAmelCase						,     _UpperCAmelCase):

          '''simple docstring'''






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


     def __setitem__(						self						,     _UpperCAmelCase						,     _UpperCAmelCase):

          '''simple docstring'''






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


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






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




class 			SCREAMING_SNAKE_CASE   (a__ ,		a__							):


     @classmethod
     def 							SCREAMING_SNAKE_CASE  (						cls						,     _UpperCAmelCase):

          '''simple docstring'''






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




class 			SCREAMING_SNAKE_CASE   (a__							):
     lowerCAmelCase		      =	'''longest'''
     lowerCAmelCase		      =	'''max_length'''
     lowerCAmelCase		      =	'''do_not_pad'''




class 			SCREAMING_SNAKE_CASE   (a__							):
     lowerCAmelCase		      =	'''pt'''
     lowerCAmelCase		      =	'''tf'''
     lowerCAmelCase		      =	'''np'''
     lowerCAmelCase		      =	'''jax'''




class 			SCREAMING_SNAKE_CASE   :


     def __init__(						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			Optional[Any]								=	context_managers
          __A						:			Optional[int]								=	ExitStack()


     def __enter__(						self):

          '''simple docstring'''






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


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

          '''simple docstring'''






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






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

     def _flatten_dict(__snake_case  :			Tuple			,							__snake_case  :			List[Any]=""			,							__snake_case  :			Tuple="."      ):
          for k, v in d.items():
               __A						:			List[Any]								=	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  :			Any			,							__snake_case  :			bool = False      )					->					List[str]:
     if use_temp_dir:
          with tempfile.TemporaryDirectory() as tmp_dir:
               yield tmp_dir
     else:
          yield working_dir






def 	_lowerCAmelCase      (  __snake_case  :			Optional[Any]			,							__snake_case  :			Optional[Any]=None      )					->					int:
     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  :			List[Any]			,							__snake_case  :			str      )					->					str:
     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  :			Tuple			,							__snake_case  :			List[str]=None      )					->					Any:
     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  :			Union[str, Any]			,							__snake_case  :			List[Any]      )					->					int:
     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[Any]      )					->					Dict:
     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  :			str			,							__snake_case  :			Tuple      )					->					Union[str, Any]:
     for key, value in auto_map.items():
          if isinstance(__snake_case			,							(tuple, list)      ):
               __A						:			Tuple								=	[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						:			Dict								=	f'{repo_id}--{value}'

     return auto_map







def 	_lowerCAmelCase      (  __snake_case  :			List[str]      )					->					int:
     for base_class in inspect.getmro(__snake_case      ):
          __A						:			int								=	base_class.__module__
          __A						:			List[str]								=	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}.'      )