



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







  def __get__(      self  :Tuple   ,							_lowercase  :str   ,							_lowercase  :Union[str, Any]=None ):






     '''simple docstring'''





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


def _A       (   __magic_name__	):
   lowercase__			       =  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 _A       (   __magic_name__	):
   if is_torch_fx_proxy(__magic_name__	):
      return True
   if is_torch_available():
      import torch

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

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

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

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

   return isinstance(__magic_name__  , np.ndarray	)


def _A       (   __magic_name__	):
   return isinstance(__magic_name__  , np.ndarray	)


def _A       (   __magic_name__	):
   return _is_numpy(__magic_name__	)


def _A       (   __magic_name__	):
   import torch

   return isinstance(__magic_name__  , torch.Tensor	)


def _A       (   __magic_name__	):
   return False if not is_torch_available() else _is_torch(__magic_name__	)


def _A       (   __magic_name__	):
   import torch

   return isinstance(__magic_name__  , torch.device	)


def _A       (   __magic_name__	):
   return False if not is_torch_available() else _is_torch_device(__magic_name__	)


def _A       (   __magic_name__	):
   import torch

   if isinstance(__magic_name__  , __magic_name__	):
      if hasattr(__magic_name__  , __magic_name__	):
         lowercase__			       =  getattr(__magic_name__  , __magic_name__	)
      else:
         return False
   return isinstance(__magic_name__  , torch.dtype	)


def _A       (   __magic_name__	):
   return False if not is_torch_available() else _is_torch_dtype(__magic_name__	)


def _A       (   __magic_name__	):
   import tensorflow as tf

   return isinstance(__magic_name__  , tf.Tensor	)


def _A       (   __magic_name__	):
   return False if not is_tf_available() else _is_tensorflow(__magic_name__	)


def _A       (   __magic_name__	):
   import tensorflow as tf

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


def _A       (   __magic_name__	):
   return False if not is_tf_available() else _is_tf_symbolic_tensor(__magic_name__	)


def _A       (   __magic_name__	):
   import jax.numpy as jnp  # noqa: F811

   return isinstance(__magic_name__  , jnp.ndarray	)


def _A       (   __magic_name__	):
   return False if not is_flax_available() else _is_jax(__magic_name__	)


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


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





class  lowerCAmelCase							(       lowercase_ ):







  def   UpperCAmelCase					(      self  :Tuple ):






     '''simple docstring'''





     lowercase__			       =  fields(self )

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

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

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







  def __delitem__(      self  :Union[str, Any]   ,							*_lowercase  :str   ,							**_lowercase  :Dict ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :List[Any]   ,							*_lowercase  :Dict   ,							**_lowercase  :Dict ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :int   ,							*_lowercase  :Tuple   ,							**_lowercase  :Dict ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :Tuple   ,							*_lowercase  :Dict   ,							**_lowercase  :Tuple ):






     '''simple docstring'''





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







  def __getitem__(      self  :Any   ,							_lowercase  :List[str] ):






     '''simple docstring'''





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







  def __setattr__(      self  :Union[str, Any]   ,							_lowercase  :Optional[int]   ,							_lowercase  :Any ):






     '''simple docstring'''





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







  def __setitem__(      self  :Union[str, Any]   ,							_lowercase  :Optional[Any]   ,							_lowercase  :List[Any] ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :Optional[int] ):






     '''simple docstring'''





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





class  lowerCAmelCase							(       lowercase_							,							lowercase_ ):







  @classmethod
  def   UpperCAmelCase					(      cls  :Dict   ,							_lowercase  :List[str] ):






     '''simple docstring'''





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





class  lowerCAmelCase							(       lowercase_ ):
  __lowerCamelCase		=      'longest'
  __lowerCamelCase		=      'max_length'
  __lowerCamelCase		=      'do_not_pad'





class  lowerCAmelCase							(       lowercase_ ):
  __lowerCamelCase		=      'pt'
  __lowerCamelCase		=      'tf'
  __lowerCamelCase		=      'np'
  __lowerCamelCase		=      'jax'





class  lowerCAmelCase							:







  def __init__(      self  :str   ,							_lowercase  :List[ContextManager] ):






     '''simple docstring'''





     lowercase__			       =  context_managers
     lowercase__			       =  ExitStack()







  def __enter__(      self  :Tuple ):






     '''simple docstring'''





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







  def __exit__(      self  :List[str]   ,							*_lowercase  :Optional[Any]   ,							**_lowercase  :List[str] ):






     '''simple docstring'''





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


def _A       (   __magic_name__	):
   lowercase__			       =  infer_framework(__magic_name__	)
   if framework == "tf":
      lowercase__			       =  inspect.signature(model_class.call	)  # TensorFlow models
   elif framework == "pt":
      lowercase__			       =  inspect.signature(model_class.forward	)  # PyTorch models
   else:
      lowercase__			       =  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 _A       (   __magic_name__	):
   lowercase__			       =  model_class.__name__
   lowercase__			       =  infer_framework(__magic_name__	)
   if framework == "tf":
      lowercase__			       =  inspect.signature(model_class.call	)  # TensorFlow models
   elif framework == "pt":
      lowercase__			       =  inspect.signature(model_class.forward	)  # PyTorch models
   else:
      lowercase__			       =  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 _A       (   __magic_name__  , __magic_name__ = ""  , __magic_name__ = "."	):

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

   return dict(_flatten_dict(__magic_name__  , __magic_name__  , __magic_name__	)	)


@contextmanager
def _A       (   __magic_name__  , __magic_name__ = False	):
   if use_temp_dir:
      with tempfile.TemporaryDirectory() as tmp_dir:
         yield tmp_dir
   else:
      yield working_dir


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

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


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

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


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

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


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

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


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

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


def _A       (   __magic_name__  , __magic_name__	):
   for key, value in auto_map.items():
      if isinstance(__magic_name__  , (tuple, list)	):
         lowercase__			       =  [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:
         lowercase__			       =  f'''{repo_id}--{value}'''

   return auto_map







def _A       (   __magic_name__	):
   for base_class in inspect.getmro(__magic_name__	):
      lowercase__			       =  base_class.__module__
      lowercase__			       =  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}.'''	)













def _A       (   __magic_name__	):
   try:
      lowercase__			       =  float(__magic_name__	)
   except ValueError:
      raise ValueError("Please enter a valid number"	)
   lowercase__			       =  decimal - int(__magic_name__	)
   if fractional_part == 0:
      return int(__magic_name__	), 1
   else:
      lowercase__			       =  len(str(__magic_name__	).split("."	)[1]	)
      lowercase__			       =  int(decimal * (10**number_of_frac_digits)	)
      lowercase__			       =  10**number_of_frac_digits
      lowercase__       ,							lowercase__			       =  denominator, numerator
      while True:
         lowercase__			       =  dividend % divisor
         if remainder == 0:
            break
         lowercase__       ,							lowercase__			       =  divisor, remainder
      lowercase__       ,							lowercase__			       =  numerator / divisor, denominator / divisor
      return int(__magic_name__	), int(__magic_name__	)


if __name__ == "__main__":
  print(F"""{decimal_to_fraction(2) = }""")
  print(F"""{decimal_to_fraction(89.0) = }""")
  print(F"""{decimal_to_fraction("67") = }""")
  print(F"""{decimal_to_fraction("45.0") = }""")
  print(F"""{decimal_to_fraction(1.5) = }""")
  print(F"""{decimal_to_fraction("6.25") = }""")
  print(F"""{decimal_to_fraction("78td") = }""")






