

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									=  True
  from torch.cuda.amp import autocast


_a									=  logging.getLogger(__name__)






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







def _a					(			SCREAMING_SNAKE_CASE						:     ModelArguments       ,   SCREAMING_SNAKE_CASE						:     TrainingArguments						)       ->       str:

 """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						)]       ,   )
 __lowerCAmelCase:  int        = logging.WARNING
 if model_args.verbose_logging:
  __lowerCAmelCase:  str        = logging.DEBUG
 elif trainer_utils.is_main_process(training_args.local_rank						):
  __lowerCAmelCase:  Optional[Any]        = logging.INFO
 logger.setLevel(SCREAMING_SNAKE_CASE						)






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







@dataclass
class 				A_					:
     _lowercase     :	List[str]        =      False
     _lowercase     :	Dict        =      None
     _lowercase     :	str        =      '|'
     _lowercase     :	int        =      field(default_factory=snake_case__   )
     _lowercase     :	Optional[Any]        =      field(default_factory=snake_case__   )
     _lowercase     :	Dict        =      None


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


     def     UpperCAmelCase    (				self     :						Dict     ,    UpperCAmelCase     :						str   )				->      str:
      # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
      if len(self.translation_table   ) > 0:
       __lowerCAmelCase:  Union[str, Any]        = text.translate(self.translation_table   )
      if len(self.words_to_remove   ) == 0:
       __lowerCAmelCase:  int        = ' '.join(text.split()   )  # clean up whitespaces
      else:
       __lowerCAmelCase:  str        = ' '.join(w for w in text.split() if w not in self.words_to_remove   )  # and clean up whilespaces
      return text


     def     UpperCAmelCase    (				self     :						Union[str, Any]     ,    UpperCAmelCase     :						ModelArguments   )				->      WavaVecaProcessor:
      __lowerCAmelCase:  Optional[Any]        = WavaVecaFeatureExtractor.from_pretrained(
          model_args.model_name_or_path     ,    cache_dir=model_args.cache_dir   )
      if self.vocab_file:
       __lowerCAmelCase:  Optional[int]        = 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:  List[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(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE   )







@dataclass
class 				A_					:
     _lowercase     :	Optional[Any]        =      4_2
     _lowercase     :	Tuple        =      True
     _lowercase     :	Dict        =      None
     _lowercase     :	str        =      None
     _lowercase     :	Optional[Any]        =      None
     _lowercase     :	Union[str, Any]        =      None


     def __call__(				self     :						List[str]     ,    UpperCAmelCase     :						List[Dict[str, Union[List[int], torch.Tensor]]]   )				->      Dict[str, torch.Tensor]:
      __lowerCAmelCase:  Dict        = [{'input_values': feature['input_values']} for feature in features]
      __lowerCAmelCase:  Tuple        = [{'input_ids': feature['labels']} for feature in features]

      __lowerCAmelCase:  Union[str, Any]        = self.processor.pad(
          _SCREAMING_SNAKE_CASE     ,    padding=self.padding     ,    max_length=self.max_length     ,    pad_to_multiple_of=self.pad_to_multiple_of     ,    return_tensors='pt'     ,    )
      __lowerCAmelCase:  Optional[Any]        = self.processor.pad(
          labels=_SCREAMING_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
      __lowerCAmelCase:  int        = labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1   )     ,    -1_0_0   )

      __lowerCAmelCase:  str        = labels

      return batch







class 				A_					(						snake_case__   ):


     def     UpperCAmelCase    (				self     :						Union[str, Any]     ,    UpperCAmelCase     :						nn.Module     ,    UpperCAmelCase     :						Dict[str, Union[torch.Tensor, Any]]   )				->      torch.Tensor:
      model.train()
      __lowerCAmelCase:  Optional[Any]        = self._prepare_inputs(_SCREAMING_SNAKE_CASE   )

      if self.use_amp:
       with autocast():
        __lowerCAmelCase:  Tuple        = self.compute_loss(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE   )
      else:
       __lowerCAmelCase:  Any        = self.compute_loss(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE   )

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

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

      return loss.detach()







def _a					(			)       ->       List[Any]:

 """simple docstring"""






 __lowerCAmelCase:  List[Any]        = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)

 __lowerCAmelCase      ,				__lowerCAmelCase      ,				__lowerCAmelCase:  str        = parser.parse_args_into_dataclasses()
 configure_logger(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

 __lowerCAmelCase:  Optional[int]        = Orthography.from_name(data_args.orthography.lower()						)
 __lowerCAmelCase:  Tuple        = orthography.create_processor(SCREAMING_SNAKE_CASE						)
 __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:  Tuple        = datasets.load_dataset(
     data_args.dataset_name       ,   data_args.dataset_config_name       ,   split=data_args.train_split_name						)
 __lowerCAmelCase:  Optional[int]        = datasets.load_dataset(
     data_args.dataset_name       ,   data_args.dataset_config_name       ,   split=data_args.validation_split_name						)

 __lowerCAmelCase:  List[str]        = datasets.load_metric('wer'						)
 __lowerCAmelCase:  Dict        = processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
 __lowerCAmelCase:  List[Any]        = ''.join(t for t in processor.tokenizer.get_vocab().keys() if len(SCREAMING_SNAKE_CASE						) == 1						)
 __lowerCAmelCase:  Dict        = 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       ,   )
 __lowerCAmelCase:  Optional[Any]        = []

 def prepare_example(SCREAMING_SNAKE_CASE						:     int						):  # TODO(elgeish) make use of multiprocessing?
  __lowerCAmelCase      ,				__lowerCAmelCase:  Union[str, Any]        = librosa.load(example[data_args.speech_file_column]       ,   sr=SCREAMING_SNAKE_CASE						)
  if data_args.max_duration_in_seconds is not None:
   __lowerCAmelCase:  Union[str, Any]        = len(example['speech']						) / example['sampling_rate']
  # Normalize and clean up text; order matters!
  __lowerCAmelCase:  Any        = orthography.preprocess_for_training(example[data_args.target_text_column]						)
  __lowerCAmelCase:  Optional[Any]        = 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)						)
   __lowerCAmelCase:  Any        = updated_text
  return example

 __lowerCAmelCase:  List[Any]        = train_dataset.map(SCREAMING_SNAKE_CASE       ,   remove_columns=[data_args.speech_file_column]						)
 __lowerCAmelCase:  Dict        = 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						:     str						):
   return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

  __lowerCAmelCase:  int        = len(SCREAMING_SNAKE_CASE						)
  __lowerCAmelCase:  Any        = len(SCREAMING_SNAKE_CASE						)
  __lowerCAmelCase:  Any        = train_dataset.filter(SCREAMING_SNAKE_CASE       ,   remove_columns=['duration_in_seconds']						)
  __lowerCAmelCase:  Any        = 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}"'''						)
 __lowerCAmelCase:  Union[str, Any]        = None

 def prepare_dataset(SCREAMING_SNAKE_CASE						:     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:  Dict        = processor(
      audio=batch['speech']       ,   text=batch[data_args.target_text_column]       ,   sampling_rate=batch['sampling_rate'][0]						)
  batch.update(SCREAMING_SNAKE_CASE						)
  return batch

 __lowerCAmelCase:  Optional[Any]        = 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       ,   )
 __lowerCAmelCase:  Optional[int]        = 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       ,   )

 __lowerCAmelCase:  List[str]        = DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE       ,   padding=SCREAMING_SNAKE_CASE						)

 def compute_metrics(SCREAMING_SNAKE_CASE						:     Union[str, Any]						):
  __lowerCAmelCase:  Optional[int]        = pred.predictions
  __lowerCAmelCase:  Tuple        = np.argmax(SCREAMING_SNAKE_CASE       ,   axis=-1						)

  __lowerCAmelCase:  List[str]        = processor.tokenizer.pad_token_id

  __lowerCAmelCase:  Optional[Any]        = processor.batch_decode(SCREAMING_SNAKE_CASE						)
  # we do not want to group tokens when computing the metrics
  __lowerCAmelCase:  Dict        = 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						)}"'''						)

  __lowerCAmelCase:  Tuple        = wer_metric.compute(predictions=SCREAMING_SNAKE_CASE       ,   references=SCREAMING_SNAKE_CASE						)

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 __lowerCAmelCase:  Optional[int]        = 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()













def   snake_case		(				UpperCAmelCase						:							set,    UpperCAmelCase						:							set ):
				assert isinstance(UpperCAmelCase,    UpperCAmelCase ), f'The input value of [set_a={set_a}] is not a set'
				assert isinstance(UpperCAmelCase,    UpperCAmelCase ), f'The input value of [set_b={set_b}] is not a set'

				return {a + b for a in set_a for b in set_b}


if __name__ == "__main__":
					from doctest import testmod

					testmod()





