





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       : Union[str, Any]			     =       NewType("""DataClass""", Any)
_UpperCAmelCase       : Any			     =       NewType("""DataClassType""", Any)


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  List[Any]:
  if isinstance(SCREAMING_SNAKE_CASE_		,			SCREAMING_SNAKE_CASE_				):
    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  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Callable[[str], Any]:
  lowerCamelCase__					:   Tuple      				=	{str(SCREAMING_SNAKE_CASE_				): choice for choice in choices}
  return lambda _UpperCAmelCase				: str_to_choice.get(SCREAMING_SNAKE_CASE_		,			SCREAMING_SNAKE_CASE_				)


def  SCREAMING_SNAKE_CASE   ( *,
    _UpperCAmelCase = None		,			_UpperCAmelCase = None		,			_UpperCAmelCase = dataclasses.MISSING		,			_UpperCAmelCase = dataclasses.MISSING		,			_UpperCAmelCase = None		,			**_UpperCAmelCase		,			)    ->  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__					:   Optional[Any]      				=	{}
  if aliases is not None:
    lowerCamelCase__					:   Dict      				=	aliases
  if help is not None:
    lowerCamelCase__					:   int      				=	help

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


class      lowerCAmelCase							(      __UpperCamelCase    ):
 UpperCAmelCase__									=	42
 def __init__(   self						:   Optional[Any]    ,  UpperCAmelCase						:   Union[DataClassType, Iterable[DataClassType]]    ,  **UpperCAmelCase						:   Optional[Any]			)    ->			Tuple:







   if "formatter_class" not in kwargs:
     lowerCamelCase__					:   Any      				=	ArgumentDefaultsHelpFormatter
   super().__init__(**UpperCAmelCase			)
   if dataclasses.is_dataclass(UpperCAmelCase			):
     lowerCamelCase__					:   Tuple      				=	[dataclass_types]
   lowerCamelCase__					:   Optional[int]      				=	list(UpperCAmelCase			)
   for dtype in self.dataclass_types:
     self._add_dataclass_arguments(UpperCAmelCase			)
 @staticmethod
 def   A_			(   UpperCAmelCase						:   ArgumentParser    ,  UpperCAmelCase						:   dataclasses.Field			)    ->			Optional[int]:
   lowerCamelCase__					:   Tuple      				=	F"""--{field.name}"""
   lowerCamelCase__					:   Union[str, Any]      				=	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    ,  UpperCAmelCase			):
     raise RuntimeError(
         'Unresolved type detected, which should have been done with the help of '
         '`typing.get_type_hints` method by default'			)

   lowerCamelCase__					:   Dict      				=	kwargs.pop('aliases'    ,  []			)
   if isinstance(UpperCAmelCase    ,  UpperCAmelCase			):
     lowerCamelCase__					:   Union[str, Any]      				=	[aliases]

   lowerCamelCase__					:   Union[str, Any]      				=	getattr(field.type    ,  '__origin__'    ,  field.type			)
   if origin_type is Union or (hasattr(UpperCAmelCase    ,  'UnionType'			) and isinstance(UpperCAmelCase    ,  types.UnionType			)):
     if str not in field.type.__args__ and (
         len(field.type.__args__			) != 2 or type(UpperCAmelCase			) 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(UpperCAmelCase			) not in field.type.__args__:
       # filter `str` in Union
       lowerCamelCase__					:   Dict      				=	field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
       lowerCamelCase__					:   Optional[Any]      				=	getattr(field.type    ,  '__origin__'    ,  field.type			)
     elif bool not in field.type.__args__:
       # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
       lowerCamelCase__					:   Optional[int]      				=	(
           field.type.__args__[0] if isinstance(UpperCAmelCase    ,  field.type.__args__[1]			) else field.type.__args__[1]
       )
       lowerCamelCase__					:   Optional[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__					:   Any      				=	{}
   if origin_type is Literal or (isinstance(field.type    ,  UpperCAmelCase			) and issubclass(field.type    ,  UpperCAmelCase			)):
     if origin_type is Literal:
       lowerCamelCase__					:   Optional[Any]      				=	field.type.__args__
     else:
       lowerCamelCase__					:   List[str]      				=	[x.value for x in field.type]

     lowerCamelCase__					:   Optional[int]      				=	make_choice_type_function(kwargs['choices']			)

     if field.default is not dataclasses.MISSING:
       lowerCamelCase__					:   Union[str, Any]      				=	field.default
     else:
       lowerCamelCase__					:   Union[str, Any]      				=	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__					:   List[str]      				=	copy(UpperCAmelCase			)

     # Hack because type=bool in argparse does not behave as we want.
     lowerCamelCase__					:   Any      				=	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__					:   Tuple      				=	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[Any]      				=	default
       # This tells argparse we accept 0 or 1 value after --field_name
       lowerCamelCase__					:   List[str]      				=	'?'
       # This is the value that will get picked if we do --field_name (without value)
       lowerCamelCase__					:   List[Any]      				=	True
   elif isclass(UpperCAmelCase			) and issubclass(UpperCAmelCase    ,  UpperCAmelCase			):
     lowerCamelCase__					:   str      				=	field.type.__args__[0]
     lowerCamelCase__					:   List[Any]      				=	'+'
     if field.default_factory is not dataclasses.MISSING:
       lowerCamelCase__					:   Optional[int]      				=	field.default_factory()
     elif field.default is dataclasses.MISSING:
       lowerCamelCase__					:   Any      				=	True
   else:
     lowerCamelCase__					:   List[Any]      				=	field.type
     if field.default is not dataclasses.MISSING:
       lowerCamelCase__					:   Tuple      				=	field.default
     elif field.default_factory is not dataclasses.MISSING:
       lowerCamelCase__					:   Dict      				=	field.default_factory()
     else:
       lowerCamelCase__					:   Dict      				=	True
   parser.add_argument(UpperCAmelCase    ,  *UpperCAmelCase    ,  **UpperCAmelCase			)

   # 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__					:   str      				=	False
     parser.add_argument(F"""--no_{field.name}"""    ,  action='store_false'    ,  dest=field.name    ,  **UpperCAmelCase			)
 def   A_			(   self						:   Union[str, Any]    ,  UpperCAmelCase						:   DataClassType			)    ->			int:







   if hasattr(UpperCAmelCase    ,  '_argument_group_name'			):
     lowerCamelCase__					:   Union[str, Any]      				=	self.add_argument_group(dtype._argument_group_name			)
   else:
     lowerCamelCase__					:   Optional[Any]      				=	self

   try:
     lowerCamelCase__					:   Dict[str, type]      				=	get_type_hints(UpperCAmelCase			)
   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, 10) and "unsupported operand type(s) for |" in str(UpperCAmelCase			):
       lowerCamelCase__					:   List[str]      				=	'.'.join(map(UpperCAmelCase    ,  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(UpperCAmelCase			):
     if not field.init:
       continue
     lowerCamelCase__					:   Dict      				=	type_hints[field.name]
     self._parse_dataclass_field(UpperCAmelCase    ,  UpperCAmelCase			)
 def   A_			(   self						:   List[Any]    ,  UpperCAmelCase						:   Tuple=None    ,  UpperCAmelCase						:   Dict=False    ,  UpperCAmelCase						:   Optional[Any]=True    ,  UpperCAmelCase						:   List[Any]=None    ,  UpperCAmelCase						:   int=None    ,  )    ->			Tuple:







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

     if args_filename:
       args_files.append(Path(UpperCAmelCase			)			)
     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__					:   Tuple      				=	ArgumentParser()
       args_file_parser.add_argument(UpperCAmelCase    ,  type=UpperCAmelCase    ,  action='append'			)

       # Use only remaining args for further parsing (remove the args_file_flag)
       lowerCamelCase__					:   Dict      				=	args_file_parser.parse_known_args(args=UpperCAmelCase			)
       lowerCamelCase__					:   Optional[int]      				=	vars(UpperCAmelCase			).get(args_file_flag.lstrip('-'			)    ,  UpperCAmelCase			)

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

     lowerCamelCase__					:   Tuple      				=	[]
     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__					:   int      				=	file_args + args if args is not None else file_args + sys.argv[1:]
   lowerCamelCase__					:   Optional[Any]      				=	self.parse_known_args(args=UpperCAmelCase			)
   lowerCamelCase__					:   Union[str, Any]      				=	[]
   for dtype in self.dataclass_types:
     lowerCamelCase__					:   Union[str, Any]      				=	{f.name for f in dataclasses.fields(UpperCAmelCase			) if f.init}
     lowerCamelCase__					:   Optional[int]      				=	{k: v for k, v in vars(UpperCAmelCase			).items() if k in keys}
     for k in keys:
       delattr(UpperCAmelCase    ,  UpperCAmelCase			)
     lowerCamelCase__					:   Optional[int]      				=	dtype(**UpperCAmelCase			)
     outputs.append(UpperCAmelCase			)
   if len(namespace.__dict__			) > 0:
     # additional namespace.
     outputs.append(UpperCAmelCase			)
   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   A_			(   self						:   List[Any]    ,  UpperCAmelCase						:   Dict[str, Any]    ,  UpperCAmelCase						:   bool = False			)    ->			Union[str, Any]:
   lowerCamelCase__					:   int      				=	set(args.keys()			)
   lowerCamelCase__					:   List[Any]      				=	[]
   for dtype in self.dataclass_types:
     lowerCamelCase__					:   List[str]      				=	{f.name for f in dataclasses.fields(UpperCAmelCase			) if f.init}
     lowerCamelCase__					:   str      				=	{k: v for k, v in args.items() if k in keys}
     unused_keys.difference_update(inputs.keys()			)
     lowerCamelCase__					:   str      				=	dtype(**UpperCAmelCase			)
     outputs.append(UpperCAmelCase			)
   if not allow_extra_keys and unused_keys:
     raise ValueError(F"""Some keys are not used by the HfArgumentParser: {sorted(UpperCAmelCase			)}"""			)
   return tuple(UpperCAmelCase			)
 def   A_			(   self						:   Tuple    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   bool = False			)    ->			int:







   with open(Path(UpperCAmelCase			)    ,  encoding='utf-8'			) as open_json_file:
     lowerCamelCase__					:   int      				=	json.loads(open_json_file.read()			)
   lowerCamelCase__					:   List[Any]      				=	self.parse_dict(UpperCAmelCase    ,  allow_extra_keys=UpperCAmelCase			)
   return tuple(UpperCAmelCase			)







 def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   bool = False			)    ->			Optional[Any]:
   lowerCamelCase__					:   str      				=	self.parse_dict(yaml.safe_load(Path(UpperCAmelCase			).read_text()			)    ,  allow_extra_keys=UpperCAmelCase			)
   return tuple(UpperCAmelCase			)












import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


_UpperCAmelCase       : Union[str, Any]			     =       logging.get_logger(__name__)

class      lowerCAmelCase							:
 UpperCAmelCase__									=	None


@experimental
def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase				)    ->  Any:
    if ParallelBackendConfig.backend_name is None:
        return _map_with_multiprocessing_pool(
            _UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase				)

    return _map_with_joblib(_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase				)


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase				)    ->  Any:
    lowerCamelCase__					:   int      				=	num_proc if num_proc <= len(_UpperCAmelCase				) else len(_UpperCAmelCase				)
    lowerCamelCase__					:   Optional[int]      				=	[]  # We organize the splits ourselve (contiguous splits)
    for index in range(_UpperCAmelCase				):
        lowerCamelCase__					:   str      				=	len(_UpperCAmelCase				) // num_proc
        lowerCamelCase__					:   List[str]      				=	len(_UpperCAmelCase				) % num_proc
        lowerCamelCase__					:   Tuple      				=	div * index + min(_UpperCAmelCase		,			_UpperCAmelCase				)
        lowerCamelCase__					:   int      				=	start + div + (1 if index < mod else 0)
        split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)				)

    if len(_UpperCAmelCase				) != sum(len(i[1]				) for i in split_kwds				):
        raise ValueError(
            F"""Error dividing inputs iterable among processes. """
            F"""Total number of objects {len(_UpperCAmelCase				)}, """
            F"""length: {sum(len(i[1]				) for i in split_kwds				)}"""				)

    logger.info(
        F"""Spawning {num_proc} processes for {len(_UpperCAmelCase				)} objects in slices of {[len(i[1]				) for i in split_kwds]}"""				)
    lowerCamelCase__				,							lowerCamelCase__					:   List[str]      				=	None, None
    if not disable_tqdm:
        lowerCamelCase__				,							lowerCamelCase__					:   Union[str, Any]      				=	(RLock(),), tqdm.set_lock
    with Pool(_UpperCAmelCase		,			initargs=_UpperCAmelCase		,			initializer=_UpperCAmelCase				) as pool:
        lowerCamelCase__					:   Any      				=	pool.map(_UpperCAmelCase		,			_UpperCAmelCase				)
    logger.info(F"""Finished {num_proc} processes"""				)
    lowerCamelCase__					:   Union[str, Any]      				=	[obj for proc_res in mapped for obj in proc_res]
    logger.info(F"""Unpacked {len(_UpperCAmelCase				)} objects"""				)

    return mapped


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase				)    ->  int:
    # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib,
    # and it requires monkey-patching joblib internal classes which is subject to change
    import joblib

    with joblib.parallel_backend(ParallelBackendConfig.backend_name		,			n_jobs=_UpperCAmelCase				):
        return joblib.Parallel()(
            joblib.delayed(_UpperCAmelCase				)((function, obj, types, None, True, None)				) for obj in iterable				)


@experimental
@contextlib.contextmanager
def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Tuple:
    lowerCamelCase__					:   List[str]      				=	backend_name

    if backend_name == "spark":
        from joblibspark import register_spark

        register_spark()

        # TODO: call create_cache_and_write_probe if "download" in steps
        # TODO: raise NotImplementedError when Dataset.map etc is called

    try:
        yield
    finally:
        lowerCamelCase__					:   str      				=	None





