






import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
	from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""):
	a__  	=  True
	from torch.cuda.amp import autocast

a__  	=  logging.getLogger(__name__)

def _UpperCAmelCase (						a    :						int=None	,       a    :						str=None			):
							return field(default_factory=lambda: default	,       metadata=__lowercase			)


@dataclass
class  _lowerCAmelCase      :



				"""simple docstring"""



				_lowercase					: str	     =	field(
				    metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}   )
				_lowercase					: Optional[str]	     =	field(
				    default=a__  ,   metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}  ,   )
				_lowercase					: Optional[bool]	     =	field(
				    default=a__  ,   metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}   )
				_lowercase					: Optional[float]	     =	field(
				    default=0.1  ,   metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}   )
				_lowercase					: Optional[float]	     =	field(
				    default=0.1  ,   metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}   )
				_lowercase					: Optional[float]	     =	field(
				    default=0.1  ,   metadata={
				        '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
				    }  ,   )
				_lowercase					: Optional[float]	     =	field(
				    default=0.1  ,   metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}  ,   )
				_lowercase					: Optional[float]	     =	field(
				    default=0.05  ,   metadata={
				        '''help''': (
				            '''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
				            '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
				            '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
				        )
				    }  ,   )
				_lowercase					: Optional[float]	     =	field(default=0.0  ,   metadata={'''help''': '''The LayerDrop probability.'''}   )


@dataclass
class  _lowerCAmelCase      :



				"""simple docstring"""



				_lowercase					: Optional[str]	     =	field(
				    default=a__  ,   metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}   )
				_lowercase					: Optional[str]	     =	field(
				    default='''train+validation'''  ,   metadata={
				        '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
				    }  ,   )
				_lowercase					: bool	     =	field(
				    default=a__  ,   metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}   )
				_lowercase					: Optional[int]	     =	field(
				    default=a__  ,   metadata={'''help''': '''The number of processes to use for the preprocessing.'''}  ,   )
				_lowercase					: Optional[int]	     =	field(
				    default=a__  ,   metadata={
				        '''help''': (
				            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
				            '''value if set.'''
				        )
				    }  ,   )
				_lowercase					: Optional[int]	     =	field(
				    default=a__  ,   metadata={
				        '''help''': (
				            '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
				            '''value if set.'''
				        )
				    }  ,   )
				_lowercase					: List[str]	     =	list_field(
				    default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''\"\"''', '''%''', '''\'''', '''\"''', '''�''']  ,   metadata={'''help''': '''A list of characters to remove from the transcripts.'''}  ,   )


@dataclass
class  _lowerCAmelCase      :



				"""simple docstring"""



				_lowercase					: WavaVecaProcessor
				_lowercase					: Union[bool, str]	     =	True
				_lowercase					: Optional[int]	     =	None
				_lowercase					: Optional[int]	     =	None
				_lowercase					: Optional[int]	     =	None
				_lowercase					: Optional[int]	     =	None



				def __call__(   self     :     Any      ,		UpperCamelCase__     :     str):






											'''simple docstring'''







											snake_case__							=							[{"""input_values""": feature["""input_values"""]} for feature in features]
											snake_case__							=							[{"""input_ids""": feature["""labels"""]} for feature in features]

											snake_case__							=							self.processor.pad(
											    __a      ,		padding=self.padding      ,		max_length=self.max_length      ,		pad_to_multiple_of=self.pad_to_multiple_of      ,		return_tensors="""pt"""      ,		)
											snake_case__							=							self.processor.pad(
											    labels=__a      ,		padding=self.padding      ,		max_length=self.max_length_labels      ,		pad_to_multiple_of=self.pad_to_multiple_of_labels      ,		return_tensors="""pt"""      ,		)

											# replace padding with -100 to ignore loss correctly
											snake_case__							=							labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1)      ,		-1_0_0)

											snake_case__							=							labels

											return batch


