






import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path

import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized

from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available

from ..wavaveca.test_feature_extraction_wavaveca import floats_list


if is_pyctcdecode_available():
				from huggingface_hub import snapshot_download
				from pyctcdecode import BeamSearchDecoderCTC

				from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
				from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput

if is_torch_available():
				from transformers import WavaVecaForCTC





@require_pyctcdecode
class 						SCREAMING_SNAKE_CASE				( unittest.TestCase					):





							"""simple docstring"""

							def       __A (  self:   List[Any]   )    ->				int:
												_A								= '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split()
												_A								= dict(zip(_a		,     range(len(_a   )   )   )   )

												_A								= {
												    '''unk_token''': '''<unk>''',
												    '''bos_token''': '''<s>''',
												    '''eos_token''': '''</s>''',
												}
												_A								= {
												    '''feature_size''': 1,
												    '''padding_value''': 0.0,
												    '''sampling_rate''': 1_60_00,
												    '''return_attention_mask''': False,
												    '''do_normalize''': True,
												}

												_A								= tempfile.mkdtemp()
												_A								= os.path.join(self.tmpdirname		,     VOCAB_FILES_NAMES['''vocab_file''']   )
												_A								= os.path.join(self.tmpdirname		,     _a   )
												with open(self.vocab_file		,     '''w'''		,     encoding='''utf-8'''   ) as fp:
																	fp.write(json.dumps(_a   ) + '''\n'''   )

												with open(self.feature_extraction_file		,     '''w'''		,     encoding='''utf-8'''   ) as fp:
																	fp.write(json.dumps(_a   ) + '''\n'''   )

												# load decoder from hub
												_A								= '''hf-internal-testing/ngram-beam-search-decoder'''

							def       __A (  self:   Optional[Any]		,     **__A:   str   )    ->				Tuple:
												_A								= self.add_kwargs_tokens_map.copy()
												kwargs.update(_a   )
												return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname		,     **_a   )

							def       __A (  self:   Union[str, Any]		,     **__A:   List[str]   )    ->				Dict:
												return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname		,     **_a   )

							def       __A (  self:   Any		,     **__A:   List[str]   )    ->				Union[str, Any]:
												return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name		,     **_a   )

							def       __A (  self:   Dict   )    ->				str:
												shutil.rmtree(self.tmpdirname   )

							def       __A (  self:   int   )    ->				int:
												_A								= self.get_tokenizer()
												_A								= self.get_feature_extractor()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												processor.save_pretrained(self.tmpdirname   )
												_A								= WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname   )

												# tokenizer
												self.assertEqual(processor.tokenizer.get_vocab()		,     tokenizer.get_vocab()   )
												self.assertIsInstance(processor.tokenizer		,     _a   )

												# feature extractor
												self.assertEqual(processor.feature_extractor.to_json_string()		,     feature_extractor.to_json_string()   )
												self.assertIsInstance(processor.feature_extractor		,     _a   )

												# decoder
												self.assertEqual(processor.decoder._alphabet.labels		,     decoder._alphabet.labels   )
												self.assertEqual(
												    processor.decoder.model_container[decoder._model_key]._unigram_set		,     decoder.model_container[decoder._model_key]._unigram_set		,     )
												self.assertIsInstance(processor.decoder		,     _a   )

							def       __A (  self:   List[Any]   )    ->				List[Any]:
												_A								= WavaVecaProcessorWithLM(
												    tokenizer=self.get_tokenizer()		,     feature_extractor=self.get_feature_extractor()		,     decoder=self.get_decoder()   )
												processor.save_pretrained(self.tmpdirname   )

												# make sure that error is thrown when decoder alphabet doesn't match
												_A								= WavaVecaProcessorWithLM.from_pretrained(
												    self.tmpdirname		,     alpha=5.0		,     beta=3.0		,     score_boundary=-7.0		,     unk_score_offset=3   )

												# decoder
												self.assertEqual(processor.language_model.alpha		,     5.0   )
												self.assertEqual(processor.language_model.beta		,     3.0   )
												self.assertEqual(processor.language_model.score_boundary		,     -7.0   )
												self.assertEqual(processor.language_model.unk_score_offset		,     3   )

							def       __A (  self:   Dict   )    ->				Dict:
												_A								= self.get_tokenizer()
												# add token to trigger raise
												tokenizer.add_tokens(['''xx''']   )
												with self.assertRaisesRegex(_a		,     '''include'''   ):
																	WavaVecaProcessorWithLM(
																	    tokenizer=_a		,     feature_extractor=self.get_feature_extractor()		,     decoder=self.get_decoder()   )

							def       __A (  self:   int   )    ->				str:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												_A								= floats_list((3, 10_00)   )

												_A								= feature_extractor(_a		,     return_tensors='''np'''   )
												_A								= processor(_a		,     return_tensors='''np'''   )

												for key in input_feat_extract.keys():
																	self.assertAlmostEqual(input_feat_extract[key].sum()		,     input_processor[key].sum()		,     delta=1e-2   )

							def       __A (  self:   Dict   )    ->				Dict:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												_A								= '''This is a test string'''

												_A								= processor(text=_a   )

												_A								= tokenizer(_a   )

												for key in encoded_tok.keys():
																	self.assertListEqual(encoded_tok[key]		,     encoded_processor[key]   )

							def       __A (  self:   Dict		,     __A:   Optional[Any]=(2, 10, 16)		,     __A:   str=77   )    ->				str:
												np.random.seed(_a   )
												return np.random.rand(*_a   )

							def       __A (  self:   List[str]   )    ->				List[Any]:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												_A								= self._get_dummy_logits(shape=(10, 16)		,     seed=13   )

												_A								= processor.decode(_a   )

												_A								= decoder.decode_beams(_a   )[0]

												self.assertEqual(decoded_decoder[0]		,     decoded_processor.text   )
												self.assertEqual('''</s> <s> </s>'''		,     decoded_processor.text   )
												self.assertEqual(decoded_decoder[-2]		,     decoded_processor.logit_score   )
												self.assertEqual(decoded_decoder[-1]		,     decoded_processor.lm_score   )

							@parameterized.expand([[None], ['''fork'''], ['''spawn''']]   )
							def       __A (  self:   Dict		,     __A:   List[str]   )    ->				Union[str, Any]:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												_A								= self._get_dummy_logits()

												# note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
												#       otherwise, the LM won't be available to the pool's sub-processes.
												# manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
												if pool_context is None:
																	_A								= processor.batch_decode(_a   )
												else:
																	with get_context(_a   ).Pool() as pool:
																						_A								= processor.batch_decode(_a		,     _a   )

												_A								= list(_a   )

												with get_context('''fork'''   ).Pool() as p:
																	_A								= decoder.decode_beams_batch(_a		,     _a   )

												_A							,_A							,_A								= [], [], []
												for beams in decoded_beams:
																	texts_decoder.append(beams[0][0]   )
																	logit_scores_decoder.append(beams[0][-2]   )
																	lm_scores_decoder.append(beams[0][-1]   )

												self.assertListEqual(_a		,     decoded_processor.text   )
												self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>''']		,     decoded_processor.text   )
												self.assertListEqual(_a		,     decoded_processor.logit_score   )
												self.assertListEqual(_a		,     decoded_processor.lm_score   )

							def       __A (  self:   int   )    ->				int:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												_A								= self._get_dummy_logits()

												_A								= 15
												_A								= -20.0
												_A								= -4.0

												_A								= processor.batch_decode(
												    _a		,     beam_width=_a		,     beam_prune_logp=_a		,     token_min_logp=_a		,     )
												_A								= decoded_processor_out.text

												_A								= list(_a   )

												with get_context('''fork'''   ).Pool() as pool:
																	_A								= decoder.decode_beams_batch(
																	    _a		,     _a		,     beam_width=_a		,     beam_prune_logp=_a		,     token_min_logp=_a		,     )

												_A								= [d[0][0] for d in decoded_decoder_out]
												_A								= [d[0][2] for d in decoded_decoder_out]
												_A								= [d[0][3] for d in decoded_decoder_out]

												self.assertListEqual(_a		,     _a   )
												self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>''']		,     _a   )

												self.assertTrue(np.array_equal(_a		,     decoded_processor_out.logit_score   )   )
												self.assertTrue(np.allclose([-20.054, -18.447]		,     _a		,     atol=1e-3   )   )

												self.assertTrue(np.array_equal(_a		,     decoded_processor_out.lm_score   )   )
												self.assertTrue(np.allclose([-15.554, -13.9_474]		,     _a		,     atol=1e-3   )   )

							def       __A (  self:   Dict   )    ->				Dict:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												_A								= self._get_dummy_logits()

												_A								= 2.0
												_A								= 5.0
												_A								= -20.0
												_A								= True

												_A								= processor.batch_decode(
												    _a		,     alpha=_a		,     beta=_a		,     unk_score_offset=_a		,     lm_score_boundary=_a		,     )
												_A								= decoded_processor_out.text

												_A								= list(_a   )
												decoder.reset_params(
												    alpha=_a		,     beta=_a		,     unk_score_offset=_a		,     lm_score_boundary=_a		,     )

												with get_context('''fork'''   ).Pool() as pool:
																	_A								= decoder.decode_beams_batch(
																	    _a		,     _a		,     )

												_A								= [d[0][0] for d in decoded_decoder_out]

												self.assertListEqual(_a		,     _a   )
												self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>''']		,     _a   )
												_A								= processor.decoder.model_container[processor.decoder._model_key]
												self.assertEqual(lm_model.alpha		,     2.0   )
												self.assertEqual(lm_model.beta		,     5.0   )
												self.assertEqual(lm_model.unk_score_offset		,     -20.0   )
												self.assertEqual(lm_model.score_boundary		,     _a   )

							def       __A (  self:   Any   )    ->				List[str]:
												_A								= WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm'''   )

												_A								= processor.decoder.model_container[processor.decoder._model_key]
												_A								= Path(language_model._kenlm_model.path.decode('''utf-8'''   )   ).parent.parent.absolute()

												_A								= os.listdir(_a   )
												_A								= ['''alphabet.json''', '''language_model''']

												downloaded_decoder_files.sort()
												expected_decoder_files.sort()

												# test that only decoder relevant files from
												# https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
												# are downloaded and none of the rest (e.g. README.md, ...)
												self.assertListEqual(_a		,     _a   )

							def       __A (  self:   List[Any]   )    ->				Tuple:
												_A								= snapshot_download('''hf-internal-testing/processor_with_lm'''   )

												_A								= WavaVecaProcessorWithLM.from_pretrained(_a   )

												_A								= processor.decoder.model_container[processor.decoder._model_key]
												_A								= Path(language_model._kenlm_model.path.decode('''utf-8'''   )   ).parent.parent.absolute()

												_A								= os.listdir(_a   )
												_A								= os.listdir(_a   )

												local_decoder_files.sort()
												expected_decoder_files.sort()

												# test that both decoder form hub and local files in cache are the same
												self.assertListEqual(_a		,     _a   )

							def       __A (  self:   int   )    ->				Dict:
												_A								= WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm'''   )
												_A								= AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm'''   )

												_A								= floats_list((3, 10_00)   )

												_A								= processor_wavaveca(_a		,     return_tensors='''np'''   )
												_A								= processor_auto(_a		,     return_tensors='''np'''   )

												for key in input_wavaveca.keys():
																	self.assertAlmostEqual(input_wavaveca[key].sum()		,     input_auto[key].sum()		,     delta=1e-2   )

												_A								= self._get_dummy_logits()

												_A								= processor_wavaveca.batch_decode(_a   )
												_A								= processor_auto.batch_decode(_a   )

												self.assertListEqual(decoded_wavaveca.text		,     decoded_auto.text   )

							def       __A (  self:   List[Any]   )    ->				List[str]:
												_A								= self.get_feature_extractor()
												_A								= self.get_tokenizer()
												_A								= self.get_decoder()

												_A								= WavaVecaProcessorWithLM(tokenizer=_a		,     feature_extractor=_a		,     decoder=_a   )

												self.assertListEqual(
												    processor.model_input_names		,     feature_extractor.model_input_names		,     msg='''`processor` and `feature_extractor` model input names do not match'''		,     )

							@staticmethod
							def       __A (  __A:   List[Any]		,     __A:   Any   )    ->				List[Any]:
												_A								= [d[key] for d in offsets]
												return retrieved_list

							def       __A (  self:   List[Any]   )    ->				Tuple:
												_A								= WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm'''   )
												_A								= self._get_dummy_logits()[0]

												_A								= processor.decode(_a		,     output_word_offsets=_a   )
												# check Wav2Vec2CTCTokenizerOutput keys for word
												self.assertEqual(len(outputs.keys()   )		,     4   )
												self.assertTrue('''text''' in outputs   )
												self.assertTrue('''word_offsets''' in outputs   )
												self.assertTrue(isinstance(_a		,     _a   )   )

												self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets''']		,     '''word'''   )   )		,     outputs.text   )
												self.assertListEqual(self.get_from_offsets(outputs['''word_offsets''']		,     '''word'''   )		,     ['''<s>''', '''<s>''', '''</s>''']   )
												self.assertListEqual(self.get_from_offsets(outputs['''word_offsets''']		,     '''start_offset'''   )		,     [0, 2, 4]   )
												self.assertListEqual(self.get_from_offsets(outputs['''word_offsets''']		,     '''end_offset'''   )		,     [1, 3, 5]   )

							def       __A (  self:   int   )    ->				Any:
												_A								= WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm'''   )
												_A								= self._get_dummy_logits()

												_A								= processor.batch_decode(_a		,     output_word_offsets=_a   )

												# check Wav2Vec2CTCTokenizerOutput keys for word
												self.assertEqual(len(outputs.keys()   )		,     4   )
												self.assertTrue('''text''' in outputs   )
												self.assertTrue('''word_offsets''' in outputs   )
												self.assertTrue(isinstance(_a		,     _a   )   )

												self.assertListEqual(
												    [''' '''.join(self.get_from_offsets(_a		,     '''word'''   )   ) for o in outputs['''word_offsets''']]		,     outputs.text   )
												self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0]		,     '''word'''   )		,     ['''<s>''', '''<s>''', '''</s>''']   )
												self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0]		,     '''start_offset'''   )		,     [0, 2, 4]   )
												self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0]		,     '''end_offset'''   )		,     [1, 3, 5]   )



							@slow
							@require_torch
							@require_torchaudio
							def       __A (  self:   List[str]   )    ->				Tuple:
												import torch

												_A								= load_dataset('''common_voice'''		,     '''en'''		,     split='''train'''		,     streaming=_a   )
												_A								= ds.cast_column('''audio'''		,     datasets.Audio(sampling_rate=1_60_00   )   )
												_A								= iter(_a   )
												_A								= next(_a   )

												_A								= AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm'''   )
												_A								= WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm'''   )

												# compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
												_A								= processor(sample['''audio''']['''array''']		,     return_tensors='''pt'''   ).input_values

												with torch.no_grad():
																	_A								= model(_a   ).logits.cpu().numpy()

												_A								= processor.decode(logits[0]		,     output_word_offsets=_a   )

												_A								= model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
												_A								= [
												    {
												        '''start_time''': d['''start_offset'''] * time_offset,
												        '''end_time''': d['''end_offset'''] * time_offset,
												        '''word''': d['''word'''],
												    }
												    for d in output['''word_offsets''']
												]

												_A								= '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL'''

												# output words
												self.assertEqual(''' '''.join(self.get_from_offsets(_a		,     '''word'''   )   )		,     _a   )
												self.assertEqual(''' '''.join(self.get_from_offsets(_a		,     '''word'''   )   )		,     output.text   )

												# output times
												_A								= torch.tensor(self.get_from_offsets(_a		,     '''start_time'''   )   )
												_A								= torch.tensor(self.get_from_offsets(_a		,     '''end_time'''   )   )

												# fmt: off
												_A								= torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599]   )
												_A								= torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94]   )
												# fmt: on

												self.assertTrue(torch.allclose(_a		,     _a		,     atol=0.01   )   )
												self.assertTrue(torch.allclose(_a		,     _a		,     atol=0.01   )   )











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   )



