






import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


__A      =				logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')

require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt')




def      __A					(     _lowercase					,			_lowercase					,			_lowercase = 1_60_00 ):

					'''simple docstring'''







					_A								= int(round(sample_rate * max_length ) )
					if len(_lowercase ) <= sample_length:
										return wav
					_A								= randint(0					,			len(_lowercase ) - sample_length - 1 )
					return wav[random_offset : random_offset + sample_length]





@dataclass
class 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

							A_						  =					field(default=snake_case  ,	metadata={"help": "Name of a dataset from the datasets package"}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "A file containing the training audio paths and labels."}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "A file containing the validation audio paths and labels."}					)
							A_						  =					field(
							    default="train"  ,	metadata={
							        "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
							    }  ,	)
							A_						  =					field(
							    default="validation"  ,	metadata={
							        "help": (
							            "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
							        )
							    }  ,	)
							A_						  =					field(
							    default="audio"  ,	metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}  ,	)
							A_						  =					field(
							    default="label"  ,	metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={
							        "help": (
							            "For debugging purposes or quicker training, truncate the number of training examples to this "
							            "value if set."
							        )
							    }  ,	)
							A_						  =					field(
							    default=snake_case  ,	metadata={
							        "help": (
							            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
							            "value if set."
							        )
							    }  ,	)
							A_						  =					field(
							    default=20  ,	metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."}  ,	)





@dataclass
class 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

							A_						  =					field(
							    default="facebook/wav2vec2-base"  ,	metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}  ,	)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Pretrained config name or path if not the same as model_name"}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"}					)
							A_						  =					field(
							    default="main"  ,	metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}  ,	)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Name or path of preprocessor config."}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Whether to freeze the feature encoder layers of the model."}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Whether to generate an attention mask in the feature extractor."}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={
							        "help": (
							            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
							            "with private models)."
							        )
							    }  ,	)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Whether to freeze the feature extractor layers of the model."}					)
							A_						  =					field(
							    default=snake_case  ,	metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}  ,	)

							def       __A (  self:   Optional[Any]   )    ->				List[Any]:
												if not self.freeze_feature_extractor and self.freeze_feature_encoder:
																	warnings.warn(
																	    '''The argument `--freeze_feature_extractor` is deprecated and '''
																	    '''will be removed in a future version. Use `--freeze_feature_encoder`'''
																	    '''instead. Setting `freeze_feature_encoder==True`.'''		,     __A		,     )
												if self.freeze_feature_extractor and not self.freeze_feature_encoder:
																	raise ValueError(
																	    '''The argument `--freeze_feature_extractor` is deprecated and '''
																	    '''should not be used in combination with `--freeze_feature_encoder`.'''
																	    '''Only make use of `--freeze_feature_encoder`.'''   )




