






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


A_     :					Dict							=     logging.getLogger(__name__)



@dataclass
class 						a_ :







      '''simple docstring'''

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






def 			lowerCamelCase_    (		_lowerCamelCase     ,  _lowerCamelCase							):
 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__	:     Dict								=		logging.DEBUG
 elif trainer_utils.is_main_process(training_args.local_rank							):
  lowerCamelCase__	:     str								=		logging.INFO
 logger.setLevel(UpperCAmelCase__							)



@dataclass
class 						a_ :







      '''simple docstring'''

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



@dataclass
class 						a_ :







      '''simple docstring'''

      lowerCamelCase__			:							int					=      False
      lowerCamelCase__			:							Tuple					=      None
      lowerCamelCase__			:							List[Any]					=      '|'
      lowerCamelCase__			:							Any					=      field(default_factory=_a					)
      lowerCamelCase__			:							Optional[int]					=      field(default_factory=_a					)
      lowerCamelCase__			:							Any					=      None




      @classmethod
      def      a__				(cls,	lowerCamelCase_   ):

       '''simple docstring'''



       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      a__				(self,	lowerCamelCase_   ):

       '''simple docstring'''



       if len(self.translation_table   ) > 0:
        lowerCamelCase__	:     Tuple								=		text.translate(self.translation_table   )
       if len(self.words_to_remove   ) == 0:
        lowerCamelCase__	:     List[str]								=		""" """.join(text.split()   )  # clean up whitespaces
       else:
        lowerCamelCase__	:     List[str]								=		""" """.join(w for w in text.split() if w not in self.words_to_remove   )  # and clean up whilespaces
       return text





      def      a__				(self,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, 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__	:     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(_SCREAMING_SNAKE_CASE,	_SCREAMING_SNAKE_CASE   )



@dataclass
class 						a_ :







      '''simple docstring'''

      lowerCamelCase__			:							str					=      42
      lowerCamelCase__			:							Optional[Any]					=      True
      lowerCamelCase__			:							Optional[Any]					=      None
      lowerCamelCase__			:							Tuple					=      None
      lowerCamelCase__			:							Any					=      None
      lowerCamelCase__			:							List[Any]					=      None




      def __call__(self,	lowerCamelCase_   ):

       '''simple docstring'''



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

       lowerCamelCase__	:     Optional[int]								=		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__	:     Tuple								=		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__	:     Any								=		labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1   ),	-1_0_0   )

       lowerCamelCase__	:     Any								=		labels

       return batch



class 						a_ (      _a					):







      '''simple docstring'''

      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       model.train()
       lowerCamelCase__	:     List[Any]								=		self._prepare_inputs(_SCREAMING_SNAKE_CASE   )

       if self.use_amp:
        with autocast():
         lowerCamelCase__	:     List[Any]								=		self.compute_loss(_SCREAMING_SNAKE_CASE,	_SCREAMING_SNAKE_CASE   )
       else:
        lowerCamelCase__	:     Tuple								=		self.compute_loss(_SCREAMING_SNAKE_CASE,	_SCREAMING_SNAKE_CASE   )

       if self.args.n_gpu > 1:
        if model.module.config.ctc_loss_reduction == "mean":
         lowerCamelCase__	:     Optional[int]								=		loss.mean()
        elif model.module.config.ctc_loss_reduction == "sum":
         lowerCamelCase__	:     str								=		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__	:     int								=		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 			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.

 lowerCamelCase__	:     int								=		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)

 lowerCamelCase__	:     Dict								=		parser.parse_args_into_dataclasses()
 configure_logger(UpperCAmelCase__     ,  UpperCAmelCase__							)

 lowerCamelCase__	:     List[Any]								=		Orthography.from_name(data_args.orthography.lower()							)
 lowerCamelCase__	:     Optional[Any]								=		orthography.create_processor(UpperCAmelCase__							)
 lowerCamelCase__	:     Optional[int]								=		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__	:     Optional[int]								=		datasets.load_dataset(
     data_args.dataset_name     ,  data_args.dataset_config_name     ,  split=data_args.train_split_name							)
 lowerCamelCase__	:     List[str]								=		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__	:     Optional[int]								=		processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
 lowerCamelCase__	:     Tuple								=		"""""".join(t for t in processor.tokenizer.get_vocab().keys() if len(UpperCAmelCase__							) == 1							)
 lowerCamelCase__	:     Optional[int]								=		re.compile(  # remove characters not in vocabulary
     rf'''[^\s{re.escape(UpperCAmelCase__							)}]'''     ,  flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0     ,  )
 lowerCamelCase__	:     Dict								=		[]

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

 lowerCamelCase__	:     Union[str, Any]								=		train_dataset.map(UpperCAmelCase__     ,  remove_columns=[data_args.speech_file_column]							)
 lowerCamelCase__	:     Optional[int]								=		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(_lowerCamelCase							):
   return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

  lowerCamelCase__	:     List[str]								=		len(UpperCAmelCase__							)
  lowerCamelCase__	:     str								=		len(UpperCAmelCase__							)
  lowerCamelCase__	:     Optional[Any]								=		train_dataset.filter(UpperCAmelCase__     ,  remove_columns=['duration_in_seconds']							)
  lowerCamelCase__	:     Dict								=		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}\"'''							)
 lowerCamelCase__	:     str								=		None

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

 lowerCamelCase__	:     int								=		train_dataset.map(
     UpperCAmelCase__     ,  batch_size=training_args.per_device_train_batch_size     ,  batched=UpperCAmelCase__     ,  num_proc=data_args.preprocessing_num_workers     ,  )
 lowerCamelCase__	:     Optional[int]								=		val_dataset.map(
     UpperCAmelCase__     ,  batch_size=training_args.per_device_train_batch_size     ,  batched=UpperCAmelCase__     ,  num_proc=data_args.preprocessing_num_workers     ,  )

 lowerCamelCase__	:     Tuple								=		DataCollatorCTCWithPadding(processor=UpperCAmelCase__     ,  padding=UpperCAmelCase__							)

 def compute_metrics(_lowerCamelCase							):
  lowerCamelCase__	:     int								=		pred.predictions
  lowerCamelCase__	:     List[str]								=		np.argmax(UpperCAmelCase__     ,  axis=-1							)

  lowerCamelCase__	:     str								=		processor.tokenizer.pad_token_id

  lowerCamelCase__	:     Tuple								=		processor.batch_decode(UpperCAmelCase__							)
  # we do not want to group tokens when computing the metrics
  lowerCamelCase__	:     Union[str, Any]								=		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__							)}\"'''							)

  lowerCamelCase__	:     List[Any]								=		wer_metric.compute(predictions=UpperCAmelCase__     ,  references=UpperCAmelCase__							)

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

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



