




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


lowerCAmelCase_    	=							logging.getLogger(__name__)

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







def 	_A			(   UpperCAmelCase			,UpperCAmelCase	):






   '''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	)]			,)
   A__         =    logging.WARNING
   if model_args.verbose_logging:
      A__         =    logging.DEBUG
   elif trainer_utils.is_main_process(training_args.local_rank	):
      A__         =    logging.INFO
   logger.setLevel(UpperCAmelCase	)

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




@dataclass
class   _snake_case:
 __snake_case:       bool									=				False
 __snake_case:       Optional[str]									=				None
 __snake_case:       Optional[str]									=				"|"
 __snake_case:       Optional[Dict[str, str]]									=				field(default_factory=UpperCAmelCase			)
 __snake_case:       Optional[Set[str]]									=				field(default_factory=UpperCAmelCase			)
 __snake_case:       Optional[Callable[[str], str]]									=				None






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[Any]						,		a					:     str						)					->      List[Any]:






    """simple docstring"""


    if name == "librispeech":
       return cls()
    if name == "timit":
       return cls(
           do_lower_case=a						,		translation_table=str.maketrans({'-': ' '}						)						,		)
    if name == "buckwalter":
       A__         =    {
           '-': ' ',  # 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 	_UpperCamelCase   (self					:     Optional[int]						,		a					:     str						)					->      str:






    """simple docstring"""


    if len(self.translation_table						) > 0:
       A__         =    text.translate(self.translation_table						)
    if len(self.words_to_remove						) == 0:
       A__         =    ' '.join(text.split()						)  # clean up whitespaces
    else:
       A__         =    ' '.join(w for w in text.split() if w not in self.words_to_remove						)  # and clean up whilespaces
    return text






 def 	_UpperCamelCase   (self					:     Any						,		a					:     ModelArguments						)					->      WavaVecaProcessor:






    """simple docstring"""


    A__         =    WavaVecaFeatureExtractor.from_pretrained(
        model_args.model_name_or_path						,		cache_dir=model_args.cache_dir						)
    if self.vocab_file:
       A__         =    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:
       A__         =    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   _snake_case:
 __snake_case:       WavaVecaProcessor
 __snake_case:       Union[bool, str]									=				True
 __snake_case:       Optional[int]									=				None
 __snake_case:       Optional[int]									=				None
 __snake_case:       Optional[int]									=				None
 __snake_case:       Optional[int]									=				None






 def __call__(self					:     List[str]						,		a					:     List[Dict[str, Union[List[int], torch.Tensor]]]						)					->      Dict[str, torch.Tensor]:






    """simple docstring"""


    A__         =    [{'input_values': feature['input_values']} for feature in features]
    A__         =    [{'input_ids': feature['labels']} for feature in features]

    A__         =    self.processor.pad(
        a						,		padding=self.padding						,		max_length=self.max_length						,		pad_to_multiple_of=self.pad_to_multiple_of						,		return_tensors='pt'						,		)
    A__         =    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
    A__         =    labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1						)						,		-1_00						)

    A__         =    labels

    return batch




class   _snake_case( UpperCAmelCase			):






 def 	_UpperCamelCase   (self					:     Optional[int]						,		a					:     nn.Module						,		a					:     Dict[str, Union[torch.Tensor, Any]]						)					->      torch.Tensor:






    """simple docstring"""


    model.train()
    A__         =    self._prepare_inputs(a						)

    if self.use_amp:
       with autocast():
          A__         =    self.compute_loss(a						,		a						)
    else:
       A__         =    self.compute_loss(a						,		a						)

    if self.args.n_gpu > 1:
       if model.module.config.ctc_loss_reduction == "mean":
          A__         =    loss.mean()
       elif model.module.config.ctc_loss_reduction == "sum":
          A__         =    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:
       A__         =    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 	_A			(   ):






   '''simple docstring'''







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

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

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

   A__         =    datasets.load_dataset(
       data_args.dataset_name			,data_args.dataset_config_name			,split=data_args.train_split_name	)
   A__         =    datasets.load_dataset(
       data_args.dataset_name			,data_args.dataset_config_name			,split=data_args.validation_split_name	)

   A__         =    datasets.load_metric('wer'	)
   A__         =    processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
   A__         =    ''.join(t for t in processor.tokenizer.get_vocab().keys() if len(UpperCAmelCase	) == 1	)
   A__         =    re.compile(  # remove characters not in vocabulary
       rF"""[^\s{re.escape(UpperCAmelCase	)}]"""			,flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0			,)
   A__         =    []

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

   A__         =    train_dataset.map(UpperCAmelCase			,remove_columns=[data_args.speech_file_column]	)
   A__         =    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(UpperCAmelCase	):
         return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

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

   def prepare_dataset(UpperCAmelCase	):
      # 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}."""

      A__         =    processor(
          audio=batch['speech']			,text=batch[data_args.target_text_column]			,sampling_rate=batch['sampling_rate'][0]	)
      batch.update(UpperCAmelCase	)
      return batch

   A__         =    train_dataset.map(
       UpperCAmelCase			,batch_size=training_args.per_device_train_batch_size			,batched=UpperCAmelCase			,num_proc=data_args.preprocessing_num_workers			,)
   A__         =    val_dataset.map(
       UpperCAmelCase			,batch_size=training_args.per_device_train_batch_size			,batched=UpperCAmelCase			,num_proc=data_args.preprocessing_num_workers			,)

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

   def compute_metrics(UpperCAmelCase	):
      A__         =    pred.predictions
      A__         =    np.argmax(UpperCAmelCase			,axis=-1	)

      A__         =    processor.tokenizer.pad_token_id

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

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

      return {"wer": wer}

   if model_args.freeze_feature_extractor:
      model.freeze_feature_extractor()

   A__         =    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'''