class  _lowerCAmelCase      (		a__   ):



				"""simple docstring"""



				def        __magic_name__				(   self     :     str      ,		UpperCamelCase__     :     Any      ,		UpperCamelCase__     :     Optional[Any]):






											'''simple docstring'''







											model.train()
											snake_case__							=							self._prepare_inputs(__a)

											if self.use_amp:
																		with autocast():
																									snake_case__							=							self.compute_loss(__a      ,		__a)
											else:
																		snake_case__							=							self.compute_loss(__a      ,		__a)

											if self.args.n_gpu > 1:
																		if model.module.config.ctc_loss_reduction == "mean":
																									snake_case__							=							loss.mean()
																		elif model.module.config.ctc_loss_reduction == "sum":
																									snake_case__							=							loss.sum() / (inputs["""labels"""] >= 0).sum()
																		else:
																									raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''')

											if self.args.gradient_accumulation_steps > 1:
																		snake_case__							=							loss / self.args.gradient_accumulation_steps

											if self.use_amp:
																		self.scaler.scale(__a).backward()
											elif self.use_apex:
																		with amp.scale_loss(__a      ,		self.optimizer) as scaled_loss:
																									scaled_loss.backward()
											elif self.deepspeed:
																		self.deepspeed.backward(__a)
											else:
																		loss.backward()

											return loss.detach()


def _UpperCAmelCase (						):
							# See all possible arguments in src/transformers/training_args.py
							# or by passing the --help flag to this script.
							# We now keep distinct sets of args, for a cleaner separation of concerns.

							snake_case__							=							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.
														snake_case__							=							parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
							else:
														snake_case__							=							parser.parse_args_into_dataclasses()

							# Detecting last checkpoint.
							snake_case__							=							None
							if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
														snake_case__							=							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 overcome."""			)
														elif last_checkpoint is not 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."""			)

    # 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			)]	,       )
							logger.setLevel(logging.INFO if is_main_process(training_args.local_rank			) else logging.WARN			)

							# 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}'''			)
							# 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()
							logger.info("""Training/evaluation parameters %s"""	,       __lowercase			)

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

							# Get the datasets:
							snake_case__							=							datasets.load_dataset(
							    """common_voice"""	,       data_args.dataset_config_name	,       split=data_args.train_split_name			)
							snake_case__							=							datasets.load_dataset("""common_voice"""	,       data_args.dataset_config_name	,       split="""test"""			)

							# Create and save tokenizer
							snake_case__							=							F'''[{''.join(data_args.chars_to_ignore			)}]'''

							def remove_special_characters(a    :						Any			):
														snake_case__							=							re.sub(__lowercase	,       """"""	,       batch["""sentence"""]			).lower() + """ """
														return batch

							snake_case__							=							train_dataset.map(__lowercase	,       remove_columns=["""sentence"""]			)
							snake_case__							=							eval_dataset.map(__lowercase	,       remove_columns=["""sentence"""]			)

							def extract_all_chars(a    :						Optional[Any]			):
														snake_case__							=							""" """.join(batch["""text"""]			)
														snake_case__							=							list(set(__lowercase			)			)
														return {"vocab": [vocab], "all_text": [all_text]}

							snake_case__							=							train_dataset.map(
							    __lowercase	,       batched=__lowercase	,       batch_size=-1	,       keep_in_memory=__lowercase	,       remove_columns=train_dataset.column_names	,       )
							snake_case__							=							train_dataset.map(
							    __lowercase	,       batched=__lowercase	,       batch_size=-1	,       keep_in_memory=__lowercase	,       remove_columns=eval_dataset.column_names	,       )

							snake_case__							=							list(set(vocab_train["""vocab"""][0]			) | set(vocab_test["""vocab"""][0]			)			)
							snake_case__							=							{v: k for k, v in enumerate(__lowercase			)}
							snake_case__							=							vocab_dict[""" """]
							del vocab_dict[" "]
							snake_case__							=							len(__lowercase			)
							snake_case__							=							len(__lowercase			)

							with open("""vocab.json"""	,       """w"""			) as vocab_file:
														json.dump(__lowercase	,       __lowercase			)

							# Load pretrained model and tokenizer
							#
							# Distributed training:
							# The .from_pretrained methods guarantee that only one local process can concurrently
							# download model & vocab.
							snake_case__							=							WavaVecaCTCTokenizer(
							    """vocab.json"""	,       unk_token="""[UNK]"""	,       pad_token="""[PAD]"""	,       word_delimiter_token="""|"""	,       )
							snake_case__							=							WavaVecaFeatureExtractor(
							    feature_size=1	,       sampling_rate=1_6000	,       padding_value=0.0	,       do_normalize=__lowercase	,       return_attention_mask=__lowercase			)
							snake_case__							=							WavaVecaProcessor(feature_extractor=__lowercase	,       tokenizer=__lowercase			)
							snake_case__							=							WavaVecaForCTC.from_pretrained(
							    model_args.model_name_or_path	,       cache_dir=model_args.cache_dir	,       activation_dropout=model_args.activation_dropout	,       attention_dropout=model_args.attention_dropout	,       hidden_dropout=model_args.hidden_dropout	,       feat_proj_dropout=model_args.feat_proj_dropout	,       mask_time_prob=model_args.mask_time_prob	,       gradient_checkpointing=training_args.gradient_checkpointing	,       layerdrop=model_args.layerdrop	,       ctc_loss_reduction="""mean"""	,       pad_token_id=processor.tokenizer.pad_token_id	,       vocab_size=len(processor.tokenizer			)	,       )

							if data_args.max_train_samples is not None:
														snake_case__							=							min(len(__lowercase			)	,       data_args.max_train_samples			)
														snake_case__							=							train_dataset.select(range(__lowercase			)			)

							if data_args.max_val_samples is not None:
														snake_case__							=							eval_dataset.select(range(data_args.max_val_samples			)			)

							snake_case__							=							torchaudio.transforms.Resample(4_8000	,       1_6000			)

							# Preprocessing the datasets.
							# We need to read the aduio files as arrays and tokenize the targets.
							def speech_file_to_array_fn(a    :						Tuple			):
														snake_case__							=							torchaudio.load(batch["""path"""]			)
														snake_case__							=							resampler(__lowercase			).squeeze().numpy()
														snake_case__							=							1_6000
														snake_case__							=							batch["""text"""]
														return batch

							snake_case__							=							train_dataset.map(
							    __lowercase	,       remove_columns=train_dataset.column_names	,       num_proc=data_args.preprocessing_num_workers	,       )
							snake_case__							=							eval_dataset.map(
							    __lowercase	,       remove_columns=eval_dataset.column_names	,       num_proc=data_args.preprocessing_num_workers	,       )

							def prepare_dataset(a    :						Union[str, Any]			):
														# check that all files have the correct sampling rate
														assert (
														    len(set(batch["""sampling_rate"""]			)			) == 1
														), F'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

														snake_case__							=							processor(
														    audio=batch["""speech"""]	,       text=batch["""target_text"""]	,       sampling_rate=batch["""sampling_rate"""][0]			)
														batch.update(__lowercase			)
														return batch

							snake_case__							=							train_dataset.map(
							    __lowercase	,       remove_columns=train_dataset.column_names	,       batch_size=training_args.per_device_train_batch_size	,       batched=__lowercase	,       num_proc=data_args.preprocessing_num_workers	,       )
							snake_case__							=							eval_dataset.map(
							    __lowercase	,       remove_columns=eval_dataset.column_names	,       batch_size=training_args.per_device_train_batch_size	,       batched=__lowercase	,       num_proc=data_args.preprocessing_num_workers	,       )

							# Metric
							snake_case__							=							datasets.load_metric("""wer"""			)

							def compute_metrics(a    :						Optional[int]			):
														snake_case__							=							pred.predictions
														snake_case__							=							np.argmax(__lowercase	,       axis=-1			)

														snake_case__							=							processor.tokenizer.pad_token_id

														snake_case__							=							processor.batch_decode(__lowercase			)
														# we do not want to group tokens when computing the metrics
														snake_case__							=							processor.batch_decode(pred.label_ids	,       group_tokens=__lowercase			)

														snake_case__							=							wer_metric.compute(predictions=__lowercase	,       references=__lowercase			)

														return {"wer": wer}

							if model_args.freeze_feature_extractor:
														model.freeze_feature_extractor()

							# Data collator
							snake_case__							=							DataCollatorCTCWithPadding(processor=__lowercase	,       padding=__lowercase			)

							# Initialize our Trainer
							snake_case__							=							CTCTrainer(
							    model=__lowercase	,       data_collator=__lowercase	,       args=__lowercase	,       compute_metrics=__lowercase	,       train_dataset=train_dataset if training_args.do_train else None	,       eval_dataset=eval_dataset if training_args.do_eval else None	,       tokenizer=processor.feature_extractor	,       )

							# Training
							if training_args.do_train:
														if last_checkpoint is not None:
																					snake_case__							=							last_checkpoint
														elif os.path.isdir(model_args.model_name_or_path			):
																					snake_case__							=							model_args.model_name_or_path
														else:
																					snake_case__							=							None

														# Save the feature_extractor and the tokenizer
														if is_main_process(training_args.local_rank			):
																					processor.save_pretrained(training_args.output_dir			)

														snake_case__							=							trainer.train(resume_from_checkpoint=__lowercase			)
														trainer.save_model()

														snake_case__							=							train_result.metrics
														snake_case__							=							(
														    data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowercase			)
														)
														snake_case__							=							min(__lowercase	,       len(__lowercase			)			)

														trainer.log_metrics("""train"""	,       __lowercase			)
														trainer.save_metrics("""train"""	,       __lowercase			)
														trainer.save_state()

							# Evaluation
							snake_case__							=							{}
							if training_args.do_eval:
														logger.info("""*** Evaluate ***"""			)
														snake_case__							=							trainer.evaluate()
														snake_case__							=							data_args.max_val_samples if data_args.max_val_samples is not None else len(__lowercase			)
														snake_case__							=							min(__lowercase	,       len(__lowercase			)			)

														trainer.log_metrics("""eval"""	,       __lowercase			)
														trainer.save_metrics("""eval"""	,       __lowercase			)

							return results