'''simple docstring'''


import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
	from .tokenization_xglm import XGLMTokenizer
else:
	__SCREAMING_SNAKE_CASE						=      None


__SCREAMING_SNAKE_CASE						=      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE						=      {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}

__SCREAMING_SNAKE_CASE						=      {
    "vocab_file": {
        "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model",
    },
    "tokenizer_file": {
        "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/tokenizer.json",
    },
}

__SCREAMING_SNAKE_CASE						=      {
    "facebook/xglm-564M": 2048,
}




class     __snake_case			(    _a	):
		a_          =					VOCAB_FILES_NAMES
		a_          =					PRETRAINED_VOCAB_FILES_MAP
		a_          =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		a_          =					["input_ids", "attention_mask"]
		a_          =					XGLMTokenizer




		def __init__(  self					:str			,    _SCREAMING_SNAKE_CASE					:Dict=None			,    _SCREAMING_SNAKE_CASE					:List[str]=None			,    _SCREAMING_SNAKE_CASE					:Dict="<s>"			,    _SCREAMING_SNAKE_CASE					:Dict="</s>"			,    _SCREAMING_SNAKE_CASE					:List[Any]="</s>"			,    _SCREAMING_SNAKE_CASE					:Tuple="<s>"			,    _SCREAMING_SNAKE_CASE					:int="<unk>"			,    _SCREAMING_SNAKE_CASE					:List[str]="<pad>"			,    **_SCREAMING_SNAKE_CASE					:Optional[int]			,    )					->			Optional[int]:






								'''simple docstring'''






								UpperCamelCase_     :	Tuple					     =     7
								UpperCamelCase_     :	int					     =     [F"""<madeupword{i}>""" for i in range(self.num_madeup_words)]

								UpperCamelCase_     :	Optional[Any]					     =     kwargs.get("""additional_special_tokens"""			,    [])
								kwargs["additional_special_tokens"] += [
								    word for word in madeup_words if word not in kwargs["additional_special_tokens"]
								]

								super().__init__(
								    _SCREAMING_SNAKE_CASE			,    tokenizer_file=_SCREAMING_SNAKE_CASE			,    bos_token=_SCREAMING_SNAKE_CASE			,    eos_token=_SCREAMING_SNAKE_CASE			,    sep_token=_SCREAMING_SNAKE_CASE			,    cls_token=_SCREAMING_SNAKE_CASE			,    unk_token=_SCREAMING_SNAKE_CASE			,    pad_token=_SCREAMING_SNAKE_CASE			,    **_SCREAMING_SNAKE_CASE			,    )

								UpperCamelCase_     :	int					     =     vocab_file
								UpperCamelCase_     :	Any					     =     False if not self.vocab_file else True




		def 	_snake_case	(  self					:Dict			,    _SCREAMING_SNAKE_CASE					:List[int]			,    _SCREAMING_SNAKE_CASE					:Optional[List[int]] = None)					->			List[int]:






								'''simple docstring'''






								if token_ids_a is None:
														return [self.sep_token_id] + token_ids_a
								UpperCamelCase_     :	str					     =     [self.sep_token_id]
								return sep + token_ids_a + sep + sep + token_ids_a




		def 	_snake_case	(  self					:int			,    _SCREAMING_SNAKE_CASE					:List[int]			,    _SCREAMING_SNAKE_CASE					:Optional[List[int]] = None)					->			List[int]:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[Any]					     =     [self.sep_token_id]

								if token_ids_a is None:
														return len(sep + token_ids_a) * [0]
								return len(sep + token_ids_a + sep + sep + token_ids_a) * [0]





		def 	_snake_case	(  self					:List[Any]			,    _SCREAMING_SNAKE_CASE					:str			,    _SCREAMING_SNAKE_CASE					:Optional[str] = None)					->			Tuple[str]:






								'''simple docstring'''






								if not self.can_save_slow_tokenizer:
														raise ValueError(
														    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
														    """tokenizer.""")

								if not os.path.isdir(_SCREAMING_SNAKE_CASE):
														logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""")
														return
								UpperCamelCase_     :	Dict					     =     os.path.join(
								    _SCREAMING_SNAKE_CASE			,    (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""])

								if os.path.abspath(self.vocab_file) != os.path.abspath(_SCREAMING_SNAKE_CASE):
														copyfile(self.vocab_file			,    _SCREAMING_SNAKE_CASE)

								return (out_vocab_file,)