from __future__ import annotations

from enum import Enum, unique
from typing import TypeVar

# Create a generic variable that can be 'Enum', or any subclass.
lowerCAmelCase_    	=							TypeVar('''T''', bound='''Enum''')

@unique
class   _snake_case( UpperCAmelCase			):
 __snake_case:       List[Any]									=				80
 __snake_case:       Optional[int]									=				70
 __snake_case:       Optional[int]									=				60
 __snake_case:       int									=				50
 __snake_case:       Dict									=				40
 __snake_case:       Dict									=				30
 __snake_case:       str									=				20
 __snake_case:       Optional[int]									=				10




@unique
class   _snake_case( UpperCAmelCase			):
 __snake_case:       List[Any]									=				24
 __snake_case:       Union[str, Any]									=				21
 __snake_case:       Dict									=				18
 __snake_case:       List[str]									=				15
 __snake_case:       Union[str, Any]									=				12
 __snake_case:       Tuple									=				9
 __snake_case:       int									=				6
 __snake_case:       Tuple									=				3
 __snake_case:       List[Any]									=				2
 __snake_case:       int									=				1
 __snake_case:       List[str]									=				-1
 __snake_case:       Union[str, Any]									=				-2
 __snake_case:       List[str]									=				-3
 __snake_case:       Any									=				-6
 __snake_case:       Tuple									=				-9
 __snake_case:       List[str]									=				-12
 __snake_case:       Dict									=				-15
 __snake_case:       Optional[int]									=				-18
 __snake_case:       str									=				-21
 __snake_case:       Any									=				-24






 @classmethod
 def 	_UpperCamelCase   (cls					:     type[T]						)					->      dict:






    """simple docstring"""


    return {unit.name: unit.value for unit in cls if unit.value > 0}






 @classmethod
 def 	_UpperCamelCase   (cls					:     type[T]						)					->      dict:






    """simple docstring"""


    return {unit.name: unit.value for unit in cls if unit.value < 0}







def 	_A			(   UpperCAmelCase	):






   '''simple docstring'''







   A__         =    SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
   for name_prefix, value_prefix in prefixes.items():
      A__         =    value / (10**value_prefix)
      if numerical_part > 1:
         return F"""{numerical_part!s} {name_prefix}"""
   return str(UpperCAmelCase	)







def 	_A			(   UpperCAmelCase	):






   '''simple docstring'''







   for prefix in BinaryUnit:
      A__         =    value / (2**prefix.value)
      if numerical_part > 1:
         return F"""{numerical_part!s} {prefix.name}"""
   return str(UpperCAmelCase	)


if __name__ == "__main__":
    import doctest

    doctest.testmod()


