
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        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  def __get__( self			: Union[str, Any]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Any=None    )			->	str:







    """simple docstring"""






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







def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       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__    (       A_					):






  '''simple docstring'''





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

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

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

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

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

  return isinstance(A_,     np.ndarray					)

def a__    (       A_					):






  '''simple docstring'''





  return isinstance(A_,     np.ndarray					)

def a__    (       A_					):






  '''simple docstring'''





  return _is_numpy(A_					)

def a__    (       A_					):






  '''simple docstring'''





  import torch

  return isinstance(A_,     torch.Tensor					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import torch

  return isinstance(A_,     torch.device					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import torch

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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import tensorflow as tf

  return isinstance(A_,     tf.Tensor					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import tensorflow as tf

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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  import jax.numpy as jnp  # noqa: F811

  return isinstance(A_,     jnp.ndarray					)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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




class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  def 							_lowercase							( self			: List[Any]    )			->	str:







    """simple docstring"""






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

    __magic_name__				     =       getattr(self			,							class_fields[0].name    )
    __magic_name__				     =       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__    ):
        __magic_name__				     =       first_field.items()
        __magic_name__				     =       True
      else:
        try:
          __magic_name__				     =       iter(UpperCamelCase__    )
          __magic_name__				     =       True
        except TypeError:
          __magic_name__				     =       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
              __magic_name__				     =       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:
            __magic_name__				     =       element[1]
      elif first_field is not None:
        __magic_name__				     =       first_field
    else:
      for field in class_fields:
        __magic_name__				     =       getattr(self			,							field.name    )
        if v is not None:
          __magic_name__				     =       v
  def __delitem__( self			: Any			,							*UpperCamelCase__			: List[Any]			,							**UpperCamelCase__			: Any    )			->	Optional[Any]:







    """simple docstring"""






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







    """simple docstring"""






    raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''    )
  def 							_lowercase							( self			: Any			,							*UpperCamelCase__			: List[str]			,							**UpperCamelCase__			: Optional[Any]    )			->	Optional[int]:







    """simple docstring"""






    raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''    )
  def 							_lowercase							( self			: List[str]			,							*UpperCamelCase__			: Dict			,							**UpperCamelCase__			: Optional[int]    )			->	Tuple:







    """simple docstring"""






    raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''    )
  def __getitem__( self			: Any			,							UpperCamelCase__			: Optional[Any]    )			->	Any:







    """simple docstring"""






    if isinstance(UpperCamelCase__			,							UpperCamelCase__    ):
      __magic_name__				     =       dict(self.items()    )
      return inner_dict[k]
    else:
      return self.to_tuple()[k]
  def __setattr__( self			: Optional[int]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: str    )			->	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__(UpperCamelCase__			,							UpperCamelCase__    )
    super().__setattr__(UpperCamelCase__			,							UpperCamelCase__    )
  def __setitem__( self			: List[Any]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: int    )			->	int:







    """simple docstring"""






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





  def 							_lowercase							( self			: str    )			->	Tuple[Any]:







    """simple docstring"""






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







class        UpperCAmelCase_			( _A  ,       _A     ):


  '''simple docstring'''







  @classmethod
  def 							_lowercase							( cls			: Union[str, Any]			,							UpperCamelCase__			: Optional[int]    )			->	Optional[int]:







    """simple docstring"""






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







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		"""longest"""
  a__           =		"""max_length"""
  a__           =		"""do_not_pad"""







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		"""pt"""
  a__           =		"""tf"""
  a__           =		"""np"""
  a__           =		"""jax"""







class        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Dict			,							UpperCamelCase__			: List[ContextManager]    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       context_managers
    __magic_name__				     =       ExitStack()
  def __enter__( self			: Optional[int]    )			->	int:







    """simple docstring"""






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





  def __exit__( self			: Dict			,							*UpperCamelCase__			: str			,							**UpperCamelCase__			: Optional[int]    )			->	str:







    """simple docstring"""






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







def a__    (       A_					):






  '''simple docstring'''





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






  '''simple docstring'''





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






  '''simple docstring'''





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

  return dict(_flatten_dict(A_,     A_,     A_					)					)

@contextmanager
def a__    (       A_,     A_ = False					):






  '''simple docstring'''





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

def a__    (       A_,     A_=None					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_=None					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_					):






  '''simple docstring'''





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

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

def a__    (       A_					):






  '''simple docstring'''





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

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

def a__    (       A_,     A_					):






  '''simple docstring'''





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

  return auto_map





