


'''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"):
       __lowercase:						Tuple  		=   True
       from torch.cuda.amp import autocast


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







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







def 				SCREAMING_SNAKE_CASE__(						_UpperCamelCase					: Union[str, Any]			,						_UpperCamelCase					: int      )						->    Dict:





   '''simple docstring'''







   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(_UpperCamelCase      )







@dataclass
class        UpperCAmelCase       :
 _lowerCamelCase       :    str			    =    field(
     default=__SCREAMING_SNAKE_CASE						,	metadata={'help': 'The name of the dataset to use (via the datasets library).'})
 _lowerCamelCase       :    Optional[str]			    =    field(
     default=__SCREAMING_SNAKE_CASE						,	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=__SCREAMING_SNAKE_CASE						,	metadata={'help': 'Resample loaded audio to target feature extractor\'s sampling rate or not.'}						,	)
 _lowerCamelCase       :    Optional[float]			    =    field(
     default=__SCREAMING_SNAKE_CASE						,	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=__SCREAMING_SNAKE_CASE						,	metadata={'help': 'Overwrite the cached preprocessed datasets or not.'})
 _lowerCamelCase       :    Optional[int]			    =    field(
     default=__SCREAMING_SNAKE_CASE						,	metadata={'help': 'The number of processes to use for the preprocessing.'}						,	)







@dataclass
class        UpperCAmelCase       :
 _lowerCamelCase       :    bool			    =    False
 _lowerCamelCase       :    Optional[str]			    =    None
 _lowerCamelCase       :    Optional[str]			    =    "|"
 _lowerCamelCase       :    Optional[Dict[str, str]]			    =    field(default_factory=__SCREAMING_SNAKE_CASE)
 _lowerCamelCase       :    Optional[Set[str]]			    =    field(default_factory=__SCREAMING_SNAKE_CASE)
 _lowerCamelCase       :    Optional[Callable[[str], str]]			    =    None

 @classmethod
 def 						lowercase_  (       cls       :		str,    a_       :		Optional[int]    ):





    """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 						lowercase_  (       self       :		str,    a_       :		Dict    ):





    """simple docstring"""



    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 						lowercase_  (       self       :		Optional[Any],    a_       :		str    ):





    """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        UpperCAmelCase       :
 _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       :		Optional[Any],    a_       :		Any    ):





    """simple docstring"""



    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    ),    -100    )

    UpperCamelCase__         =  labels

    return batch







class        UpperCAmelCase       (				__SCREAMING_SNAKE_CASE):

 def 						lowercase_  (       self       :		Tuple,    a_       :		List[str],    a_       :		Optional[Any]    ):





    """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 				SCREAMING_SNAKE_CASE__(						)						->    Tuple:





   '''simple docstring'''







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

   UpperCamelCase__         =  parser.parse_args_into_dataclasses()
   configure_logger(_UpperCamelCase			,						_UpperCamelCase      )

   UpperCamelCase__         =  Orthography.from_name(data_args.orthography.lower()      )
   UpperCamelCase__         =  orthography.create_processor(_UpperCamelCase      )
   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(_UpperCamelCase      ) == 1      )
   UpperCamelCase__         =  re.compile(  # remove characters not in vocabulary
       rF'[^\s{re.escape(_UpperCamelCase      )}]'			,						flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0			,						)
   UpperCamelCase__         =  []

   def prepare_example(_UpperCamelCase					: str      ):  # TODO(elgeish) make use of multiprocessing?
      UpperCamelCase__         =  librosa.load(example[data_args.speech_file_column]			,						sr=_UpperCamelCase      )
      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(""			,						_UpperCamelCase      )
      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(_UpperCamelCase			,						remove_columns=[data_args.speech_file_column]      )
   UpperCamelCase__         =  val_dataset.map(_UpperCamelCase			,						remove_columns=[data_args.speech_file_column]      )

   if data_args.max_duration_in_seconds is not None:

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

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

   logger.warning(F'Updated {len(_UpperCamelCase      )} 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(_UpperCamelCase					: List[str]      ):
      # 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(_UpperCamelCase      )
      return batch

   UpperCamelCase__         =  train_dataset.map(
       _UpperCamelCase			,						batch_size=training_args.per_device_train_batch_size			,						batched=_UpperCamelCase			,						num_proc=data_args.preprocessing_num_workers			,						)
   UpperCamelCase__         =  val_dataset.map(
       _UpperCamelCase			,						batch_size=training_args.per_device_train_batch_size			,						batched=_UpperCamelCase			,						num_proc=data_args.preprocessing_num_workers			,						)

   UpperCamelCase__         =  DataCollatorCTCWithPadding(processor=_UpperCamelCase			,						padding=_UpperCamelCase      )

   def compute_metrics(_UpperCamelCase					: int      ):
      UpperCamelCase__         =  pred.predictions
      UpperCamelCase__         =  np.argmax(_UpperCamelCase			,						axis=-1      )

      UpperCamelCase__         =  processor.tokenizer.pad_token_id

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

      UpperCamelCase__         =  wer_metric.compute(predictions=_UpperCamelCase			,						references=_UpperCamelCase      )

      return {"wer": wer}

   if model_args.freeze_feature_extractor:
      model.freeze_feature_extractor()

   UpperCamelCase__         =  CTCTrainer(
       model=_UpperCamelCase			,						data_collator=_UpperCamelCase			,						args=_UpperCamelCase			,						compute_metrics=_UpperCamelCase			,						train_dataset=_UpperCamelCase			,						eval_dataset=_UpperCamelCase			,						tokenizer=processor.feature_extractor			,						)

   trainer.train()


if __name__ == "__main__":
       main()





def  lowerCAmelCase  (	UpperCAmelCase       )  ->str:






					"""simple docstring"""






					return " ".join(sorted(set(sentence.split()       )       )       )


if __name__ == "__main__":
				import doctest

				doctest.testmod()



