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


SCREAMING_SNAKE_CASE    =					logging.getLogger(__name__)






@dataclass
class        UpperCAmelCase_       :

 '''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[bool]				=       field(
     default=A				,							metadata={"help": "Whether to log verbose messages or not."}				,							)







def snake_case_    (				lowercase__      ,					lowercase__		):
  logging.basicConfig(
      format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"      ,					datefmt="%m/%d/%Y %H:%M:%S"      ,					handlers=[logging.StreamHandler(sys.stdout		)]      ,					)
  UpperCAmelCase__			:				Any												=       logging.WARNING
  if model_args.verbose_logging:
    UpperCAmelCase__			:				Dict												=       logging.DEBUG
  elif trainer_utils.is_main_process(training_args.local_rank		):
    UpperCAmelCase__			:				Dict												=       logging.INFO
  logger.setLevel(lowercase__		)






@dataclass
class        UpperCAmelCase_       :

 '''simple docstring'''
 lowercase_				:						str				=       field(
     default=A				,							metadata={"help": "The name of the dataset to use (via the datasets library)."}							)
 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"				,							metadata={
         "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
     }				,							)
 lowercase_				:						Optional[str]				=       field(
     default="validation"				,							metadata={
         "help": (
             "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
         )
     }				,							)
 lowercase_				:						Optional[str]				=       field(
     default="text"				,							metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}				,							)
 lowercase_				:						Optional[str]				=       field(
     default="file"				,							metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}				,							)
 lowercase_				:						Optional[bool]				=       field(
     default=A				,							metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}				,							)
 lowercase_				:						Optional[float]				=       field(
     default=A				,							metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}				,							)
 lowercase_				:						Optional[str]				=       field(
     default="librispeech"				,							metadata={
         "help": (
             "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
             " 'buckwalter'."
         )
     }				,							)
 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."}				,							)






@dataclass
class        UpperCAmelCase_       :

 '''simple docstring'''
 lowercase_				:						bool				=       False
 lowercase_				:						Optional[str]				=       None
 lowercase_				:						Optional[str]				=       "|"
 lowercase_				:						Optional[Dict[str, str]]				=       field(default_factory=A							)
 lowercase_				:						Optional[Set[str]]				=       field(default_factory=A							)
 lowercase_				:						Optional[Callable[[str], str]]				=       None







 @classmethod
 def        UpperCamelCase     (				cls		:     List[Any] ,							snake_case__		:     str   ):



   '''simple docstring'''




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







 def        UpperCamelCase     (				self		:     int ,							snake_case__		:     str   ):



   '''simple docstring'''




   if len(self.translation_table   ) > 0:
     UpperCAmelCase__			:				Union[str, Any]												=       text.translate(self.translation_table   )
   if len(self.words_to_remove   ) == 0:
     UpperCAmelCase__			:				Optional[Any]												=       " ".join(text.split()   )  # clean up whitespaces
   else:
     UpperCAmelCase__			:				Optional[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		:     int ,							snake_case__		:     ModelArguments   ):



   '''simple docstring'''




   UpperCAmelCase__			:				Union[str, Any]												=       WavaVecaFeatureExtractor.from_pretrained(
       model_args.model_name_or_path ,							cache_dir=model_args.cache_dir   )
   if self.vocab_file:
     UpperCAmelCase__			:				Optional[Any]												=       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__			:				List[str]												=       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(snake_case__ ,							snake_case__   )






@dataclass
class        UpperCAmelCase_       :

 '''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		:     List[str] ,							snake_case__		:     List[Dict[str, Union[List[int], torch.Tensor]]]   ):



   '''simple docstring'''




   UpperCAmelCase__			:				int												=       [{"input_values": feature["input_values"]} for feature in features]
   UpperCAmelCase__			:				Optional[Any]												=       [{"input_ids": feature["labels"]} for feature in features]

   UpperCAmelCase__			:				str												=       self.processor.pad(
       snake_case__ ,							padding=self.padding ,							max_length=self.max_length ,							pad_to_multiple_of=self.pad_to_multiple_of ,							return_tensors="pt" ,							)
   UpperCAmelCase__			:				Tuple												=       self.processor.pad(
       labels=snake_case__ ,							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__			:				Optional[int]												=       labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1   ) ,							-1_00   )

   UpperCAmelCase__			:				int												=       labels

   return batch






