

'''simple docstring'''




import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


_a				: Any 							=						logging.getLogger(__name__)

require_version('pytorch_lightning>=1.0.4')

_a				: Tuple 							=						{
    'base': AutoModel,
    'sequence-classification': AutoModelForSequenceClassification,
    'question-answering': AutoModelForQuestionAnswering,
    'pretraining': AutoModelForPreTraining,
    'token-classification': AutoModelForTokenClassification,
    'language-modeling': AutoModelWithLMHead,
    'summarization': AutoModelForSeqaSeqLM,
    'translation': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
_a				: List[Any] 							=						{
    'linear': get_linear_schedule_with_warmup,
    'cosine': get_cosine_schedule_with_warmup,
    'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup,
    'polynomial': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
_a				: Optional[int] 							=						sorted(arg_to_scheduler.keys())
_a				: str 							=						'{' + ', '.join(arg_to_scheduler_choices) + '}'



class        lowercase_	(		pl.LightningModule ):

  '''simple docstring'''





  def __init__(     self   , a_   , a_=None   , a_="base"   , a_=None   , a_=None   , a_=None   , **a_   , )							->				Optional[int]:


    """simple docstring"""
    super().__init__()
    # TODO: move to self.save_hyperparameters()
    # self.save_hyperparameters()
    # can also expand arguments into trainer signature for easier reading

    self.save_hyperparameters(__lowerCamelCase     )
    UpperCAmelCase													=	0
    UpperCAmelCase													=	Path(self.hparams.output_dir     )
    UpperCAmelCase													=	self.hparams.cache_dir if self.hparams.cache_dir else None
    if config is None:
      UpperCAmelCase													=	AutoConfig.from_pretrained(
          self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path   , **({'num_labels': num_labels} if num_labels is not None else {})   , cache_dir=__lowerCamelCase   , **__lowerCamelCase   , )
    else:
      UpperCAmelCase													=	config

    UpperCAmelCase													=	("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout")
    for p in extra_model_params:
      if getattr(self.hparams   , __lowerCamelCase   , __lowerCamelCase     ):
        assert hasattr(self.config   , __lowerCamelCase     ), F'''model config doesn\'t have a `{p}` attribute'''
        setattr(self.config   , __lowerCamelCase   , getattr(self.hparams   , __lowerCamelCase     )     )

    if tokenizer is None:
      UpperCAmelCase													=	AutoTokenizer.from_pretrained(
          self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path   , cache_dir=__lowerCamelCase   , )
    else:
      UpperCAmelCase													=	tokenizer
    UpperCAmelCase													=	MODEL_MODES[mode]
    if model is None:
      UpperCAmelCase													=	self.model_type.from_pretrained(
          self.hparams.model_name_or_path   , from_tf=bool('.ckpt' in self.hparams.model_name_or_path     )   , config=self.config   , cache_dir=__lowerCamelCase   , )
    else:
      UpperCAmelCase													=	model
  def 						snake_case_			(     self   , *a_   , **a_     )							->				Dict:


    """simple docstring"""
    UpperCAmelCase													=	self.model_type.from_pretrained(*__lowerCamelCase   , **__lowerCamelCase     )
  def 						snake_case_			(     self     )							->				Tuple:


    """simple docstring"""
    UpperCAmelCase													=	arg_to_scheduler[self.hparams.lr_scheduler]
    UpperCAmelCase													=	get_schedule_func(
        self.opt   , num_warmup_steps=self.hparams.warmup_steps   , num_training_steps=self.total_steps()     )
    UpperCAmelCase													=	{"scheduler": scheduler, "interval": "step", "frequency": 1}
    return scheduler
  def 						snake_case_			(     self     )							->				List[str]:


    """simple docstring"""
    UpperCAmelCase													=	self.model
    UpperCAmelCase													=	["bias", "LayerNorm.weight"]
    UpperCAmelCase													=	[
        {
            "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay     )],
            "weight_decay": self.hparams.weight_decay,
        },
        {
            "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay     )],
            "weight_decay": 0.0,
        },
    ]
    if self.hparams.adafactor:
      UpperCAmelCase													=	Adafactor(
          __lowerCamelCase   , lr=self.hparams.learning_rate   , scale_parameter=__lowerCamelCase   , relative_step=__lowerCamelCase     )

    else:
      UpperCAmelCase													=	AdamW(
          __lowerCamelCase   , lr=self.hparams.learning_rate   , eps=self.hparams.adam_epsilon     )
    UpperCAmelCase													=	optimizer

    UpperCAmelCase													=	self.get_lr_scheduler()

    return [optimizer], [scheduler]
  def 						snake_case_			(     self   , a_   , a_     )							->				Dict:


    """simple docstring"""
    return self.validation_step(__lowerCamelCase   , __lowerCamelCase     )
  def 						snake_case_			(     self   , a_     )							->				Optional[int]:


    """simple docstring"""
    return self.validation_end(__lowerCamelCase     )
  def 						snake_case_			(     self     )							->				int:


    """simple docstring"""
    UpperCAmelCase													=	max(1   , self.hparams.gpus     )  # TODO: consider num_tpu_cores
    UpperCAmelCase													=	self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
    return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs
  def 						snake_case_			(     self   , a_     )							->				List[Any]:


    """simple docstring"""
    if mode == "test":
      UpperCAmelCase													=	len(self.test_dataloader().dataset     )
    else:
      UpperCAmelCase													=	self.get_dataloader('train'   , self.hparams.train_batch_size   , shuffle=__lowerCamelCase     )
      UpperCAmelCase													=	len(self.train_dataloader().dataset     )
  def 						snake_case_			(     self   , a_   , a_   , a_ = False     )							->				Any:


    """simple docstring"""
    raise NotImplementedError('You must implement this for your task'     )
  def 						snake_case_			(     self     )							->				Optional[int]:


    """simple docstring"""
    return self.train_loader
  def 						snake_case_			(     self     )							->				Tuple:


    """simple docstring"""
    return self.get_dataloader('dev'   , self.hparams.eval_batch_size   , shuffle=__lowerCamelCase     )
  def 						snake_case_			(     self     )							->				str:


    """simple docstring"""
    return self.get_dataloader('test'   , self.hparams.eval_batch_size   , shuffle=__lowerCamelCase     )
  def 						snake_case_			(     self   , a_     )							->				str:


    """simple docstring"""
    return os.path.join(
        self.hparams.data_dir   , 'cached_{}_{}_{}'.format(
            __lowerCamelCase   , list(filter(__lowerCamelCase   , self.hparams.model_name_or_path.split('/'     )     )     ).pop()   , str(self.hparams.max_seq_length     )   , )   , )
  @pl.utilities.rank_zero_only
  def 						snake_case_			(     self   , a_     )							->				None:


    """simple docstring"""
    UpperCAmelCase													=	self.output_dir.joinpath('best_tfmr'     )
    UpperCAmelCase													=	self.step_count
    self.model.save_pretrained(__lowerCamelCase     )
    self.tokenizer.save_pretrained(__lowerCamelCase     )





  @staticmethod
  def 						snake_case_			(     a_   , a_     )							->				str:


    """simple docstring"""
    parser.add_argument(
        '--model_name_or_path'   , default=__lowerCamelCase   , type=__lowerCamelCase   , required=__lowerCamelCase   , help='Path to pretrained model or model identifier from huggingface.co/models'   , )
    parser.add_argument(
        '--config_name'   , default=''   , type=__lowerCamelCase   , help='Pretrained config name or path if not the same as model_name'     )
    parser.add_argument(
        '--tokenizer_name'   , default=__lowerCamelCase   , type=__lowerCamelCase   , help='Pretrained tokenizer name or path if not the same as model_name'   , )
    parser.add_argument(
        '--cache_dir'   , default=''   , type=__lowerCamelCase   , help='Where do you want to store the pre-trained models downloaded from huggingface.co'   , )
    parser.add_argument(
        '--encoder_layerdrop'   , type=__lowerCamelCase   , help='Encoder layer dropout probability (Optional). Goes into model.config'   , )
    parser.add_argument(
        '--decoder_layerdrop'   , type=__lowerCamelCase   , help='Decoder layer dropout probability (Optional). Goes into model.config'   , )
    parser.add_argument(
        '--dropout'   , type=__lowerCamelCase   , help='Dropout probability (Optional). Goes into model.config'   , )
    parser.add_argument(
        '--attention_dropout'   , type=__lowerCamelCase   , help='Attention dropout probability (Optional). Goes into model.config'   , )
    parser.add_argument('--learning_rate'   , default=5E-5   , type=__lowerCamelCase   , help='The initial learning rate for Adam.'     )
    parser.add_argument(
        '--lr_scheduler'   , default='linear'   , choices=__lowerCamelCase   , metavar=__lowerCamelCase   , type=__lowerCamelCase   , help='Learning rate scheduler'   , )
    parser.add_argument('--weight_decay'   , default=0.0   , type=__lowerCamelCase   , help='Weight decay if we apply some.'     )
    parser.add_argument('--adam_epsilon'   , default=1E-8   , type=__lowerCamelCase   , help='Epsilon for Adam optimizer.'     )
    parser.add_argument('--warmup_steps'   , default=0   , type=__lowerCamelCase   , help='Linear warmup over warmup_steps.'     )
    parser.add_argument('--num_workers'   , default=4   , type=__lowerCamelCase   , help='kwarg passed to DataLoader'     )
    parser.add_argument('--num_train_epochs'   , dest='max_epochs'   , default=3   , type=__lowerCamelCase     )
    parser.add_argument('--train_batch_size'   , default=3_2   , type=__lowerCamelCase     )
    parser.add_argument('--eval_batch_size'   , default=3_2   , type=__lowerCamelCase     )
    parser.add_argument('--adafactor'   , action='store_true'     )




class        lowercase_	(		pl.Callback ):

  '''simple docstring'''





  def 						snake_case_			(     self   , a_   , a_     )							->				Union[str, Any]:


    """simple docstring"""
    UpperCAmelCase													=	trainer.lr_schedulers[0]["scheduler"]
    UpperCAmelCase													=	{F'''lr_group_{i}''': lr for i, lr in enumerate(lr_scheduler.get_lr()     )}
    pl_module.logger.log_metrics(__lowerCamelCase     )
  def 						snake_case_			(     self   , a_   , a_     )							->				List[str]:


    """simple docstring"""
    rank_zero_info('***** Validation results *****'     )
    UpperCAmelCase													=	trainer.callback_metrics
    # Log results
    for key in sorted(__lowerCamelCase     ):
      if key not in ["log", "progress_bar"]:
        rank_zero_info('{} = {}\n'.format(__lowerCamelCase   , str(metrics[key]     )     )     )





  def 						snake_case_			(     self   , a_   , a_     )							->				int:


    """simple docstring"""
    rank_zero_info('***** Test results *****'     )
    UpperCAmelCase													=	trainer.callback_metrics
    # Log and save results to file
    UpperCAmelCase													=	os.path.join(pl_module.hparams.output_dir   , 'test_results.txt'     )
    with open(__lowerCamelCase   , 'w'     ) as writer:
      for key in sorted(__lowerCamelCase     ):
        if key not in ["log", "progress_bar"]:
          rank_zero_info('{} = {}\n'.format(__lowerCamelCase   , str(metrics[key]     )     )     )
          writer.write('{} = {}\n'.format(__lowerCamelCase   , str(metrics[key]     )     )     )




def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   Any       ,   SCREAMING_SNAKE_CASE      :   List[Any]						):
  #  To allow all pl args uncomment the following line
  #  parser = pl.Trainer.add_argparse_args(parser)
  parser.add_argument(
      '--output_dir'       ,   default=UpperCamelCase__       ,   type=UpperCamelCase__       ,   required=UpperCamelCase__       ,   help='The output directory where the model predictions and checkpoints will be written.'       ,   )
  parser.add_argument(
      '--fp16'       ,   action='store_true'       ,   help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'       ,   )

  parser.add_argument(
      '--fp16_opt_level'       ,   type=UpperCamelCase__       ,   default='O2'       ,   help=(
          'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'
          'See details at https://nvidia.github.io/apex/amp.html'
      )       ,   )
  parser.add_argument('--n_tpu_cores'       ,   dest='tpu_cores'       ,   type=UpperCamelCase__						)
  parser.add_argument('--max_grad_norm'       ,   dest='gradient_clip_val'       ,   default=1.0       ,   type=UpperCamelCase__       ,   help='Max gradient norm'						)
  parser.add_argument('--do_train'       ,   action='store_true'       ,   help='Whether to run training.'						)
  parser.add_argument('--do_predict'       ,   action='store_true'       ,   help='Whether to run predictions on the test set.'						)
  parser.add_argument(
      '--gradient_accumulation_steps'       ,   dest='accumulate_grad_batches'       ,   type=UpperCamelCase__       ,   default=1       ,   help='Number of updates steps to accumulate before performing a backward/update pass.'       ,   )
  parser.add_argument('--seed'       ,   type=UpperCamelCase__       ,   default=42       ,   help='random seed for initialization'						)
  parser.add_argument(
      '--data_dir'       ,   default=UpperCamelCase__       ,   type=UpperCamelCase__       ,   required=UpperCamelCase__       ,   help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.'       ,   )



def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   BaseTransformer       ,   SCREAMING_SNAKE_CASE      :   argparse.Namespace       ,   SCREAMING_SNAKE_CASE      :   List[Any]=None       ,   SCREAMING_SNAKE_CASE      :   List[str]=True       ,   SCREAMING_SNAKE_CASE      :   int=[]       ,   SCREAMING_SNAKE_CASE      :   Dict=None       ,   SCREAMING_SNAKE_CASE      :   Dict=None       ,   **SCREAMING_SNAKE_CASE      :   Union[str, Any]       ,   ):
  pl.seed_everything(args.seed						)

  # init model
  UpperCAmelCase													=	Path(model.hparams.output_dir						)
  odir.mkdir(exist_ok=UpperCamelCase__						)

  # add custom checkpoints
  if checkpoint_callback is None:
    UpperCAmelCase													=	pl.callbacks.ModelCheckpoint(
        filepath=args.output_dir       ,   prefix='checkpoint'       ,   monitor='val_loss'       ,   mode='min'       ,   save_top_k=1						)
  if early_stopping_callback:
    extra_callbacks.append(UpperCamelCase__						)
  if logging_callback is None:
    UpperCAmelCase													=	LoggingCallback()

  UpperCAmelCase													=	{}

  # TODO: remove with PyTorch 1.6 since pl uses native amp
  if args.fpaa:
    UpperCAmelCase													=	16
    UpperCAmelCase													=	args.fpaa_opt_level

  if args.gpus > 1:
    UpperCAmelCase													=	"ddp"

  UpperCAmelCase													=	args.accumulate_grad_batches
  UpperCAmelCase													=	extra_train_kwargs.get('accelerator'       ,   UpperCamelCase__						)
  UpperCAmelCase													=	extra_train_kwargs.get('profiler'       ,   UpperCamelCase__						)

  UpperCAmelCase													=	pl.Trainer.from_argparse_args(
      UpperCamelCase__       ,   weights_summary=UpperCamelCase__       ,   callbacks=[logging_callback] + extra_callbacks       ,   logger=UpperCamelCase__       ,   checkpoint_callback=UpperCamelCase__       ,   **UpperCamelCase__       ,   )

  if args.do_train:
    trainer.fit(UpperCamelCase__						)

  return trainer









'''simple docstring'''




import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
  from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
  _a				: int 							=						True
  from torch.cuda.amp import autocast


_a				: Optional[int] 							=						logging.getLogger(__name__)



@dataclass
class        lowercase_	:

  '''simple docstring'''





  __lowerCAmelCase					: str      =   field(
      metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
  __lowerCAmelCase					: Optional[str]      =   field(
      default=a ,       metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,       )
  __lowerCAmelCase					: Optional[bool]      =   field(
      default=a ,       metadata={"help": "Whether to freeze the feature extractor layers of the model."} )
  __lowerCAmelCase					: Optional[bool]      =   field(
      default=a ,       metadata={"help": "Whether to log verbose messages or not."} ,       )




def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   ModelArguments       ,   SCREAMING_SNAKE_CASE      :   TrainingArguments						):
  logging.basicConfig(
      format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'       ,   datefmt='%m/%d/%Y %H:%M:%S'       ,   handlers=[logging.StreamHandler(sys.stdout						)]       ,   )
  UpperCAmelCase													=	logging.WARNING
  if model_args.verbose_logging:
    UpperCAmelCase													=	logging.DEBUG
  elif trainer_utils.is_main_process(training_args.local_rank						):
    UpperCAmelCase													=	logging.INFO
  logger.setLevel(SCREAMING_SNAKE_CASE						)



@dataclass
class        lowercase_	:

  '''simple docstring'''





  __lowerCAmelCase					: str      =   field(
      default=a ,       metadata={"help": "The name of the dataset to use (via the datasets library)."} )
  __lowerCAmelCase					: Optional[str]      =   field(
      default=a ,       metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} )
  __lowerCAmelCase					: Optional[str]      =   field(
      default="train" ,       metadata={
          "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
      } ,       )
  __lowerCAmelCase					: Optional[str]      =   field(
      default="validation" ,       metadata={
          "help": (
              "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
          )
      } ,       )
  __lowerCAmelCase					: Optional[str]      =   field(
      default="text" ,       metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"} ,       )
  __lowerCAmelCase					: Optional[str]      =   field(
      default="file" ,       metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"} ,       )
  __lowerCAmelCase					: Optional[bool]      =   field(
      default=a ,       metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."} ,       )
  __lowerCAmelCase					: Optional[float]      =   field(
      default=a ,       metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."} ,       )
  __lowerCAmelCase					: Optional[str]      =   field(
      default="librispeech" ,       metadata={
          "help": (
              "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
              " 'buckwalter'."
          )
      } ,       )
  __lowerCAmelCase					: bool      =   field(
      default=a ,       metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
  __lowerCAmelCase					: Optional[int]      =   field(
      default=a ,       metadata={"help": "The number of processes to use for the preprocessing."} ,       )




@dataclass
class        lowercase_	:

  '''simple docstring'''





  __lowerCAmelCase					: bool      =   False
  __lowerCAmelCase					: Optional[str]      =   None
  __lowerCAmelCase					: Optional[str]      =   "|"
  __lowerCAmelCase					: Optional[Dict[str, str]]      =   field(default_factory=a )
  __lowerCAmelCase					: Optional[Set[str]]      =   field(default_factory=a )
  __lowerCAmelCase					: Optional[Callable[[str], str]]      =   None
  @classmethod
  def 						snake_case_			(     cls   , a_     )							->				Optional[Any]:


    """simple docstring"""
    if name == "librispeech":
      return cls()
    if name == "timit":
      return cls(
          do_lower_case=a_   , translation_table=str.maketrans({'-': ' '}     )   , )
    if name == "buckwalter":
      UpperCAmelCase													=	{
          '-': ' ',  # sometimes used to represent pauses
          '^': 'v',  # fixing "tha" in arabic_speech_corpus dataset
      }
      return cls(
          vocab_file=pathlib.Path(a_     ).parent.joinpath('vocab/buckwalter.json'     )   , word_delimiter_token='/'   , translation_table=str.maketrans(a_     )   , words_to_remove={'sil'}   , untransliterator=arabic.buckwalter.untransliterate   , )
    raise ValueError(F'''Unsupported orthography: \'{name}\'.'''     )
  def 						snake_case_			(     self   , a_     )							->				str:


    """simple docstring"""
    # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
    if len(self.translation_table     ) > 0:
      UpperCAmelCase													=	text.translate(self.translation_table     )
    if len(self.words_to_remove     ) == 0:
      UpperCAmelCase													=	' '.join(text.split()     )  # clean up whitespaces
    else:
      UpperCAmelCase													=	' '.join(w for w in text.split() if w not in self.words_to_remove     )  # and clean up whilespaces
    return text





  def 						snake_case_			(     self   , a_     )							->				WavaVecaProcessor:


    """simple docstring"""
    UpperCAmelCase													=	WavaVecaFeatureExtractor.from_pretrained(
        model_args.model_name_or_path   , cache_dir=model_args.cache_dir     )
    if self.vocab_file:
      UpperCAmelCase													=	WavaVecaCTCTokenizer(
          self.vocab_file   , cache_dir=model_args.cache_dir   , do_lower_case=self.do_lower_case   , word_delimiter_token=self.word_delimiter_token   , )
    else:
      UpperCAmelCase													=	WavaVecaCTCTokenizer.from_pretrained(
          model_args.model_name_or_path   , cache_dir=model_args.cache_dir   , do_lower_case=self.do_lower_case   , word_delimiter_token=self.word_delimiter_token   , )
    return WavaVecaProcessor(a_   , a_     )




@dataclass
class        lowercase_	:

  '''simple docstring'''





  __lowerCAmelCase					: WavaVecaProcessor
  __lowerCAmelCase					: Union[bool, str]      =   True
  __lowerCAmelCase					: Optional[int]      =   None
  __lowerCAmelCase					: Optional[int]      =   None
  __lowerCAmelCase					: Optional[int]      =   None
  __lowerCAmelCase					: Optional[int]      =   None
  def __call__(     self   , a_     )							->				Dict[str, torch.Tensor]:


    """simple docstring"""
    # split inputs and labels since they have to be of different lenghts and need
    # different padding methods
    UpperCAmelCase													=	[{'input_values': feature['input_values']} for feature in features]
    UpperCAmelCase													=	[{'input_ids': feature['labels']} for feature in features]

    UpperCAmelCase													=	self.processor.pad(
        a_   , padding=self.padding   , max_length=self.max_length   , pad_to_multiple_of=self.pad_to_multiple_of   , return_tensors='pt'   , )
    UpperCAmelCase													=	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
    UpperCAmelCase													=	labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1     )   , -1_0_0     )

    UpperCAmelCase													=	labels

    return batch




class        lowercase_	(		a ):

  '''simple docstring'''





  def 						snake_case_			(     self   , a_   , a_     )							->				torch.Tensor:


    """simple docstring"""
    model.train()
    UpperCAmelCase													=	self._prepare_inputs(a_     )

    if self.use_amp:
      with autocast():
        UpperCAmelCase													=	self.compute_loss(a_   , a_     )
    else:
      UpperCAmelCase													=	self.compute_loss(a_   , a_     )

    if self.args.n_gpu > 1:
      if model.module.config.ctc_loss_reduction == "mean":
        UpperCAmelCase													=	loss.mean()
      elif model.module.config.ctc_loss_reduction == "sum":
        UpperCAmelCase													=	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:
      UpperCAmelCase													=	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       lowerCamelCase__		(						):
  # 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.

  UpperCAmelCase													=	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)

  UpperCAmelCase							,      UpperCAmelCase							,      UpperCAmelCase													=	parser.parse_args_into_dataclasses()
  configure_logger(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

  UpperCAmelCase													=	Orthography.from_name(data_args.orthography.lower()						)
  UpperCAmelCase													=	orthography.create_processor(SCREAMING_SNAKE_CASE						)
  UpperCAmelCase													=	WavaVecaForCTC.from_pretrained(
      model_args.model_name_or_path       ,   cache_dir=model_args.cache_dir       ,   gradient_checkpointing=training_args.gradient_checkpointing       ,   vocab_size=len(processor.tokenizer						)       ,   )

  UpperCAmelCase													=	datasets.load_dataset(
      data_args.dataset_name       ,   data_args.dataset_config_name       ,   split=data_args.train_split_name						)
  UpperCAmelCase													=	datasets.load_dataset(
      data_args.dataset_name       ,   data_args.dataset_config_name       ,   split=data_args.validation_split_name						)

  UpperCAmelCase													=	datasets.load_metric('wer'						)
  UpperCAmelCase													=	processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
  UpperCAmelCase													=	''.join(t for t in processor.tokenizer.get_vocab().keys() if len(SCREAMING_SNAKE_CASE						) == 1						)
  UpperCAmelCase													=	re.compile(  # remove characters not in vocabulary
      Rf'''[^\s{re.escape(SCREAMING_SNAKE_CASE						)}]'''       ,   flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0       ,   )
  UpperCAmelCase													=	[]

  def prepare_example(SCREAMING_SNAKE_CASE      :   Dict						):  # TODO(elgeish) make use of multiprocessing?
    UpperCAmelCase							,      UpperCAmelCase													=	librosa.load(example[data_args.speech_file_column]       ,   sr=SCREAMING_SNAKE_CASE						)
    if data_args.max_duration_in_seconds is not None:
      UpperCAmelCase													=	len(example['speech']						) / example['sampling_rate']
    # Normalize and clean up text; order matters!
    UpperCAmelCase													=	orthography.preprocess_for_training(example[data_args.target_text_column]						)
    UpperCAmelCase													=	vocabulary_text_cleaner.sub(''       ,   SCREAMING_SNAKE_CASE						)
    if updated_text != example[data_args.target_text_column]:
      text_updates.append((example[data_args.target_text_column], updated_text)						)
      UpperCAmelCase													=	updated_text
    return example

  UpperCAmelCase													=	train_dataset.map(SCREAMING_SNAKE_CASE       ,   remove_columns=[data_args.speech_file_column]						)
  UpperCAmelCase													=	val_dataset.map(SCREAMING_SNAKE_CASE       ,   remove_columns=[data_args.speech_file_column]						)

  if data_args.max_duration_in_seconds is not None:

    def filter_by_max_duration(SCREAMING_SNAKE_CASE      :   int						):
      return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

    UpperCAmelCase													=	len(SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	len(SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	train_dataset.filter(SCREAMING_SNAKE_CASE       ,   remove_columns=['duration_in_seconds']						)
    UpperCAmelCase													=	val_dataset.filter(SCREAMING_SNAKE_CASE       ,   remove_columns=['duration_in_seconds']						)
    if len(SCREAMING_SNAKE_CASE						) > old_train_size:
      logger.warning(
          f'''Filtered out {len(SCREAMING_SNAKE_CASE						) - old_train_size} train example(s) longer than'''
          f''' {data_args.max_duration_in_seconds} second(s).'''						)
    if len(SCREAMING_SNAKE_CASE						) > old_val_size:
      logger.warning(
          f'''Filtered out {len(SCREAMING_SNAKE_CASE						) - old_val_size} validation example(s) longer than'''
          f''' {data_args.max_duration_in_seconds} second(s).'''						)
  logger.info(f'''Split sizes: {len(SCREAMING_SNAKE_CASE						)} train and {len(SCREAMING_SNAKE_CASE						)} validation.'''						)

  logger.warning(f'''Updated {len(SCREAMING_SNAKE_CASE						)} transcript(s) using \'{data_args.orthography}\' orthography rules.'''						)
  if logger.isEnabledFor(logging.DEBUG						):
    for original_text, updated_text in text_updates:
      logger.debug(f'''Updated text: "{original_text}" -> "{updated_text}"'''						)
  UpperCAmelCase													=	None

  def prepare_dataset(SCREAMING_SNAKE_CASE      :   Optional[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}.'''

    UpperCAmelCase													=	processor(
        audio=batch['speech']       ,   text=batch[data_args.target_text_column]       ,   sampling_rate=batch['sampling_rate'][0]						)
    batch.update(SCREAMING_SNAKE_CASE						)
    return batch

  UpperCAmelCase													=	train_dataset.map(
      SCREAMING_SNAKE_CASE       ,   batch_size=training_args.per_device_train_batch_size       ,   batched=SCREAMING_SNAKE_CASE       ,   num_proc=data_args.preprocessing_num_workers       ,   )
  UpperCAmelCase													=	val_dataset.map(
      SCREAMING_SNAKE_CASE       ,   batch_size=training_args.per_device_train_batch_size       ,   batched=SCREAMING_SNAKE_CASE       ,   num_proc=data_args.preprocessing_num_workers       ,   )

  UpperCAmelCase													=	DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE       ,   padding=SCREAMING_SNAKE_CASE						)

  def compute_metrics(SCREAMING_SNAKE_CASE      :   Optional[int]						):
    UpperCAmelCase													=	pred.predictions
    UpperCAmelCase													=	np.argmax(SCREAMING_SNAKE_CASE       ,   axis=-1						)

    UpperCAmelCase													=	processor.tokenizer.pad_token_id

    UpperCAmelCase													=	processor.batch_decode(SCREAMING_SNAKE_CASE						)
    # we do not want to group tokens when computing the metrics
    UpperCAmelCase													=	processor.batch_decode(pred.label_ids       ,   group_tokens=SCREAMING_SNAKE_CASE						)
    if logger.isEnabledFor(logging.DEBUG						):
      for reference, predicted in zip(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						):
        logger.debug(f'''reference: "{reference}"'''						)
        logger.debug(f'''predicted: "{predicted}"'''						)
        if orthography.untransliterator is not None:
          logger.debug(f'''reference (untransliterated): "{orthography.untransliterator(SCREAMING_SNAKE_CASE						)}"'''						)
          logger.debug(f'''predicted (untransliterated): "{orthography.untransliterator(SCREAMING_SNAKE_CASE						)}"'''						)

    UpperCAmelCase													=	wer_metric.compute(predictions=SCREAMING_SNAKE_CASE       ,   references=SCREAMING_SNAKE_CASE						)

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  UpperCAmelCase													=	CTCTrainer(
      model=SCREAMING_SNAKE_CASE       ,   data_collator=SCREAMING_SNAKE_CASE       ,   args=SCREAMING_SNAKE_CASE       ,   compute_metrics=SCREAMING_SNAKE_CASE       ,   train_dataset=SCREAMING_SNAKE_CASE       ,   eval_dataset=SCREAMING_SNAKE_CASE       ,   tokenizer=processor.feature_extractor       ,   )

  trainer.train()


if __name__ == "__main__":
  main()


