

'''simple docstring'''




# Lint as: python3

import hashlib
from typing import Union


def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   Union[str, int, bytes]						):
  if isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						):
    # Data already in bytes, returns as it as
    return hash_data
  elif isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						):
    # We keep the data as it as for it ot be later encoded to UTF-8
    # However replace `\\` with `/` for Windows compatibility
    UpperCAmelCase													=	hash_data.replace('\\'       ,   '/'						)
  elif isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						):
    UpperCAmelCase													=	str(SCREAMING_SNAKE_CASE						)
  else:
    # If data is not of the required type, raise error
    raise InvalidKeyError(SCREAMING_SNAKE_CASE						)

  return hash_data.encode('utf-8'						)



class        lowercase_	(		a ):

  '''simple docstring'''





  def __init__(     self   , a_     )							->				str:


    """simple docstring"""
    UpperCAmelCase													=	'\nFAILURE TO GENERATE DATASET: Invalid key type detected'
    UpperCAmelCase													=	F'''\nFound Key {hash_data} of type {type(a_     )}'''
    UpperCAmelCase													=	'\nKeys should be either str, int or bytes type'
    super().__init__(F'''{self.prefix}{self.err_msg}{self.suffix}'''     )




class        lowercase_	(		a ):

  '''simple docstring'''





  def __init__(     self   , a_   , a_   , a_=""     )							->				Tuple:


    """simple docstring"""
    UpperCAmelCase													=	key
    UpperCAmelCase													=	duplicate_key_indices
    UpperCAmelCase													=	fix_msg
    UpperCAmelCase													=	'Found multiple examples generated with the same key'
    if len(a_     ) <= 2_0:
      UpperCAmelCase													=	F'''\nThe examples at index {', '.join(a_     )} have the key {key}'''
    else:
      UpperCAmelCase													=	F'''\nThe examples at index {', '.join(duplicate_key_indices[:2_0]     )}... ({len(a_     ) - 2_0} more) have the key {key}'''
    UpperCAmelCase													=	'\n' + fix_msg if fix_msg else ''
    super().__init__(F'''{self.prefix}{self.err_msg}{self.suffix}'''     )




class        lowercase_	:

  '''simple docstring'''





  def __init__(     self   , a_     )							->				Optional[Any]:


    """simple docstring"""
    UpperCAmelCase													=	hashlib.mda(_as_bytes(a_     )     )





  def 						snake_case_			(     self   , a_     )							->				int:


    """simple docstring"""
    UpperCAmelCase													=	self._split_mda.copy()
    UpperCAmelCase													=	_as_bytes(a_     )
    mda.update(a_     )
    # Convert to integer with hexadecimal conversion
    return int(mda.hexdigest()   , 1_6     )





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


_a				: Optional[int] 							=						logging.getLogger(__name__)



@dataclass
class        lowercase_	:

  '''simple docstring'''





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




def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   ModelArguments       ,   SCREAMING_SNAKE_CASE      :   TrainingArguments						):
  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(SCREAMING_SNAKE_CASE						)



@dataclass
class        lowercase_	:

  '''simple docstring'''





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




@dataclass
class        lowercase_	:

  '''simple docstring'''





  __lowerCAmelCase					: bool      =   False
  __lowerCAmelCase					: Optional[str]      =   None
  __lowerCAmelCase					: Optional[str]      =   "|"
  __lowerCAmelCase					: Optional[Dict[str, str]]      =   field(default_factory=a )
  __lowerCAmelCase					: Optional[Set[str]]      =   field(default_factory=a )
  __lowerCAmelCase					: Optional[Callable[[str], str]]      =   None
  @classmethod
  def 						snake_case_			(     cls   , a_     )							->				Optional[Any]:


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


    """simple docstring"""
    # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
    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 						snake_case_			(     self   , a_     )							->				WavaVecaProcessor:


    """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        lowercase_	:

  '''simple docstring'''





  __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   , a_     )							->				Dict[str, torch.Tensor]:


    """simple docstring"""
    # split inputs and labels since they have to be of different lenghts and need
    # different padding methods
    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     )   , -1_0_0     )

    UpperCAmelCase													=	labels

    return batch




class        lowercase_	(		a ):

  '''simple docstring'''





  def 						snake_case_			(     self   , a_   , a_     )							->				torch.Tensor:


    """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       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.

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

  UpperCAmelCase							,      UpperCAmelCase							,      UpperCAmelCase													=	parser.parse_args_into_dataclasses()
  configure_logger(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

  UpperCAmelCase													=	Orthography.from_name(data_args.orthography.lower()						)
  UpperCAmelCase													=	orthography.create_processor(SCREAMING_SNAKE_CASE						)
  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(SCREAMING_SNAKE_CASE						) == 1						)
  UpperCAmelCase													=	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       ,   )
  UpperCAmelCase													=	[]

  def prepare_example(SCREAMING_SNAKE_CASE      :   Dict						):  # TODO(elgeish) make use of multiprocessing?
    UpperCAmelCase							,      UpperCAmelCase													=	librosa.load(example[data_args.speech_file_column]       ,   sr=SCREAMING_SNAKE_CASE						)
    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(''       ,   SCREAMING_SNAKE_CASE						)
    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(SCREAMING_SNAKE_CASE       ,   remove_columns=[data_args.speech_file_column]						)
  UpperCAmelCase													=	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      :   int						):
      return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

    UpperCAmelCase													=	len(SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	len(SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	train_dataset.filter(SCREAMING_SNAKE_CASE       ,   remove_columns=['duration_in_seconds']						)
    UpperCAmelCase													=	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}"'''						)
  UpperCAmelCase													=	None

  def prepare_dataset(SCREAMING_SNAKE_CASE      :   Optional[Any]						):
    # 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(SCREAMING_SNAKE_CASE						)
    return batch

  UpperCAmelCase													=	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       ,   )
  UpperCAmelCase													=	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       ,   )

  UpperCAmelCase													=	DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE       ,   padding=SCREAMING_SNAKE_CASE						)

  def compute_metrics(SCREAMING_SNAKE_CASE      :   Optional[int]						):
    UpperCAmelCase													=	pred.predictions
    UpperCAmelCase													=	np.argmax(SCREAMING_SNAKE_CASE       ,   axis=-1						)

    UpperCAmelCase													=	processor.tokenizer.pad_token_id

    UpperCAmelCase													=	processor.batch_decode(SCREAMING_SNAKE_CASE						)
    # we do not want to group tokens when computing the metrics
    UpperCAmelCase													=	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						)}"'''						)

    UpperCAmelCase													=	wer_metric.compute(predictions=SCREAMING_SNAKE_CASE       ,   references=SCREAMING_SNAKE_CASE						)

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  UpperCAmelCase													=	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()