if __name__ == "__main__":
	main()






'''simple docstring'''







# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation

import warnings

from .state import AcceleratorState, GradientState


warnings.filterwarnings("""ignore""", category=UserWarning, module="""torch.optim.lr_scheduler""")







class 					_a :





     '''simple docstring'''



     def __init__(				self							,__a							,__a							,__a = True							,__a = False							)      ->				Dict:
          snake_case			:      List[Any]        =			scheduler
          snake_case			:      List[Any]        =			optimizers if isinstance(__a							,(list, tuple)							) else [optimizers]
          snake_case			:      List[str]        =			split_batches
          snake_case			:      List[str]        =			step_with_optimizer
          snake_case			:      int        =			GradientState()







     def 			snake_case_      (				self							,*__a							,**__a							)      ->				Optional[Any]:
          if not self.step_with_optimizer:
               # No link between scheduler and optimizer -> just step
               self.scheduler.step(*__a							,**__a							)
               return

          # Otherwise, first make sure the optimizer was stepped.
          if not self.gradient_state.sync_gradients:
               if self.gradient_state.adjust_scheduler:
                    self.scheduler._step_count += 1
               return

          for opt in self.optimizers:
               if opt.step_was_skipped:
                    return
          if self.split_batches:
               # Split batches -> the training dataloader batch size is not changed so one step per training step
               self.scheduler.step(*__a							,**__a							)
          else:
               # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
               # num_processes steps per training step
               snake_case			:      List[str]        =			AcceleratorState().num_processes
               for _ in range(__a							):
                    # Special case when using OneCycle and `drop_last` was not used
                    if hasattr(self.scheduler							,"""total_steps"""							):
                         if self.scheduler._step_count <= self.scheduler.total_steps:
                              self.scheduler.step(*__a							,**__a							)
                    else:
                         self.scheduler.step(*__a							,**__a							)







     def 			snake_case_      (				self							)      ->				Dict:
          return self.scheduler.get_last_lr()







     def 			snake_case_      (				self							)      ->				int:
          return self.scheduler.state_dict()







     def 			snake_case_      (				self							,__a							)      ->				Any:
          self.scheduler.load_state_dict(__a							)







     def 			snake_case_      (				self							)      ->				Any:
          return self.scheduler.get_lr()







     def 			snake_case_      (				self							,*__a							,**__a							)      ->				Optional[Any]:
          return self.scheduler.print_lr(*__a							,**__a							)