def      __A					(     ):

					'''simple docstring'''







					_A								= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
					if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										_A							,_A							,_A								= parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
					else:
										_A							,_A							,_A								= parser.parse_args_into_dataclasses()

					# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
					# information sent is the one passed as arguments along with your Python/PyTorch versions.
					send_example_telemetry('''run_audio_classification'''					,			_lowercase					,			_lowercase )

					# Setup logging
					logging.basicConfig(
					    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''					,			datefmt='''%m/%d/%Y %H:%M:%S'''					,			handlers=[logging.StreamHandler(sys.stdout )]					,			)

					if training_args.should_log:
										# The default of training_args.log_level is passive, so we set log level at info here to have that default.
										transformers.utils.logging.set_verbosity_info()

					_A								= training_args.get_process_log_level()
					logger.setLevel(_lowercase )
					transformers.utils.logging.set_verbosity(_lowercase )
					transformers.utils.logging.enable_default_handler()
					transformers.utils.logging.enable_explicit_format()

					# Log on each process the small summary:
					logger.warning(
					    f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """
					    + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" )
					logger.info(f"""Training/evaluation parameters {training_args}""" )

					# Set seed before initializing model.
					set_seed(training_args.seed )

					# Detecting last checkpoint.
					_A								= None
					if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
										_A								= get_last_checkpoint(training_args.output_dir )
										if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
															raise ValueError(
															    f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
															    '''Use --overwrite_output_dir to train from scratch.''' )
										elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
															logger.info(
															    f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
															    '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' )

    # Initialize our dataset and prepare it for the audio classification task.
					_A								= DatasetDict()
					_A								= load_dataset(
					    data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.train_split_name					,			use_auth_token=True if model_args.use_auth_token else None					,			)
					_A								= load_dataset(
					    data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.eval_split_name					,			use_auth_token=True if model_args.use_auth_token else None					,			)

					if data_args.audio_column_name not in raw_datasets["train"].column_names:
										raise ValueError(
										    f"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """
										    '''Make sure to set `--audio_column_name` to the correct audio column - one of '''
										    f"""{", ".join(raw_datasets["train"].column_names )}.""" )

					if data_args.label_column_name not in raw_datasets["train"].column_names:
										raise ValueError(
										    f"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """
										    '''Make sure to set `--label_column_name` to the correct text column - one of '''
										    f"""{", ".join(raw_datasets["train"].column_names )}.""" )

					# Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
					# transformer outputs in the classifier, but it doesn't always lead to better accuracy
					_A								= AutoFeatureExtractor.from_pretrained(
					    model_args.feature_extractor_name or model_args.model_name_or_path					,			return_attention_mask=model_args.attention_mask					,			cache_dir=model_args.cache_dir					,			revision=model_args.model_revision					,			use_auth_token=True if model_args.use_auth_token else None					,			)

					# `datasets` takes care of automatically loading and resampling the audio,
					# so we just need to set the correct target sampling rate.
					_A								= raw_datasets.cast_column(
					    data_args.audio_column_name					,			datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) )

					_A								= feature_extractor.model_input_names[0]

					def train_transforms(_lowercase ):
										_A								= []
										for audio in batch[data_args.audio_column_name]:
															_A								= random_subsample(
															    audio['''array''']					,			max_length=data_args.max_length_seconds					,			sample_rate=feature_extractor.sampling_rate )
															subsampled_wavs.append(_lowercase )
										_A								= feature_extractor(_lowercase					,			sampling_rate=feature_extractor.sampling_rate )
										_A								= {model_input_name: inputs.get(_lowercase )}
										_A								= list(batch[data_args.label_column_name] )

										return output_batch

					def val_transforms(_lowercase ):
										_A								= [audio['''array'''] for audio in batch[data_args.audio_column_name]]
										_A								= feature_extractor(_lowercase					,			sampling_rate=feature_extractor.sampling_rate )
										_A								= {model_input_name: inputs.get(_lowercase )}
										_A								= list(batch[data_args.label_column_name] )

										return output_batch

					# Prepare label mappings.
					# We'll include these in the model's config to get human readable labels in the Inference API.
					_A								= raw_datasets['''train'''].features[data_args.label_column_name].names
					_A							,_A								= {}, {}
					for i, label in enumerate(_lowercase ):
										_A								= str(_lowercase )
										_A								= label

					# Load the accuracy metric from the datasets package
					_A								= evaluate.load('''accuracy''' )

					# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
					# `predictions` and `label_ids` fields) and has to return a dictionary string to float.
					def compute_metrics(_lowercase ):
										_A								= np.argmax(eval_pred.predictions					,			axis=1 )
										return metric.compute(predictions=_lowercase					,			references=eval_pred.label_ids )

					_A								= AutoConfig.from_pretrained(
					    model_args.config_name or model_args.model_name_or_path					,			num_labels=len(_lowercase )					,			labelaid=_lowercase					,			idalabel=_lowercase					,			finetuning_task='''audio-classification'''					,			cache_dir=model_args.cache_dir					,			revision=model_args.model_revision					,			use_auth_token=True if model_args.use_auth_token else None					,			)
					_A								= AutoModelForAudioClassification.from_pretrained(
					    model_args.model_name_or_path					,			from_tf=bool('''.ckpt''' in model_args.model_name_or_path )					,			config=_lowercase					,			cache_dir=model_args.cache_dir					,			revision=model_args.model_revision					,			use_auth_token=True if model_args.use_auth_token else None					,			ignore_mismatched_sizes=model_args.ignore_mismatched_sizes					,			)

					# freeze the convolutional waveform encoder
					if model_args.freeze_feature_encoder:
										model.freeze_feature_encoder()

					if training_args.do_train:
										if data_args.max_train_samples is not None:
															_A								= (
															    raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) )
															)
										# Set the training transforms
										raw_datasets["train"].set_transform(_lowercase					,			output_all_columns=_lowercase )

					if training_args.do_eval:
										if data_args.max_eval_samples is not None:
															_A								= (
															    raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) )
															)
										# Set the validation transforms
										raw_datasets["eval"].set_transform(_lowercase					,			output_all_columns=_lowercase )

					# Initialize our trainer
					_A								= Trainer(
					    model=_lowercase					,			args=_lowercase					,			train_dataset=raw_datasets['''train'''] if training_args.do_train else None					,			eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None					,			compute_metrics=_lowercase					,			tokenizer=_lowercase					,			)

					# Training
					if training_args.do_train:
										_A								= None
										if training_args.resume_from_checkpoint is not None:
															_A								= training_args.resume_from_checkpoint
										elif last_checkpoint is not None:
															_A								= last_checkpoint
										_A								= trainer.train(resume_from_checkpoint=_lowercase )
										trainer.save_model()
										trainer.log_metrics('''train'''					,			train_result.metrics )
										trainer.save_metrics('''train'''					,			train_result.metrics )
										trainer.save_state()

					# Evaluation
					if training_args.do_eval:
										_A								= trainer.evaluate()
										trainer.log_metrics('''eval'''					,			_lowercase )
										trainer.save_metrics('''eval'''					,			_lowercase )

					# Write model card and (optionally) push to hub
					_A								= {
					    '''finetuned_from''': model_args.model_name_or_path,
					    '''tasks''': '''audio-classification''',
					    '''dataset''': data_args.dataset_name,
					    '''tags''': ['''audio-classification'''],
					}
					if training_args.push_to_hub:
										trainer.push_to_hub(**_lowercase )
					else:
										trainer.create_model_card(**_lowercase )


