





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


UpperCAmelCase_       : str							=    logging.getLogger(__name__)





@dataclass
class   lowercase__     :
  __UpperCamelCase						  =	field(
      metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	)
  __UpperCamelCase						  =	field(
      default=__A  ,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}  ,       )
  __UpperCamelCase						  =	field(
      default=__A  ,       metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}	)
  __UpperCamelCase						  =	field(
      default=__A  ,       metadata={"""help""": """Whether to log verbose messages or not."""}  ,       )






def 				_lowerCAmelCase			(	_a :       ModelArguments       , _a :       TrainingArguments      )						->      List[str]:
     logging.basicConfig(
         format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""       , datefmt="""%m/%d/%Y %H:%M:%S"""       , handlers=[logging.StreamHandler(sys.stdout      )]       , )
     lowerCAmelCase_       :							Union[str, Any]			 =		logging.WARNING
     if model_args.verbose_logging:
          lowerCAmelCase_       :							Any			 =		logging.DEBUG
     elif trainer_utils.is_main_process(training_args.local_rank      ):
          lowerCAmelCase_       :							Optional[Any]			 =		logging.INFO
     logger.setLevel(_a      )





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





@dataclass
class   lowercase__     :
  __UpperCamelCase						  =	False
  __UpperCamelCase						  =	None
  __UpperCamelCase						  =	"|"
  __UpperCamelCase						  =	field(default_factory=__A	)
  __UpperCamelCase						  =	field(default_factory=__A	)
  __UpperCamelCase						  =	None







  @classmethod
  def 						UpperCAmelCase__		(						cls     ,    _lowercase    ):
       if name == "librispeech":
            return cls()
       if name == "timit":
            return cls(
                do_lower_case=_lowercase     ,    translation_table=str.maketrans({"""-""": """ """}    )     ,    )
       if name == "buckwalter":
            lowerCAmelCase_       :							Union[str, Any]			 =		{
                """-""": """ """,  # sometimes used to represent pauses
                """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
            }
            return cls(
                vocab_file=pathlib.Path(_lowercase    ).parent.joinpath("""vocab/buckwalter.json"""    )     ,    word_delimiter_token="""/"""     ,    translation_table=str.maketrans(_lowercase    )     ,    words_to_remove={"""sil"""}     ,    untransliterator=arabic.buckwalter.untransliterate     ,    )
       raise ValueError(F'Unsupported orthography: \'{name}\'.'    )







  def 						UpperCAmelCase__		(						self     ,    _lowercase    ):
       # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
       if len(self.translation_table    ) > 0:
            lowerCAmelCase_       :							Tuple			 =		text.translate(self.translation_table    )
       if len(self.words_to_remove    ) == 0:
            lowerCAmelCase_       :							str			 =		""" """.join(text.split()    )  # clean up whitespaces
       else:
            lowerCAmelCase_       :							List[Any]			 =		""" """.join(w for w in text.split() if w not in self.words_to_remove    )  # and clean up whilespaces
       return text







  def 						UpperCAmelCase__		(						self     ,    _lowercase    ):
       lowerCAmelCase_       :							Dict			 =		WavaVecaFeatureExtractor.from_pretrained(
           model_args.model_name_or_path     ,    cache_dir=model_args.cache_dir    )
       if self.vocab_file:
            lowerCAmelCase_       :							str			 =		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:
            lowerCAmelCase_       :							Any			 =		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(_lowercase     ,    _lowercase    )





@dataclass
class   lowercase__     :
  __UpperCamelCase						  =	42
  __UpperCamelCase						  =	True
  __UpperCamelCase						  =	None
  __UpperCamelCase						  =	None
  __UpperCamelCase						  =	None
  __UpperCamelCase						  =	None







  def __call__(						self     ,    _lowercase    ):
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       lowerCAmelCase_       :							List[Any]			 =		[{"""input_values""": feature["""input_values"""]} for feature in features]
       lowerCAmelCase_       :							str			 =		[{"""input_ids""": feature["""labels"""]} for feature in features]

       lowerCAmelCase_       :							Dict			 =		self.processor.pad(
           _lowercase     ,    padding=self.padding     ,    max_length=self.max_length     ,    pad_to_multiple_of=self.pad_to_multiple_of     ,    return_tensors="""pt"""     ,    )
       lowerCAmelCase_       :							Union[str, Any]			 =		self.processor.pad(
           labels=_lowercase     ,    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
       lowerCAmelCase_       :							List[str]			 =		labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1    )     ,    -100    )

       lowerCAmelCase_       :							str			 =		labels

       return batch





class   lowercase__     (				__A	):







  def 						UpperCAmelCase__		(						self     ,    _lowercase     ,    _lowercase    ):
       model.train()
       lowerCAmelCase_       :							List[Any]			 =		self._prepare_inputs(_lowercase    )

       if self.use_amp:
            with autocast():
                 lowerCAmelCase_       :							Union[str, Any]			 =		self.compute_loss(_lowercase     ,    _lowercase    )
       else:
            lowerCAmelCase_       :							Any			 =		self.compute_loss(_lowercase     ,    _lowercase    )

       if self.args.n_gpu > 1:
            if model.module.config.ctc_loss_reduction == "mean":
                 lowerCAmelCase_       :							Optional[Any]			 =		loss.mean()
            elif model.module.config.ctc_loss_reduction == "sum":
                 lowerCAmelCase_       :							Tuple			 =		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:
            lowerCAmelCase_       :							Union[str, Any]			 =		loss / self.args.gradient_accumulation_steps

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

       return loss.detach()






def 				_lowerCAmelCase			(	)						->      List[Any]:
     # 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.

     lowerCAmelCase_       :							Dict			 =		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )

     lowerCAmelCase_ ,	lowerCAmelCase_ ,	lowerCAmelCase_       :							List[str]			 =		parser.parse_args_into_dataclasses()
     configure_logger(_a       , _a      )

     lowerCAmelCase_       :							Optional[Any]			 =		Orthography.from_name(data_args.orthography.lower()      )
     lowerCAmelCase_       :							List[str]			 =		orthography.create_processor(_a      )
     lowerCAmelCase_       :							Tuple			 =		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      )       , )

     lowerCAmelCase_       :							int			 =		datasets.load_dataset(
         data_args.dataset_name       , data_args.dataset_config_name       , split=data_args.train_split_name      )
     lowerCAmelCase_       :							Union[str, Any]			 =		datasets.load_dataset(
         data_args.dataset_name       , data_args.dataset_config_name       , split=data_args.validation_split_name      )

     lowerCAmelCase_       :							int			 =		datasets.load_metric("""wer"""      )
     lowerCAmelCase_       :							int			 =		processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
     lowerCAmelCase_       :							Optional[int]			 =		"""""".join(t for t in processor.tokenizer.get_vocab().keys() if len(_a      ) == 1      )
     lowerCAmelCase_       :							int			 =		re.compile(  # remove characters not in vocabulary
         RF'[^\s{re.escape(_a      )}]'       , flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0       , )
     lowerCAmelCase_       :							Union[str, Any]			 =		[]

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

     lowerCAmelCase_       :							Any			 =		train_dataset.map(_a       , remove_columns=[data_args.speech_file_column]      )
     lowerCAmelCase_       :							Tuple			 =		val_dataset.map(_a       , remove_columns=[data_args.speech_file_column]      )

     if data_args.max_duration_in_seconds is not None:

          def filter_by_max_duration(_a :       Optional[Any]      ):
               return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

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

     logger.warning(F'Updated {len(_a      )} 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}"'      )
     lowerCAmelCase_       :							str			 =		None

     def prepare_dataset(_a :       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}.'

          lowerCAmelCase_       :							Tuple			 =		processor(
              audio=batch["""speech"""]       , text=batch[data_args.target_text_column]       , sampling_rate=batch["""sampling_rate"""][0]      )
          batch.update(_a      )
          return batch

     lowerCAmelCase_       :							Dict			 =		train_dataset.map(
         _a       , batch_size=training_args.per_device_train_batch_size       , batched=_a       , num_proc=data_args.preprocessing_num_workers       , )
     lowerCAmelCase_       :							List[Any]			 =		val_dataset.map(
         _a       , batch_size=training_args.per_device_train_batch_size       , batched=_a       , num_proc=data_args.preprocessing_num_workers       , )

     lowerCAmelCase_       :							str			 =		DataCollatorCTCWithPadding(processor=_a       , padding=_a      )

     def compute_metrics(_a :       int      ):
          lowerCAmelCase_       :							Optional[Any]			 =		pred.predictions
          lowerCAmelCase_       :							List[Any]			 =		np.argmax(_a       , axis=-1      )

          lowerCAmelCase_       :							Union[str, Any]			 =		processor.tokenizer.pad_token_id

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

          lowerCAmelCase_       :							int			 =		wer_metric.compute(predictions=_a       , references=_a      )

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     lowerCAmelCase_       :							Dict			 =		CTCTrainer(
         model=_a       , data_collator=_a       , args=_a       , compute_metrics=_a       , train_dataset=_a       , eval_dataset=_a       , tokenizer=processor.feature_extractor       , )

     trainer.train()


if __name__ == "__main__":
      main()







from typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


UpperCAmelCase_       : List[Any]							=    {
    """configuration_retribert""": ["""RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RetriBertConfig"""],
    """tokenization_retribert""": ["""RetriBertTokenizer"""],
}

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCAmelCase_       : str							=    ["""RetriBertTokenizerFast"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCAmelCase_       : Optional[Any]							=    [
          """RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """RetriBertModel""",
          """RetriBertPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_retribert import RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RetriBertConfig
      from .tokenization_retribert import RetriBertTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_retribert_fast import RetriBertTokenizerFast

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_retribert import (
                RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                RetriBertModel,
                RetriBertPreTrainedModel,
            )

else:
      import sys

      UpperCAmelCase_       : Tuple							=    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
