
import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_snake_case      :							List[Any]     	=    logging.getLogger(__name__)


_snake_case      :							Any     	=    list(MODEL_WITH_LM_HEAD_MAPPING.keys())
_snake_case      :							Optional[int]     	=    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)





@dataclass
class   UpperCamelCase_      :







						'''simple docstring'''



						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={
						        '''help''': (
						            '''The model checkpoint for weights initialization. Leave None if you want to train a model from'''
						            ''' scratch.'''
						        )
						    }		,    )
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__a		)}		,    )
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}		)
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}		)
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}		,    )





@dataclass
class   UpperCamelCase_      :







						'''simple docstring'''



						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''The input training data file (a text file).'''}		)
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={
						        '''help''': (
						            '''The input training data files (multiple files in glob format). '''
						            '''Very often splitting large files to smaller files can prevent tokenizer going out of memory'''
						        )
						    }		,    )
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}		,    )
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''}		,    )
						UpperCamelCase      :  Optional[str]				   =					field(
						    default=__a		,    metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''}		,    )
						UpperCamelCase      :  bool				   =					field(
						    default=__a		,    metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''}		,    )

						UpperCamelCase      :  bool				   =					field(
						    default=__a		,    metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''}		)
						UpperCamelCase      :  bool				   =					field(default=__a		,    metadata={'''help''': '''Whether ot not to use whole word mask.'''}		)
						UpperCamelCase      :  float				   =					field(
						    default=0.15		,    metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''}		)
						UpperCamelCase      :  float				   =					field(
						    default=1 / 6		,    metadata={
						        '''help''': (
						            '''Ratio of length of a span of masked tokens to surrounding context length for permutation language'''
						            ''' modeling.'''
						        )
						    }		,    )
						UpperCamelCase      :  int				   =					field(
						    default=5		,    metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''}		)

						UpperCamelCase      :  int				   =					field(
						    default=-1		,    metadata={
						        '''help''': (
						            '''Optional input sequence length after tokenization.'''
						            '''The training dataset will be truncated in block of this size for training.'''
						            '''Default to the model max input length for single sentence inputs (take into account special tokens).'''
						        )
						    }		,    )
						UpperCamelCase      :  bool				   =					field(
						    default=__a		,    metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}		)




def  __snake_case							(	__magic_name__		,    __magic_name__		,    __magic_name__ = False		,    __magic_name__ = None		,    ):







				'''simple docstring'''


				def _dataset(__magic_name__		,    __magic_name__=None						):
								if args.line_by_line:
												if ref_path is not None:
																if not args.whole_word_mask or not args.mlm:
																				raise ValueError("You need to set world whole masking and mlm to True for Chinese Whole Word Mask"						)
																return LineByLineWithRefDataset(
																    tokenizer=__magic_name__		,    file_path=__magic_name__		,    block_size=args.block_size		,    ref_path=__magic_name__		,    )

												return LineByLineTextDataset(tokenizer=__magic_name__		,    file_path=__magic_name__		,    block_size=args.block_size						)
								else:
												return TextDataset(
												    tokenizer=__magic_name__		,    file_path=__magic_name__		,    block_size=args.block_size		,    overwrite_cache=args.overwrite_cache		,    cache_dir=__magic_name__		,    )

				if evaluate:
								return _dataset(args.eval_data_file		,    args.eval_ref_file						)
				elif args.train_data_files:
								return ConcatDataset([_dataset(__magic_name__						) for f in glob(args.train_data_files						)]						)
				else:
								return _dataset(args.train_data_file		,    args.train_ref_file						)

def  __snake_case							(	):







				'''simple docstring'''


				lowercase         =      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
				lowercase     ,	lowercase     ,	lowercase         =      parser.parse_args_into_dataclasses()

				if data_args.eval_data_file is None and training_args.do_eval:
								raise ValueError(
								    "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file "
								    "or remove the --do_eval argument."						)
				if (
				    os.path.exists(training_args.output_dir						)
				    and os.listdir(training_args.output_dir						)
				    and training_args.do_train
				    and not training_args.overwrite_output_dir
				):
								raise ValueError(
								    F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
								    " --overwrite_output_dir to overcome."						)

				# Setup logging
				logging.basicConfig(
				    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"		,    datefmt="%m/%d/%Y %H:%M:%S"		,    level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN		,    )
				logger.warning(
				    "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"		,    training_args.local_rank		,    training_args.device		,    training_args.n_gpu		,    bool(training_args.local_rank != -1						)		,    training_args.fpaa		,    )
				# Set the verbosity to info of the Transformers logger (on main process only):
				if is_main_process(training_args.local_rank						):
								transformers.utils.logging.set_verbosity_info()
								transformers.utils.logging.enable_default_handler()
								transformers.utils.logging.enable_explicit_format()
				logger.info("Training/evaluation parameters %s"		,    __magic_name__						)

				# Set seed
				set_seed(training_args.seed						)

				# Load pretrained model and tokenizer
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.

				if model_args.config_name:
								lowercase         =      AutoConfig.from_pretrained(model_args.config_name		,    cache_dir=model_args.cache_dir						)
				elif model_args.model_name_or_path:
								lowercase         =      AutoConfig.from_pretrained(model_args.model_name_or_path		,    cache_dir=model_args.cache_dir						)
				else:
								lowercase         =      CONFIG_MAPPING[model_args.model_type]()
								logger.warning("You are instantiating a new config instance from scratch."						)

				if model_args.tokenizer_name:
								lowercase         =      AutoTokenizer.from_pretrained(model_args.tokenizer_name		,    cache_dir=model_args.cache_dir						)
				elif model_args.model_name_or_path:
								lowercase         =      AutoTokenizer.from_pretrained(model_args.model_name_or_path		,    cache_dir=model_args.cache_dir						)
				else:
								raise ValueError(
								    "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another"
								    " script, save it,and load it from here, using --tokenizer_name"						)

				if model_args.model_name_or_path:
								lowercase         =      AutoModelWithLMHead.from_pretrained(
								    model_args.model_name_or_path		,    from_tf=bool(".ckpt" in model_args.model_name_or_path						)		,    config=__magic_name__		,    cache_dir=model_args.cache_dir		,    )
				else:
								logger.info("Training new model from scratch"						)
								lowercase         =      AutoModelWithLMHead.from_config(__magic_name__						)

				model.resize_token_embeddings(len(__magic_name__						)						)

				if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
								raise ValueError(
								    "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the"
								    "--mlm flag (masked language modeling)."						)

				if data_args.block_size <= 0:
								lowercase         =      tokenizer.max_len
								# Our input block size will be the max possible for the model
				else:
								lowercase         =      min(data_args.block_size		,    tokenizer.max_len						)

				# Get datasets

				lowercase         =      (
				    get_dataset(__magic_name__		,    tokenizer=__magic_name__		,    cache_dir=model_args.cache_dir						) if training_args.do_train else None
				)
				lowercase         =      (
				    get_dataset(__magic_name__		,    tokenizer=__magic_name__		,    evaluate=__magic_name__		,    cache_dir=model_args.cache_dir						)
				    if training_args.do_eval
				    else None
				)
				if config.model_type == "xlnet":
								lowercase         =      DataCollatorForPermutationLanguageModeling(
								    tokenizer=__magic_name__		,    plm_probability=data_args.plm_probability		,    max_span_length=data_args.max_span_length		,    )
				else:
								if data_args.mlm and data_args.whole_word_mask:
												lowercase         =      DataCollatorForWholeWordMask(
												    tokenizer=__magic_name__		,    mlm_probability=data_args.mlm_probability						)
								else:
												lowercase         =      DataCollatorForLanguageModeling(
												    tokenizer=__magic_name__		,    mlm=data_args.mlm		,    mlm_probability=data_args.mlm_probability						)

    # Initialize our Trainer
				lowercase         =      Trainer(
				    model=__magic_name__		,    args=__magic_name__		,    data_collator=__magic_name__		,    train_dataset=__magic_name__		,    eval_dataset=__magic_name__		,    prediction_loss_only=__magic_name__		,    )

				# Training
				if training_args.do_train:
								lowercase         =      (
								    model_args.model_name_or_path
								    if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path						)
								    else None
								)
								trainer.train(model_path=__magic_name__						)
								trainer.save_model()
								# For convenience, we also re-save the tokenizer to the same directory,
								# so that you can share your model easily on huggingface.co/models =)
								if trainer.is_world_master():
												tokenizer.save_pretrained(training_args.output_dir						)

    # Evaluation
				lowercase         =      {}
				if training_args.do_eval:
								logger.info("*** Evaluate ***"						)

								lowercase         =      trainer.evaluate()

								lowercase         =      math.exp(eval_output["eval_loss"]						)
								lowercase         =      {"perplexity": perplexity}

								lowercase         =      os.path.join(training_args.output_dir		,    "eval_results_lm.txt"						)
								if trainer.is_world_master():
												with open(__magic_name__		,    "w"						) as writer:
																logger.info("***** Eval results *****"						)
																for key in sorted(result.keys()						):
																				logger.info("  %s = %s"		,    __magic_name__		,    str(result[key]						)						)
																				writer.write("%s = %s\n" % (key, str(result[key]						))						)

								results.update(__magic_name__						)

				return results

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				main()


if __name__ == "__main__":
						main()


from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


_snake_case      :							Any     	=    logging.get_logger(__name__)





class   UpperCamelCase_      (      __a		):







						'''simple docstring'''



						UpperCamelCase      :  Any				   =					['''input_features''', '''attention_mask''']





						def __init__(			self							:List[Any]		,    lowerCAmelCase__							:List[Any]=80		,    lowerCAmelCase__							:int=16000		,    lowerCAmelCase__							:str=0.0		,    lowerCAmelCase__							:int=10		,    lowerCAmelCase__							:List[Any]=25		,    lowerCAmelCase__							:List[str]="hamming_window"		,    lowerCAmelCase__							:int=3_27_68.0		,    lowerCAmelCase__							:str=0.97		,    lowerCAmelCase__							:List[str]=1.0		,    lowerCAmelCase__							:Optional[int]=True		,    lowerCAmelCase__							:Tuple=True		,    lowerCAmelCase__							:str=False		,    **lowerCAmelCase__							:Optional[Any]		,    )  ->Union[str, Any]:
										super().__init__(feature_size=lowerCAmelCase__		,    sampling_rate=lowerCAmelCase__		,    padding_value=lowerCAmelCase__		,    **lowerCAmelCase__     )

										lowercase         =      feature_size
										lowercase         =      sampling_rate
										lowercase         =      padding_value
										lowercase         =      hop_length
										lowercase         =      win_length
										lowercase         =      frame_signal_scale
										lowercase         =      preemphasis_coeff
										lowercase         =      mel_floor
										lowercase         =      normalize_means
										lowercase         =      normalize_vars
										lowercase         =      win_function
										lowercase         =      return_attention_mask

										lowercase         =      win_length * sampling_rate // 1000
										lowercase         =      hop_length * sampling_rate // 1000

										lowercase         =      optimal_fft_length(self.sample_size     )
										lowercase         =      (self.n_fft // 2) + 1





						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]		,    lowerCAmelCase__							:np.array     )  ->np.ndarray:
										if self.win_function == "hamming_window":
														lowercase         =      window_function(window_length=self.sample_size		,    name=self.win_function		,    periodic=lowerCAmelCase__     )
										else:
														lowercase         =      window_function(window_length=self.sample_size		,    name=self.win_function     )

										lowercase         =      mel_filter_bank(
										    num_frequency_bins=self.n_freqs		,    num_mel_filters=self.feature_size		,    min_frequency=0.0		,    max_frequency=self.sampling_rate / 2.0		,    sampling_rate=self.sampling_rate		,    )

										lowercase         =      spectrogram(
										    one_waveform * self.frame_signal_scale		,    window=lowerCAmelCase__		,    frame_length=self.sample_size		,    hop_length=self.sample_stride		,    fft_length=self.n_fft		,    center=lowerCAmelCase__		,    preemphasis=self.preemphasis_coeff		,    mel_filters=lowerCAmelCase__		,    mel_floor=self.mel_floor		,    log_mel="log"		,    )
										return msfc_features.T





						def        SCREAMING_SNAKE_CASE(			self							:Tuple		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Dict     )  ->int:
										# make sure we normalize float32 arrays
										if self.normalize_means:
														lowercase         =      x[:input_length].mean(axis=0     )
														lowercase         =      np.subtract(lowerCAmelCase__		,    lowerCAmelCase__     )
										if self.normalize_vars:
														lowercase         =      x[:input_length].std(axis=0     )
														lowercase         =      np.divide(lowerCAmelCase__		,    lowerCAmelCase__     )

										if input_length < x.shape[0]:
														lowercase         =      padding_value

										# make sure array is in float32
										lowercase         =      x.astype(np.floataa     )

										return x





						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]		,    lowerCAmelCase__							:List[np.ndarray]		,    lowerCAmelCase__							:Optional[np.ndarray] = None     )  ->List[np.ndarray]:
										lowercase         =      attention_mask.sum(-1     ) if attention_mask is not None else [x.shape[0] for x in input_features]
										return [self._normalize_one(lowerCAmelCase__		,    lowerCAmelCase__		,    self.padding_value     ) for x, n in zip(lowerCAmelCase__		,    lowerCAmelCase__     )]





						def __call__(			self							:Any		,    lowerCAmelCase__							:Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]		,    lowerCAmelCase__							:Union[bool, str, PaddingStrategy] = False		,    lowerCAmelCase__							:Optional[int] = None		,    lowerCAmelCase__							:bool = False		,    lowerCAmelCase__							:Optional[int] = None		,    lowerCAmelCase__							:Optional[bool] = None		,    lowerCAmelCase__							:Optional[Union[str, TensorType]] = None		,    lowerCAmelCase__							:Optional[int] = None		,    **lowerCAmelCase__							:Union[str, Any]		,    )  ->BatchFeature:

										if sampling_rate is not None:
														if sampling_rate != self.sampling_rate:
																		raise ValueError(
																		    F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
																		    F''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
																		    F''' {self.sampling_rate} and not {sampling_rate}.'''     )
										else:
														logger.warning(
														    "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
														    "Failing to do so can result in silent errors that might be hard to debug."     )

										lowercase         =      isinstance(lowerCAmelCase__		,    np.ndarray     ) and len(raw_speech.shape     ) > 1
										if is_batched_numpy and len(raw_speech.shape     ) > 2:
														raise ValueError(F'''Only mono-channel audio is supported for input to {self}'''     )
										lowercase         =      is_batched_numpy or (
										    isinstance(lowerCAmelCase__		,    (list, tuple)     ) and (isinstance(raw_speech[0]		,    (np.ndarray, tuple, list)     ))
										)

										if is_batched:
														lowercase         =      [np.asarray(lowerCAmelCase__		,    dtype=np.floataa     ) for speech in raw_speech]
										elif not is_batched and not isinstance(lowerCAmelCase__		,    np.ndarray     ):
														lowercase         =      np.asarray(lowerCAmelCase__		,    dtype=np.floataa     )
										elif isinstance(lowerCAmelCase__		,    np.ndarray     ) and raw_speech.dtype is np.dtype(np.floataa     ):
														lowercase         =      raw_speech.astype(np.floataa     )

										# always return batch
										if not is_batched:
														lowercase         =      [raw_speech]

										# extract fbank features
										lowercase         =      [self._extract_mfsc_features(lowerCAmelCase__     ) for one_waveform in raw_speech]

										# convert into correct format for padding
										lowercase         =      BatchFeature({"input_features": features}     )

										lowercase         =      self.pad(
										    lowerCAmelCase__		,    padding=lowerCAmelCase__		,    max_length=lowerCAmelCase__		,    truncation=lowerCAmelCase__		,    pad_to_multiple_of=lowerCAmelCase__		,    return_attention_mask=lowerCAmelCase__		,    **lowerCAmelCase__		,    )
										# make sure list is in array format
										lowercase         =      padded_inputs.get("input_features"     )
										if isinstance(input_features[0]		,    lowerCAmelCase__     ):
														lowercase         =      [np.asarray(lowerCAmelCase__		,    dtype=np.floataa     ) for feature in input_features]

										lowercase         =      padded_inputs.get("attention_mask"     )
										if attention_mask is not None:
														lowercase         =      [np.asarray(lowerCAmelCase__		,    dtype=np.intaa     ) for array in attention_mask]

										if self.normalize_means or self.normalize_vars:
														lowercase         =      (
														    np.array(lowerCAmelCase__		,    dtype=np.intaa     )
														    if self._get_padding_strategies(lowerCAmelCase__		,    max_length=lowerCAmelCase__     ) is not PaddingStrategy.DO_NOT_PAD
														    and padding
														    else None
														)
														lowercase         =      self.normalize(
														    padded_inputs["input_features"]		,    attention_mask=lowerCAmelCase__     )

										if return_tensors is not None:
														lowercase         =      padded_inputs.convert_to_tensors(lowerCAmelCase__     )

										return padded_inputs
