



"""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


lowercase  							=					NewType('''DataClass''', Any)
lowercase  							=					NewType('''DataClassType''', Any)




def 	UpperCAmelCase     (		A	:						List[str]       ):

		'''simple docstring'''


		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 	UpperCAmelCase     (		A	:						list       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		{str(A       ): choice for choice in choices}
		return lambda A       : str_to_choice.get(A     ,				A       )




def 	UpperCAmelCase     (		*,
    A	:						Union[str, List[str]] = None     ,				A	:						str = None     ,				A	:						Any = dataclasses.MISSING     ,				A	:						Callable[[], Any] = dataclasses.MISSING     ,				A	:						dict = None     ,				**A	:						List[str]     ,				):

		'''simple docstring'''


		if metadata is None:
				# Important, don't use as default param in function signature because dict is mutable and shared across function calls
				_UpperCAmelCase							 =		{}
		if aliases is not None:
				_UpperCAmelCase							 =		aliases
		if help is not None:
				_UpperCAmelCase							 =		help

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






class 			lowercase__			(      A    ):
							'''simple docstring'''







							_UpperCAmelCase      				=					42






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






							@staticmethod
							def        lowerCamelCase_   (  snake_case	,       snake_case						)			->							Union[str, Any]:
									_UpperCAmelCase							 =		f'--{field.name}'
									_UpperCAmelCase							 =		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	,       snake_case						):
											raise RuntimeError(
											    'Unresolved type detected, which should have been done with the help of '
											    '`typing.get_type_hints` method by default'						)

									_UpperCAmelCase							 =		kwargs.pop('aliases'	,       []						)
									if isinstance(snake_case	,       snake_case						):
											_UpperCAmelCase							 =		[aliases]

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

											_UpperCAmelCase							 =		make_choice_type_function(kwargs['choices']						)

											if field.default is not dataclasses.MISSING:
													_UpperCAmelCase							 =		field.default
											else:
													_UpperCAmelCase							 =		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
											_UpperCAmelCase							 =		copy(snake_case						)

											# Hack because type=bool in argparse does not behave as we want.
											_UpperCAmelCase							 =		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.
													_UpperCAmelCase							 =		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
													_UpperCAmelCase							 =		default
													# This tells argparse we accept 0 or 1 value after --field_name
													_UpperCAmelCase							 =		'?'
													# This is the value that will get picked if we do --field_name (without value)
													_UpperCAmelCase							 =		True
									elif isclass(snake_case						) and issubclass(snake_case	,       snake_case						):
											_UpperCAmelCase							 =		field.type.__args__[0]
											_UpperCAmelCase							 =		'+'
											if field.default_factory is not dataclasses.MISSING:
													_UpperCAmelCase							 =		field.default_factory()
											elif field.default is dataclasses.MISSING:
													_UpperCAmelCase							 =		True
									else:
											_UpperCAmelCase							 =		field.type
											if field.default is not dataclasses.MISSING:
													_UpperCAmelCase							 =		field.default
											elif field.default_factory is not dataclasses.MISSING:
													_UpperCAmelCase							 =		field.default_factory()
											else:
													_UpperCAmelCase							 =		True
									parser.add_argument(snake_case	,       *snake_case	,       **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]):
											_UpperCAmelCase							 =		False
											parser.add_argument(f'--no_{field.name}'	,       action='store_false'	,       dest=field.name	,       **snake_case						)






							def        lowerCamelCase_   (  self	,       snake_case						)			->							Tuple:
									if hasattr(snake_case	,       '_argument_group_name'						):
											_UpperCAmelCase							 =		self.add_argument_group(dtype._argument_group_name						)
									else:
											_UpperCAmelCase							 =		self

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






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

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

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

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

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

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






							def        lowerCamelCase_   (  self	,       snake_case	,       snake_case = False						)			->							Tuple[DataClass, ...]:
									with open(Path(snake_case						)	,       encoding='utf-8'						) as open_json_file:
											_UpperCAmelCase							 =		json.loads(open_json_file.read()						)
									_UpperCAmelCase							 =		self.parse_dict(snake_case	,       allow_extra_keys=snake_case						)
									return tuple(snake_case						)






							def        lowerCamelCase_   (  self	,       snake_case	,       snake_case = False						)			->							Tuple[DataClass, ...]:
									_UpperCAmelCase							 =		self.parse_dict(yaml.safe_load(Path(snake_case						).read_text()						)	,       allow_extra_keys=snake_case						)
									return tuple(snake_case						)







"""simple docstring"""





from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


lowercase  							=					logging.get_logger(__name__)


lowercase  							=					TypeVar('''DatasetType''', Dataset, IterableDataset)




def 	UpperCAmelCase     (		A	:						List[DatasetType]     ,				A	:						Optional[List[float]] = None     ,				A	:						Optional[int] = None     ,				A	:						Optional[DatasetInfo] = None     ,				A	:						Optional[NamedSplit] = None     ,				A	:						Literal["first_exhausted", "all_exhausted"] = "first_exhausted"     ,				):

		'''simple docstring'''


		from .arrow_dataset import Dataset
		from .iterable_dataset import IterableDataset

		if not datasets:
				raise ValueError('Unable to interleave an empty list of datasets.'       )
		for i, dataset in enumerate(A       ):
				if not isinstance(A     ,				(Dataset, IterableDataset)       ):
						if isinstance(A     ,				(DatasetDict, IterableDatasetDict)       ):
								if not dataset:
										raise ValueError(
										    f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
										    'is an empty dataset dictionary.'       )
								raise ValueError(
								    f'Dataset at position {i} has at least one split: {list(A       )}\n'
								    f'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(A       )       )}\']'       )
						raise ValueError(
						    f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(A       ).__name__}.'       )
				if i == 0:
						_UpperCAmelCase ,					_UpperCAmelCase							 =		(
						    (Dataset, IterableDataset) if isinstance(A     ,				A       ) else (IterableDataset, Dataset)
						)
				elif not isinstance(A     ,				A       ):
						raise ValueError(
						    f'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.'       )
		if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
				raise ValueError(f'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.'       )
		if dataset_type is Dataset:
				return _interleave_map_style_datasets(
				    A     ,				A     ,				A     ,				info=A     ,				split=A     ,				stopping_strategy=A       )
		else:
				return _interleave_iterable_datasets(
				    A     ,				A     ,				A     ,				info=A     ,				split=A     ,				stopping_strategy=A       )






def 	UpperCAmelCase     (		A	:						List[DatasetType]     ,				A	:						Optional[DatasetInfo] = None     ,				A	:						Optional[NamedSplit] = None     ,				A	:						int = 0     ,				):

		'''simple docstring'''


		if not dsets:
				raise ValueError('Unable to concatenate an empty list of datasets.'       )
		for i, dataset in enumerate(A       ):
				if not isinstance(A     ,				(Dataset, IterableDataset)       ):
						if isinstance(A     ,				(DatasetDict, IterableDatasetDict)       ):
								if not dataset:
										raise ValueError(
										    f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
										    'is an empty dataset dictionary.'       )
								raise ValueError(
								    f'Dataset at position {i} has at least one split: {list(A       )}\n'
								    f'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(A       )       )}\']'       )
						raise ValueError(
						    f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(A       ).__name__}.'       )
				if i == 0:
						_UpperCAmelCase ,					_UpperCAmelCase							 =		(
						    (Dataset, IterableDataset) if isinstance(A     ,				A       ) else (IterableDataset, Dataset)
						)
				elif not isinstance(A     ,				A       ):
						raise ValueError(
						    f'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.'       )
		if dataset_type is Dataset:
				return _concatenate_map_style_datasets(A     ,				info=A     ,				split=A     ,				axis=A       )
		else:
				return _concatenate_iterable_datasets(A     ,				info=A     ,				split=A     ,				axis=A       )