def a__    (       A_					):






  '''simple docstring'''





  for base_class in inspect.getmro(A_					):
    __magic_name__				     =       base_class.__module__
    __magic_name__				     =       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 dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


_UpperCAmelCase	:     Optional[Any]   =NewType("""DataClass""", Any)
_UpperCAmelCase	:     Dict   =NewType("""DataClassType""", Any)



def 	lowerCAmelCase       (						lowerCAmelCase_       )->       Tuple:
				if isinstance(lowerCAmelCase_       ,      lowerCAmelCase_       ):
								return v
				if v.lower() in ("yes", "true", "t", "y", "1"):
								return True
				elif v.lower() in ("no", "false", "f", "n", "0"):
								return False
				else:
								raise ArgumentTypeError(
								    f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."""       )



def 	lowerCAmelCase       (						lowerCAmelCase_       )->       Callable[[str], Any]:
				lowerCAmelCase_       :					str			 = {str(lowerCAmelCase_       ): choice for choice in choices}
				return lambda lowerCAmelCase_       : str_to_choice.get(lowerCAmelCase_       ,      lowerCAmelCase_       )



def 	lowerCAmelCase       (						*,
    lowerCAmelCase_ = None       ,      lowerCAmelCase_ = None       ,      lowerCAmelCase_ = dataclasses.MISSING       ,      lowerCAmelCase_ = dataclasses.MISSING       ,      lowerCAmelCase_ = None       ,      **lowerCAmelCase_       ,      )->       dataclasses.Field:
				if metadata is None:
								# Important, don't use as default param in function signature because dict is mutable and shared across function calls
								lowerCAmelCase_       :					Dict			 = {}
				if aliases is not None:
								lowerCAmelCase_       :					str			 = aliases
				if help is not None:
								lowerCAmelCase_       :					Tuple			 = help

				return dataclasses.field(metadata=lowerCAmelCase_       ,      default=lowerCAmelCase_       ,      default_factory=lowerCAmelCase_       ,      **lowerCAmelCase_       )







class  snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__					:     Iterable[DataClassType]




						def __init__( self      ,  __lowercase      ,  **__lowercase							)    ->			List[str]:
										# To make the default appear when using --help
										if "formatter_class" not in kwargs:
														lowerCAmelCase_       :					Optional[int]			 = ArgumentDefaultsHelpFormatter
										super().__init__(**__lowercase							)
										if dataclasses.is_dataclass(__lowercase							):
														lowerCAmelCase_       :					Union[str, Any]			 = [dataclass_types]
										lowerCAmelCase_       :					List[Any]			 = list(__lowercase							)
										for dtype in self.dataclass_types:
														self._add_dataclass_arguments(__lowercase							)




						@staticmethod
						def   lowercase_       ( __lowercase      ,  __lowercase							)    ->			Union[str, Any]:
										lowerCAmelCase_       :					Optional[Any]			 = f"""--{field.name}"""
										lowerCAmelCase_       :					Tuple			 = field.metadata.copy()
										# field.metadata is not used at all by Data Classes,
										# it is provided as a third-party extension mechanism.
										if isinstance(field.type      ,  __lowercase							):
														raise RuntimeError(
														    '''Unresolved type detected, which should have been done with the help of '''
														    '''`typing.get_type_hints` method by default'''							)

										lowerCAmelCase_       :					List[str]			 = kwargs.pop('''aliases'''      ,  []							)
										if isinstance(__lowercase      ,  __lowercase							):
														lowerCAmelCase_       :					Optional[Any]			 = [aliases]

										lowerCAmelCase_       :					Any			 = getattr(field.type      ,  '''__origin__'''      ,  field.type							)
										if origin_type is Union or (hasattr(__lowercase      ,  '''UnionType'''							) and isinstance(__lowercase      ,  types.UnionType							)):
														if str not in field.type.__args__ and (
														    len(field.type.__args__							) != 2 or type(__lowercase							) not in field.type.__args__
														):
																		raise ValueError(
																		    '''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
																		    ''' the argument parser only supports one type per argument.'''
																		    f""" Problem encountered in field '{field.name}'."""							)
														if type(__lowercase							) not in field.type.__args__:
																		# filter `str` in Union
																		lowerCAmelCase_       :					List[Any]			 = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
																		lowerCAmelCase_       :					Dict			 = getattr(field.type      ,  '''__origin__'''      ,  field.type							)
														elif bool not in field.type.__args__:
																		# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
																		lowerCAmelCase_       :					str			 = (
																		    field.type.__args__[0] if isinstance(__lowercase      ,  field.type.__args__[1]							) else field.type.__args__[1]
																		)
																		lowerCAmelCase_       :					List[Any]			 = getattr(field.type      ,  '''__origin__'''      ,  field.type							)

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
										lowerCAmelCase_       :					Dict			 = {}
										if origin_type is Literal or (isinstance(field.type      ,  __lowercase							) and issubclass(field.type      ,  __lowercase							)):
														if origin_type is Literal:
																		lowerCAmelCase_       :					Optional[Any]			 = field.type.__args__
														else:
																		lowerCAmelCase_       :					int			 = [x.value for x in field.type]

														lowerCAmelCase_       :					str			 = make_choice_type_function(kwargs['''choices''']							)

														if field.default is not dataclasses.MISSING:
																		lowerCAmelCase_       :					str			 = field.default
														else:
																		lowerCAmelCase_       :					Tuple			 = True
										elif field.type is bool or field.type == Optional[bool]:
														# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
														# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
														lowerCAmelCase_       :					Tuple			 = copy(__lowercase							)

														# Hack because type=bool in argparse does not behave as we want.
														lowerCAmelCase_       :					Dict			 = string_to_bool
														if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
																		# Default value is False if we have no default when of type bool.
																		lowerCAmelCase_       :					Union[str, Any]			 = False if field.default is dataclasses.MISSING else field.default
																		# This is the value that will get picked if we don't include --field_name in any way
																		lowerCAmelCase_       :					List[str]			 = default
																		# This tells argparse we accept 0 or 1 value after --field_name
																		lowerCAmelCase_       :					int			 = '''?'''
																		# This is the value that will get picked if we do --field_name (without value)
																		lowerCAmelCase_       :					List[Any]			 = True
										elif isclass(__lowercase							) and issubclass(__lowercase      ,  __lowercase							):
														lowerCAmelCase_       :					Union[str, Any]			 = field.type.__args__[0]
														lowerCAmelCase_       :					Dict			 = '''+'''
														if field.default_factory is not dataclasses.MISSING:
																		lowerCAmelCase_       :					Any			 = field.default_factory()
														elif field.default is dataclasses.MISSING:
																		lowerCAmelCase_       :					Optional[int]			 = True
										else:
														lowerCAmelCase_       :					List[Any]			 = field.type
														if field.default is not dataclasses.MISSING:
																		lowerCAmelCase_       :					Dict			 = field.default
														elif field.default_factory is not dataclasses.MISSING:
																		lowerCAmelCase_       :					List[Any]			 = field.default_factory()
														else:
																		lowerCAmelCase_       :					int			 = True
										parser.add_argument(__lowercase      ,  *__lowercase      ,  **__lowercase							)

										# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
										# Order is important for arguments with the same destination!
										# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
										# here and we do not need those changes/additional keys.
										if field.default is True and (field.type is bool or field.type == Optional[bool]):
														lowerCAmelCase_       :					Any			 = False
														parser.add_argument(f"""--no_{field.name}"""      ,  action='''store_false'''      ,  dest=field.name      ,  **__lowercase							)




						def   lowercase_       ( self      ,  __lowercase							)    ->			List[Any]:
										if hasattr(__lowercase      ,  '''_argument_group_name'''							):
														lowerCAmelCase_       :					str			 = self.add_argument_group(dtype._argument_group_name							)
										else:
														lowerCAmelCase_       :					Dict			 = self

										try:
														lowerCAmelCase_       :					Dict[str, type]			 = get_type_hints(__lowercase							)
										except NameError:
														raise RuntimeError(
														    f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
														    '''removing line of `from __future__ import annotations` which opts in Postponed '''
														    '''Evaluation of Annotations (PEP 563)'''							)
										except TypeError as ex:
														# Remove this block when we drop Python 3.9 support
														if sys.version_info[:2] < (3, 1_0) and "unsupported operand type(s) for |" in str(__lowercase							):
																		lowerCAmelCase_       :					Any			 = '''.'''.join(map(__lowercase      ,  sys.version_info[:3]							)							)
																		raise RuntimeError(
																		    f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
																		    '''line of `from __future__ import annotations` which opts in union types as '''
																		    '''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
																		    '''support Python versions that lower than 3.10, you need to use '''
																		    '''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
																		    '''`X | None`.'''							) from ex
														raise

										for field in dataclasses.fields(__lowercase							):
														if not field.init:
																		continue
														lowerCAmelCase_       :					Optional[int]			 = type_hints[field.name]
														self._parse_dataclass_field(__lowercase      ,  __lowercase							)




						def   lowercase_       ( self      ,  __lowercase=None      ,  __lowercase=False      ,  __lowercase=True      ,  __lowercase=None      ,  __lowercase=None      ,  )    ->			Tuple[DataClass, ...]:

										if args_file_flag or args_filename or (look_for_args_file and len(sys.argv							)):
														lowerCAmelCase_       :					str			 = []

														if args_filename:
																		args_files.append(Path(__lowercase							)							)
														elif look_for_args_file and len(sys.argv							):
																		args_files.append(Path(sys.argv[0]							).with_suffix('''.args'''							)							)

														# args files specified via command line flag should overwrite default args files so we add them last
														if args_file_flag:
																		# Create special parser just to extract the args_file_flag values
																		lowerCAmelCase_       :					str			 = ArgumentParser()
																		args_file_parser.add_argument(__lowercase      ,  type=__lowercase      ,  action='''append'''							)

																		# Use only remaining args for further parsing (remove the args_file_flag)
																		lowerCAmelCase_ ,     lowerCAmelCase_       :					Tuple			 = args_file_parser.parse_known_args(args=__lowercase							)
																		lowerCAmelCase_       :					int			 = vars(__lowercase							).get(args_file_flag.lstrip('''-'''							)      ,  __lowercase							)

																		if cmd_args_file_paths:
																						args_files.extend([Path(__lowercase							) for p in cmd_args_file_paths]							)

														lowerCAmelCase_       :					Dict			 = []
														for args_file in args_files:
																		if args_file.exists():
																						file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
														lowerCAmelCase_       :					Any			 = file_args + args if args is not None else file_args + sys.argv[1:]
										lowerCAmelCase_ ,     lowerCAmelCase_       :					Dict			 = self.parse_known_args(args=__lowercase							)
										lowerCAmelCase_       :					Any			 = []
										for dtype in self.dataclass_types:
														lowerCAmelCase_       :					str			 = {f.name for f in dataclasses.fields(__lowercase							) if f.init}
														lowerCAmelCase_       :					str			 = {k: v for k, v in vars(__lowercase							).items() if k in keys}
														for k in keys:
																		delattr(__lowercase      ,  __lowercase							)
														lowerCAmelCase_       :					Optional[int]			 = dtype(**__lowercase							)
														outputs.append(__lowercase							)
										if len(namespace.__dict__							) > 0:
														# additional namespace.
														outputs.append(__lowercase							)
										if return_remaining_strings:
														return (*outputs, remaining_args)
										else:
														if remaining_args:
																		raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}"""							)

														return (*outputs,)




						def   lowercase_       ( self      ,  __lowercase      ,  __lowercase = False							)    ->			Tuple[DataClass, ...]:
										lowerCAmelCase_       :					int			 = set(args.keys()							)
										lowerCAmelCase_       :					str			 = []
										for dtype in self.dataclass_types:
														lowerCAmelCase_       :					int			 = {f.name for f in dataclasses.fields(__lowercase							) if f.init}
														lowerCAmelCase_       :					List[str]			 = {k: v for k, v in args.items() if k in keys}
														unused_keys.difference_update(inputs.keys()							)
														lowerCAmelCase_       :					List[str]			 = dtype(**__lowercase							)
														outputs.append(__lowercase							)
										if not allow_extra_keys and unused_keys:
														raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__lowercase							)}"""							)
										return tuple(__lowercase							)




						def   lowercase_       ( self      ,  __lowercase      ,  __lowercase = False							)    ->			Tuple[DataClass, ...]:
										with open(Path(__lowercase							)      ,  encoding='''utf-8'''							) as open_json_file:
														lowerCAmelCase_       :					Dict			 = json.loads(open_json_file.read()							)
										lowerCAmelCase_       :					str			 = self.parse_dict(__lowercase      ,  allow_extra_keys=__lowercase							)
										return tuple(__lowercase							)




						def   lowercase_       ( self      ,  __lowercase      ,  __lowercase = False							)    ->			Tuple[DataClass, ...]:
										lowerCAmelCase_       :					Optional[Any]			 = self.parse_dict(yaml.safe_load(Path(__lowercase							).read_text()							)      ,  allow_extra_keys=__lowercase							)
										return tuple(__lowercase							)