
'''simple docstring'''





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    					=   NewType("DataClass", Any)
UpperCAmelCase    					=   NewType("DataClassType", Any)

def      A (       A_							:					Any       ):
						if isinstance(A_    ,							A_       ):
												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      A (       A_							:					list       ):
						snake_case       :     Optional[Any] =    {str(A_       ): choice for choice in choices}
						return lambda A_       : str_to_choice.get(A_    ,							A_       )

def      A (       *,
    A_							:					Union[str, List[str]] = None    ,							A_							:					str = None    ,							A_							:					Any = dataclasses.MISSING    ,							A_							:					Callable[[], Any] = dataclasses.MISSING    ,							A_							:					dict = None    ,							**A_							:					str    ,							):
						if metadata is None:
												# Important, don't use as default param in function signature because dict is mutable and shared across function calls
												snake_case       :     Dict =    {}
						if aliases is not None:
												snake_case       :     Any =    aliases
						if help is not None:
												snake_case       :     Any =    help

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





class 						a   (				__magic_name__    ):
				_snake_case		    = 42




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




				@staticmethod
				def 	__snake_case							(							SCREAMING_SNAKE_CASE_	:				ArgumentParser,    SCREAMING_SNAKE_CASE_	:				dataclasses.Field      ):
										snake_case       :     int =    F"""--{field.name}"""
										snake_case       :     List[str] =    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,    SCREAMING_SNAKE_CASE_      ):
																raise RuntimeError(
																    '''Unresolved type detected, which should have been done with the help of '''
																    '''`typing.get_type_hints` method by default'''      )

										snake_case       :     Dict =    kwargs.pop('''aliases''',    []      )
										if isinstance(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_      ):
																snake_case       :     str =    [aliases]

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

																snake_case       :     Tuple =    make_choice_type_function(kwargs['''choices''']      )

																if field.default is not dataclasses.MISSING:
																						snake_case       :     Optional[Any] =    field.default
																else:
																						snake_case       :     Dict =    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
																snake_case       :     Tuple =    copy(SCREAMING_SNAKE_CASE_      )

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

										# 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]):
																snake_case       :     Optional[Any] =    False
																parser.add_argument(F"""--no_{field.name}""",    action='''store_false''',    dest=field.name,    **SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Optional[int],    SCREAMING_SNAKE_CASE_	:				DataClassType      ):
										if hasattr(SCREAMING_SNAKE_CASE_,    '''_argument_group_name'''      ):
																snake_case       :     Optional[Any] =    self.add_argument_group(dtype._argument_group_name      )
										else:
																snake_case       :     Union[str, Any] =    self

										try:
																snake_case       :     Dict[str, type] =    get_type_hints(SCREAMING_SNAKE_CASE_      )
										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(SCREAMING_SNAKE_CASE_      ):
																						snake_case       :     Dict =    '''.'''.join(map(SCREAMING_SNAKE_CASE_,    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(SCREAMING_SNAKE_CASE_      ):
																if not field.init:
																						continue
																snake_case       :     int =    type_hints[field.name]
																self._parse_dataclass_field(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				int,    SCREAMING_SNAKE_CASE_	:				Dict=None,    SCREAMING_SNAKE_CASE_	:				int=False,    SCREAMING_SNAKE_CASE_	:				Optional[int]=True,    SCREAMING_SNAKE_CASE_	:				Any=None,    SCREAMING_SNAKE_CASE_	:				List[str]=None,    ):

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

																if args_filename:
																						args_files.append(Path(SCREAMING_SNAKE_CASE_      )      )
																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
																						snake_case       :     List[Any] =    ArgumentParser()
																						args_file_parser.add_argument(SCREAMING_SNAKE_CASE_,    type=SCREAMING_SNAKE_CASE_,    action='''append'''      )

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

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

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




				def 	__snake_case							(							self	:				Union[str, Any],    SCREAMING_SNAKE_CASE_	:				str,    SCREAMING_SNAKE_CASE_	:				bool = False      ):
										with open(Path(SCREAMING_SNAKE_CASE_      ),    encoding='''utf-8'''      ) as open_json_file:
																snake_case       :     Tuple =    json.loads(open_json_file.read()      )
										snake_case       :     Dict =    self.parse_dict(SCREAMING_SNAKE_CASE_,    allow_extra_keys=SCREAMING_SNAKE_CASE_      )
										return tuple(SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				str,    SCREAMING_SNAKE_CASE_	:				bool = False      ):
										snake_case       :     List[str] =    self.parse_dict(yaml.safe_load(Path(SCREAMING_SNAKE_CASE_      ).read_text()      ),    allow_extra_keys=SCREAMING_SNAKE_CASE_      )
										return tuple(SCREAMING_SNAKE_CASE_      )



'''simple docstring'''





import os
from typing import Optional

import fsspec
from fsspec.archive import AbstractArchiveFileSystem
from fsspec.utils import DEFAULT_BLOCK_SIZE

class 						a   (				__magic_name__    ):
				_snake_case		    = ''''''
				_snake_case		    = (
				    None  # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz
				)
				_snake_case		    = None  # compression type in fsspec. ex: "gzip"
				_snake_case		    = None  # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz




				def __init__(							self	:				Optional[int],    SCREAMING_SNAKE_CASE_	:				str = "",    SCREAMING_SNAKE_CASE_	:				Optional[str] = None,    SCREAMING_SNAKE_CASE_	:				Optional[dict] = None,    **SCREAMING_SNAKE_CASE_	:				Union[str, Any]      ):
										super().__init__(self,    **SCREAMING_SNAKE_CASE_      )
										# always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode
										snake_case       :     List[Any] =    fsspec.open(
										    SCREAMING_SNAKE_CASE_,    mode='''rb''',    protocol=SCREAMING_SNAKE_CASE_,    compression=self.compression,    client_kwargs={
										        '''requote_redirect_url''': False,  # see https://github.com/huggingface/datasets/pull/5459
										        '''trust_env''': True,  # Enable reading proxy env variables.
										        **(target_options or {}).pop('''client_kwargs''',    {}      ),  # To avoid issues if it was already passed.
										    },    **(target_options or {}),    )
										snake_case       :     Tuple =    os.path.basename(self.file.path.split('''::'''      )[0]      )
										snake_case       :     Optional[Any] =    (
										    self.compressed_name[: self.compressed_name.rindex('''.'''      )]
										    if '''.''' in self.compressed_name
										    else self.compressed_name
										)
										snake_case       :     str =    None




				@classmethod
				def 	__snake_case							(							cls	:				Any,    SCREAMING_SNAKE_CASE_	:				int      ):
										# compressed file paths are always relative to the archive root
										return super()._strip_protocol(SCREAMING_SNAKE_CASE_      ).lstrip('''/'''      )




				def 	__snake_case							(							self	:				Optional[int]      ):
										if self.dir_cache is None:
																snake_case       :     Optional[int] =    {**self.file.fs.info(self.file.path      ), '''name''': self.uncompressed_name}
																snake_case       :     Tuple =    {f['''name''']: f}




				def 	__snake_case							(							self	:				List[Any],    SCREAMING_SNAKE_CASE_	:				str      ):
										return self.file.open().read()




				def 	__snake_case							(							self	:				List[Any],    SCREAMING_SNAKE_CASE_	:				str,    SCREAMING_SNAKE_CASE_	:				str = "rb",    SCREAMING_SNAKE_CASE_	:				int=None,    SCREAMING_SNAKE_CASE_	:				Optional[int]=True,    SCREAMING_SNAKE_CASE_	:				List[Any]=None,    **SCREAMING_SNAKE_CASE_	:				Any,    ):
										snake_case       :     int =    self._strip_protocol(SCREAMING_SNAKE_CASE_      )
										if mode != "rb":
																raise ValueError(F"""Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'"""      )
										return self.file.open()




class 						a   (				__magic_name__    ):
				_snake_case		    = '''bz2'''
				_snake_case		    = '''bz2'''
				_snake_case		    = '''.bz2'''




class 						a   (				__magic_name__    ):
				_snake_case		    = '''gzip'''
				_snake_case		    = '''gzip'''
				_snake_case		    = '''.gz'''




class 						a   (				__magic_name__    ):
				_snake_case		    = '''lz4'''
				_snake_case		    = '''lz4'''
				_snake_case		    = '''.lz4'''




class 						a   (				__magic_name__    ):
				_snake_case		    = '''xz'''
				_snake_case		    = '''xz'''
				_snake_case		    = '''.xz'''




class 						a   (				__magic_name__    ):
				_snake_case		    = '''zstd'''
				_snake_case		    = '''zstd'''
				_snake_case		    = '''.zst'''




				def __init__(							self	:				int,    SCREAMING_SNAKE_CASE_	:				str,    SCREAMING_SNAKE_CASE_	:				str = "rb",    SCREAMING_SNAKE_CASE_	:				Optional[str] = None,    SCREAMING_SNAKE_CASE_	:				Optional[dict] = None,    SCREAMING_SNAKE_CASE_	:				int = DEFAULT_BLOCK_SIZE,    **SCREAMING_SNAKE_CASE_	:				Optional[Any],    ):
										super().__init__(
										    fo=SCREAMING_SNAKE_CASE_,    mode=SCREAMING_SNAKE_CASE_,    target_protocol=SCREAMING_SNAKE_CASE_,    target_options=SCREAMING_SNAKE_CASE_,    block_size=SCREAMING_SNAKE_CASE_,    **SCREAMING_SNAKE_CASE_,    )
										# We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2:
										#
										# File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open
										#     out.close = close
										# AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only
										#
										# see https://github.com/intake/filesystem_spec/issues/725
										snake_case       :     List[Any] =    self.file.__enter__

										class 						a   :




														def __init__(							self	:				int,    SCREAMING_SNAKE_CASE_	:				Dict      ):
																				snake_case       :     Dict =    file_




														def __enter__(							self	:				Optional[Any]      ):
																				self._file.__enter__()
																				return self




														def __exit__(							self	:				Union[str, Any],    *SCREAMING_SNAKE_CASE_	:				Dict,    **SCREAMING_SNAKE_CASE_	:				Tuple      ):
																				self._file.__exit__(*SCREAMING_SNAKE_CASE_,    **SCREAMING_SNAKE_CASE_      )




														def __iter__(							self	:				Union[str, Any]      ):
																				return iter(self._file      )




														def 	__snake_case							(							self	:				Union[str, Any]      ):
																				return next(self._file      )




														def __getattr__(							self	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				Optional[int]      ):
																				return getattr(self._file,    SCREAMING_SNAKE_CASE_      )

										def fixed_enter(*SCREAMING_SNAKE_CASE_	:				Optional[Any],    **SCREAMING_SNAKE_CASE_	:				List[Any]      ):
																return WrappedFile(_enter(*SCREAMING_SNAKE_CASE_,    **SCREAMING_SNAKE_CASE_      )      )

										snake_case       :     Union[str, Any] =    fixed_enter