class        UpperCAmelCase_       (						A							):

 '''simple docstring'''







 def        UpperCamelCase     (				self		:     Any ,							snake_case__		:     nn.Module ,							snake_case__		:     Dict[str, Union[torch.Tensor, Any]]   ):



   '''simple docstring'''




   model.train()
   UpperCAmelCase__			:				int												=       self._prepare_inputs(snake_case__   )

   if self.use_amp:
     with autocast():
       UpperCAmelCase__			:				Any												=       self.compute_loss(snake_case__ ,							snake_case__   )
   else:
     UpperCAmelCase__			:				List[Any]												=       self.compute_loss(snake_case__ ,							snake_case__   )

   if self.args.n_gpu > 1:
     if model.module.config.ctc_loss_reduction == "mean":
       UpperCAmelCase__			:				int												=       loss.mean()
     elif model.module.config.ctc_loss_reduction == "sum":
       UpperCAmelCase__			:				int												=       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__			:				List[Any]												=       loss / self.args.gradient_accumulation_steps

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

   return loss.detach()







def snake_case_    (				):
  # 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__			:				List[Any]												=       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)

  UpperCAmelCase__					, UpperCAmelCase__					, UpperCAmelCase__			:				Union[str, Any]												=       parser.parse_args_into_dataclasses()
  configure_logger(lowercase__      ,					lowercase__		)

  UpperCAmelCase__			:				List[Any]												=       Orthography.from_name(data_args.orthography.lower()		)
  UpperCAmelCase__			:				Union[str, Any]												=       orthography.create_processor(lowercase__		)
  UpperCAmelCase__			:				List[Any]												=       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__			:				Any												=       datasets.load_dataset(
      data_args.dataset_name      ,					data_args.dataset_config_name      ,					split=data_args.train_split_name		)
  UpperCAmelCase__			:				Optional[int]												=       datasets.load_dataset(
      data_args.dataset_name      ,					data_args.dataset_config_name      ,					split=data_args.validation_split_name		)

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

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

  UpperCAmelCase__			:				Union[str, Any]												=       train_dataset.map(lowercase__      ,					remove_columns=[data_args.speech_file_column]		)
  UpperCAmelCase__			:				List[Any]												=       val_dataset.map(lowercase__      ,					remove_columns=[data_args.speech_file_column]		)

  if data_args.max_duration_in_seconds is not None:

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

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

  logger.warning(F"""Updated {len(lowercase__		)} 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__			:				int												=       None

  def prepare_dataset(lowercase__		):
    # 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__			:				Optional[int]												=       processor(
        audio=batch["speech"]      ,					text=batch[data_args.target_text_column]      ,					sampling_rate=batch["sampling_rate"][0]		)
    batch.update(lowercase__		)
    return batch

  UpperCAmelCase__			:				Any												=       train_dataset.map(
      lowercase__      ,					batch_size=training_args.per_device_train_batch_size      ,					batched=lowercase__      ,					num_proc=data_args.preprocessing_num_workers      ,					)
  UpperCAmelCase__			:				str												=       val_dataset.map(
      lowercase__      ,					batch_size=training_args.per_device_train_batch_size      ,					batched=lowercase__      ,					num_proc=data_args.preprocessing_num_workers      ,					)

  UpperCAmelCase__			:				int												=       DataCollatorCTCWithPadding(processor=lowercase__      ,					padding=lowercase__		)

  def compute_metrics(lowercase__		):
    UpperCAmelCase__			:				Tuple												=       pred.predictions
    UpperCAmelCase__			:				Optional[Any]												=       np.argmax(lowercase__      ,					axis=-1		)

    UpperCAmelCase__			:				Any												=       processor.tokenizer.pad_token_id

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

    UpperCAmelCase__			:				int												=       wer_metric.compute(predictions=lowercase__      ,					references=lowercase__		)

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  UpperCAmelCase__			:				List[Any]												=       CTCTrainer(
      model=lowercase__      ,					data_collator=lowercase__      ,					args=lowercase__      ,					compute_metrics=lowercase__      ,					train_dataset=lowercase__      ,					eval_dataset=lowercase__      ,					tokenizer=processor.feature_extractor      ,					)

  trainer.train()


if __name__ == "__main__":
      main()





'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE    =					{"""configuration_visual_bert""": ["""VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VisualBertConfig"""]}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE    =					[
          """VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """VisualBertForMultipleChoice""",
          """VisualBertForPreTraining""",
          """VisualBertForQuestionAnswering""",
          """VisualBertForRegionToPhraseAlignment""",
          """VisualBertForVisualReasoning""",
          """VisualBertLayer""",
          """VisualBertModel""",
          """VisualBertPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_visual_bert import VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, VisualBertConfig

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_visual_bert import (
                VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                VisualBertForMultipleChoice,
                VisualBertForPreTraining,
                VisualBertForQuestionAnswering,
                VisualBertForRegionToPhraseAlignment,
                VisualBertForVisualReasoning,
                VisualBertLayer,
                VisualBertModel,
                VisualBertPreTrainedModel,
            )


else:
      import sys

      SCREAMING_SNAKE_CASE    =					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