if __name__ == "__main__":
				main()











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


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




def      __A					(     _lowercase ):

					'''simple docstring'''







					if isinstance(_lowercase					,			_lowercase ):
										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					(     _lowercase ):

					'''simple docstring'''







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




def      __A					(     *,
    _lowercase = None					,			_lowercase = None					,			_lowercase = dataclasses.MISSING					,			_lowercase = dataclasses.MISSING					,			_lowercase = None					,			**_lowercase					,			):

					'''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
										_A								= {}
					if aliases is not None:
										_A								= aliases
					if help is not None:
										_A								= help

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





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							A_						  =					42

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

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

												_A								= kwargs.pop('''aliases'''		,     []   )
												if isinstance(__A		,     __A   ):
																	_A								= [aliases]

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

																	_A								= make_choice_type_function(kwargs['''choices''']   )

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

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

												# 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]):
																	_A								= False
																	parser.add_argument(f"""--no_{field.name}"""		,     action='''store_false'''		,     dest=field.name		,     **__A   )

							def       __A (  self:   Dict		,     __A:   DataClassType   )    ->				List[Any]:
												if hasattr(__A		,     '''_argument_group_name'''   ):
																	_A								= self.add_argument_group(dtype._argument_group_name   )
												else:
																	_A								= self

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

							def       __A (  self:   int		,     __A:   Any=None		,     __A:   int=False		,     __A:   Any=True		,     __A:   Optional[Any]=None		,     __A:   Any=None		,     )    ->				Tuple[DataClass, ...]:

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

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

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

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

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

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



							def       __A (  self:   List[Any]		,     __A:   str		,     __A:   bool = False   )    ->				Tuple[DataClass, ...]:
												_A								= self.parse_dict(yaml.safe_load(Path(__A   ).read_text()   )		,     allow_extra_keys=__A   )
												return tuple(__A   )



