





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


snake_case_     			=						logging.getLogger(__name__)


@dataclass
class 	_lowercase    :
   _UpperCamelCase									= field(
       metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}					)
   _UpperCamelCase									= field(
       default=_UpperCAmelCase		,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,       )
   _UpperCamelCase									= field(
       default=_UpperCAmelCase		,       metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}					)
   _UpperCamelCase									= field(
       default=_UpperCAmelCase		,       metadata={"""help""": """Whether to log verbose messages or not."""}		,       )







def 				_lowerCamelCase(	UpperCamelCase__     :			ModelArguments     ,							UpperCamelCase__     :			TrainingArguments		)		->	Dict:
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''     ,							datefmt='''%m/%d/%Y %H:%M:%S'''     ,							handlers=[logging.StreamHandler(sys.stdout		)]     ,							)
    A							:							Optional[Any]				=    logging.WARNING
    if model_args.verbose_logging:
        A							:							Tuple				=    logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank		):
        A							:							List[Any]				=    logging.INFO
    logger.setLevel(UpperCamelCase__		)


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







@dataclass
class 	_lowercase    :
   _UpperCamelCase									= False
   _UpperCamelCase									= None
   _UpperCamelCase									= "|"
   _UpperCamelCase									= field(default_factory=_UpperCAmelCase					)
   _UpperCamelCase									= field(default_factory=_UpperCAmelCase					)
   _UpperCamelCase									= None


   @classmethod
   def        snake_case					(			cls     , _UpperCAmelCase       ):
       if name == "librispeech":
           return cls()
       if name == "timit":
           return cls(
               do_lower_case=SCREAMING_SNAKE_CASE_     , translation_table=str.maketrans({'''-''': ''' '''}       )     , )
       if name == "buckwalter":
           A							:							List[Any]				=    {
               """-""": """ """,  # 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        snake_case					(			self     , _UpperCAmelCase       ):
       # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
       if len(self.translation_table       ) > 0:
           A							:							str				=    text.translate(self.translation_table       )
       if len(self.words_to_remove       ) == 0:
           A							:							List[str]				=    """ """.join(text.split()       )  # clean up whitespaces
       else:
           A							:							Dict				=    """ """.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     , _UpperCAmelCase       ):
       A							:							str				=    WavaVecaFeatureExtractor.from_pretrained(
           model_args.model_name_or_path     , cache_dir=model_args.cache_dir       )
       if self.vocab_file:
           A							:							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:
           A							:							Union[str, 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 	_lowercase    :
   _UpperCamelCase									= 42
   _UpperCamelCase									= True
   _UpperCamelCase									= None
   _UpperCamelCase									= None
   _UpperCamelCase									= None
   _UpperCamelCase									= None


   def __call__(			self     , _UpperCAmelCase       ):
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       A							:							Optional[int]				=    [{"""input_values""": feature["""input_values"""]} for feature in features]
       A							:							Tuple				=    [{"""input_ids""": feature["""labels"""]} for feature in features]

       A							:							Tuple				=    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'''     , )
       A							:							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
       A							:							List[str]				=    labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1       )     , -100       )

       A							:							Any				=    labels

       return batch







class 	_lowercase    (				_UpperCAmelCase					):


   def        snake_case					(			self     , _UpperCAmelCase     , _UpperCAmelCase       ):
       model.train()
       A							:							Tuple				=    self._prepare_inputs(SCREAMING_SNAKE_CASE_       )

       if self.use_amp:
           with autocast():
               A							:							int				=    self.compute_loss(SCREAMING_SNAKE_CASE_     , SCREAMING_SNAKE_CASE_       )
       else:
           A							:							Optional[int]				=    self.compute_loss(SCREAMING_SNAKE_CASE_     , SCREAMING_SNAKE_CASE_       )

       if self.args.n_gpu > 1:
           if model.module.config.ctc_loss_reduction == "mean":
               A							:							List[Any]				=    loss.mean()
           elif model.module.config.ctc_loss_reduction == "sum":
               A							:							Tuple				=    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							:							Union[str, Any]				=    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(	)		->	Union[str, Any]:
    # 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.

    A							:							Dict				=    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)

    A							:							int				=    parser.parse_args_into_dataclasses()
    configure_logger(UpperCamelCase__     ,							UpperCamelCase__		)

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

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

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

    A							:							List[Any]				=    train_dataset.map(UpperCamelCase__     ,							remove_columns=[data_args.speech_file_column]		)
    A							:							List[Any]				=    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__     :			Optional[Any]		):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

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

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

    A							:							Tuple				=    train_dataset.map(
        UpperCamelCase__     ,							batch_size=training_args.per_device_train_batch_size     ,							batched=UpperCamelCase__     ,							num_proc=data_args.preprocessing_num_workers     ,							)
    A							:							Tuple				=    val_dataset.map(
        UpperCamelCase__     ,							batch_size=training_args.per_device_train_batch_size     ,							batched=UpperCamelCase__     ,							num_proc=data_args.preprocessing_num_workers     ,							)

    A							:							Union[str, Any]				=    DataCollatorCTCWithPadding(processor=UpperCamelCase__     ,							padding=UpperCamelCase__		)

    def compute_metrics(UpperCamelCase__     :			Union[str, Any]		):
        A							:							List[str]				=    pred.predictions
        A							:							List[Any]				=    np.argmax(UpperCamelCase__     ,							axis=-1		)

        A							:							int				=    processor.tokenizer.pad_token_id

        A							:							List[str]				=    processor.batch_decode(UpperCamelCase__		)
        # we do not want to group tokens when computing the metrics
        A							:							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__		)}"'''		)

        A							:							Optional[int]				=    wer_metric.compute(predictions=UpperCamelCase__     ,							references=UpperCamelCase__		)

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    A							:							List[str]				=    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()




_A		:					Optional[int]          =							{
    '''+''': lambda x, y: x + y,
    '''-''': lambda x, y: x - y,
    '''*''': lambda x, y: x * y,
    '''/''': lambda x, y: x / y,
}



def      __lowerCAmelCase    (				snake_case						:     Union[str, Any]			)							->				str:
   return c.isdigit()



def      __lowerCAmelCase    (				snake_case						:     Optional[Any]			)							->				str:
   __lowerCamelCase:					List[str]	 =						[]

   # iterate over the string in reverse order
   for c in expression.split()[::-1]:
      # push operand to stack
      if is_operand(snake_case			):
         stack.append(int(snake_case			)			)

      else:
         # pop values from stack can calculate the result
         # push the result onto the stack again
         __lowerCamelCase:					Any	 =						stack.pop()
         __lowerCamelCase:					int	 =						stack.pop()
         stack.append(calc[c](snake_case    ,   snake_case			)			)

   return stack.pop()


# Driver code
if __name__ == "__main__":
   _A		:					int          =							'''+ 9 * 2 6'''
   print(evaluate(test_expression))

   _A		:					str          =							'''/ * 10 2 + 4 1 '''
   print(evaluate(test_expression))


