





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


a_				=    logging.getLogger(__name__)






@dataclass
class 	__snake_case      :





 """simple docstring"""


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







def 	__lowercase  (     snake_case_						:						ModelArguments       ,snake_case_						:						TrainingArguments		)     ->List[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		)]       ,)
    __A					:		List[str]						=  logging.WARNING
    if model_args.verbose_logging:
        __A					:		Dict						=  logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank		):
        __A					:		Any						=  logging.INFO
    logger.setLevel(snake_case_		)






@dataclass
class 	__snake_case      :





 """simple docstring"""


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






@dataclass
class 	__snake_case      :





 """simple docstring"""


 _lowerCamelCase				 =  False
 _lowerCamelCase				 =  None
 _lowerCamelCase				 =  "|"
 _lowerCamelCase				 =  field(default_factory=SCREAMING_SNAKE_CASE__  )
 _lowerCamelCase				 =  field(default_factory=SCREAMING_SNAKE_CASE__  )
 _lowerCamelCase				 =  None

 @classmethod
 def       UpperCamelCase__(					cls      ,		__lowerCamelCase						):



     '''simple docstring'''




     if name == "librispeech":
         return cls()
     if name == "timit":
         return cls(
             do_lower_case=__lowerCamelCase      ,		translation_table=str.maketrans({'''-''': ''' '''}						)      ,		)
     if name == "buckwalter":
         __A					:		Dict						=  {
             '''-''': ''' ''',  # sometimes used to represent pauses
             '''^''': '''v''',  # fixing "tha" in arabic_speech_corpus dataset
         }
         return cls(
             vocab_file=pathlib.Path(__lowerCamelCase						).parent.joinpath('''vocab/buckwalter.json'''						)      ,		word_delimiter_token='''/'''      ,		translation_table=str.maketrans(__lowerCamelCase						)      ,		words_to_remove={'''sil'''}      ,		untransliterator=arabic.buckwalter.untransliterate      ,		)
     raise ValueError(F"""Unsupported orthography: '{name}'."""						)

 def       UpperCamelCase__(					self      ,		__lowerCamelCase						):



     '''simple docstring'''




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







 def       UpperCamelCase__(					self      ,		__lowerCamelCase						):



     '''simple docstring'''




     __A					:		Union[str, Any]						=  WavaVecaFeatureExtractor.from_pretrained(
         model_args.model_name_or_path      ,		cache_dir=model_args.cache_dir						)
     if self.vocab_file:
         __A					:		Dict						=  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(__lowerCamelCase      ,		__lowerCamelCase						)






@dataclass
class 	__snake_case      :





 """simple docstring"""


 _lowerCamelCase				 =  42
 _lowerCamelCase				 =  True
 _lowerCamelCase				 =  None
 _lowerCamelCase				 =  None
 _lowerCamelCase				 =  None
 _lowerCamelCase				 =  None

 def __call__(					self      ,		__lowerCamelCase						):



     '''simple docstring'''




     __A					:		str						=  [{'''input_values''': feature['''input_values''']} for feature in features]
     __A					:		Tuple						=  [{'''input_ids''': feature['''labels''']} for feature in features]

     __A					:		List[str]						=  self.processor.pad(
         __lowerCamelCase      ,		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=__lowerCamelCase      ,		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					:		Optional[Any]						=  labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1						)      ,		-100						)

     __A					:		Tuple						=  labels

     return batch






class 	__snake_case      (	SCREAMING_SNAKE_CASE__  ):





 """simple docstring"""


 def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase						):



     '''simple docstring'''




     model.train()
     __A					:		Optional[int]						=  self._prepare_inputs(__lowerCamelCase						)

     if self.use_amp:
         with autocast():
             __A					:		Dict						=  self.compute_loss(__lowerCamelCase      ,		__lowerCamelCase						)
     else:
         __A					:		List[str]						=  self.compute_loss(__lowerCamelCase      ,		__lowerCamelCase						)

     if self.args.n_gpu > 1:
         if model.module.config.ctc_loss_reduction == "mean":
             __A					:		Optional[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					:		str						=  loss / self.args.gradient_accumulation_steps

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

     return loss.detach()







def 	__lowercase  (     )     ->Dict:



    '''simple docstring'''







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

    __A				, __A				, __A					:		List[str]						=  parser.parse_args_into_dataclasses()
    configure_logger(snake_case_       ,snake_case_		)

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

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

    def prepare_example(snake_case_						:						Dict		):  # TODO(elgeish) make use of multiprocessing?
        __A				, __A					:		Tuple						=  librosa.load(example[data_args.speech_file_column]       ,sr=snake_case_		)
        if data_args.max_duration_in_seconds is not None:
            __A					:		Any						=  len(example['''speech''']		) / example['''sampling_rate''']
        # Normalize and clean up text; order matters!
        __A					:		int						=  orthography.preprocess_for_training(example[data_args.target_text_column]		)
        __A					:		Tuple						=  vocabulary_text_cleaner.sub(''''''       ,snake_case_		)
        if updated_text != example[data_args.target_text_column]:
            text_updates.append((example[data_args.target_text_column], updated_text)		)
            __A					:		Dict						=  updated_text
        return example

    __A					:		List[str]						=  train_dataset.map(snake_case_       ,remove_columns=[data_args.speech_file_column]		)
    __A					:		List[str]						=  val_dataset.map(snake_case_       ,remove_columns=[data_args.speech_file_column]		)

    if data_args.max_duration_in_seconds is not None:

        def filter_by_max_duration(snake_case_						:						List[Any]		):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

        __A					:		Union[str, Any]						=  len(snake_case_		)
        __A					:		str						=  len(snake_case_		)
        __A					:		Tuple						=  train_dataset.filter(snake_case_       ,remove_columns=['''duration_in_seconds''']		)
        __A					:		str						=  val_dataset.filter(snake_case_       ,remove_columns=['''duration_in_seconds''']		)
        if len(snake_case_		) > old_train_size:
            logger.warning(
                F"""Filtered out {len(snake_case_		) - old_train_size} train example(s) longer than"""
                F""" {data_args.max_duration_in_seconds} second(s)."""		)
        if len(snake_case_		) > old_val_size:
            logger.warning(
                F"""Filtered out {len(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(snake_case_		)} train and {len(snake_case_		)} validation."""		)

    logger.warning(F"""Updated {len(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}\""""		)
    __A					:		List[str]						=  None

    def prepare_dataset(snake_case_						:						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}."""

        __A					:		str						=  processor(
            audio=batch['''speech''']       ,text=batch[data_args.target_text_column]       ,sampling_rate=batch['''sampling_rate'''][0]		)
        batch.update(snake_case_		)
        return batch

    __A					:		Optional[int]						=  train_dataset.map(
        snake_case_       ,batch_size=training_args.per_device_train_batch_size       ,batched=snake_case_       ,num_proc=data_args.preprocessing_num_workers       ,)
    __A					:		List[Any]						=  val_dataset.map(
        snake_case_       ,batch_size=training_args.per_device_train_batch_size       ,batched=snake_case_       ,num_proc=data_args.preprocessing_num_workers       ,)

    __A					:		int						=  DataCollatorCTCWithPadding(processor=snake_case_       ,padding=snake_case_		)

    def compute_metrics(snake_case_						:						Any		):
        __A					:		Optional[Any]						=  pred.predictions
        __A					:		List[Any]						=  np.argmax(snake_case_       ,axis=-1		)

        __A					:		Dict						=  processor.tokenizer.pad_token_id

        __A					:		int						=  processor.batch_decode(snake_case_		)
        # we do not want to group tokens when computing the metrics
        __A					:		Dict						=  processor.batch_decode(pred.label_ids       ,group_tokens=snake_case_		)
        if logger.isEnabledFor(logging.DEBUG		):
            for reference, predicted in zip(snake_case_       ,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(snake_case_		)}\""""		)
                    logger.debug(F"""predicted (untransliterated): \"{orthography.untransliterator(snake_case_		)}\""""		)

        __A					:		List[Any]						=  wer_metric.compute(predictions=snake_case_       ,references=snake_case_		)

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    __A					:		Tuple						=  CTCTrainer(
        model=snake_case_       ,data_collator=snake_case_       ,args=snake_case_       ,compute_metrics=snake_case_       ,train_dataset=snake_case_       ,eval_dataset=snake_case_       ,tokenizer=processor.feature_extractor       ,)

    trainer.train()


if __name__ == "__main__":
       main()











"""simple docstring"""



import unittest
from functools import partial

import torch

from accelerate import Accelerator, debug_launcher
from accelerate.state import AcceleratorState, GradientState
from accelerate.test_utils import require_cpu, require_huggingface_suite
from accelerate.utils import GradientAccumulationPlugin







def 	__lowercase  (     snake_case_						:						Dict=2       ,snake_case_						:						str=True       ,snake_case_						:						Tuple=False		)     ->Any:



    '''simple docstring'''







    __A					:		List[str]						=  Accelerator(step_scheduler_with_optimizer=snake_case_       ,split_batches=snake_case_		)
    __A					:		Dict						=  torch.nn.Linear(2       ,4		)
    __A					:		Tuple						=  torch.optim.AdamW(model.parameters()       ,lr=1.0		)
    __A					:		int						=  torch.optim.lr_scheduler.OneCycleLR(snake_case_       ,max_lr=0.01       ,steps_per_epoch=2       ,epochs=1		)
    __A				, __A				, __A					:		Optional[int]						=  accelerator.prepare(snake_case_       ,snake_case_       ,snake_case_		)

    # Optimizer has stepped
    scheduler.step()
    if step_scheduler_with_optimizer or (num_processes == 1):
        assert (
            scheduler.scheduler.last_epoch == num_processes
        ), F"""Last Epoch ({scheduler.scheduler.last_epoch}) != Num Processes ({num_processes})"""
    else:
        assert (
            scheduler.scheduler.last_epoch != num_processes
        ), F"""Last Epoch ({scheduler.scheduler.last_epoch}) == Num Processes ({num_processes})"""







def 	__lowercase  (     snake_case_						:						str=2       ,snake_case_						:						Dict=True       ,snake_case_						:						Tuple=False		)     ->List[Any]:



    '''simple docstring'''







    __A					:		int						=  Accelerator(step_scheduler_with_optimizer=snake_case_       ,split_batches=snake_case_		)
    __A					:		Any						=  torch.nn.Linear(2       ,4		)
    __A					:		Optional[int]						=  torch.optim.AdamW(model.parameters()       ,lr=1.0		)
    __A					:		Tuple						=  torch.optim.lr_scheduler.LambdaLR(snake_case_       ,lr_lambda=lambda snake_case_		: 1 - n / 10		)
    __A				, __A				, __A					:		Tuple						=  accelerator.prepare(snake_case_       ,snake_case_       ,snake_case_		)

    # Optimizer has stepped
    __A					:		List[Any]						=  False
    scheduler.step()
    __A					:		List[Any]						=  1 - (num_processes if (step_scheduler_with_optimizer and not split_batches) else 1) / 10
    assert (
        scheduler.get_last_lr()[0] == expected_lr
    ), F"""Wrong lr found at first step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"""

    # Optimizer has not stepped
    __A					:		List[str]						=  True
    scheduler.step()
    if not step_scheduler_with_optimizer:
        __A					:		List[Any]						=  1 - 2 / 10
    assert (
        scheduler.get_last_lr()[0] == expected_lr
    ), F"""Wrong lr found at second step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"""







def 	__lowercase  (     snake_case_						:						int = 2		)     ->str:



    '''simple docstring'''







    from transformers import get_linear_schedule_with_warmup

    __A					:		Any						=  [1, 2, 4]
    for num_steps in steps:
        __A					:		Tuple						=  GradientAccumulationPlugin(num_steps=snake_case_       ,adjust_scheduler=num_steps > 1		)
        __A					:		Optional[Any]						=  Accelerator(gradient_accumulation_plugin=snake_case_		)
        __A					:		Optional[int]						=  torch.nn.Linear(2       ,4		)
        __A					:		Any						=  torch.optim.AdamW(model.parameters()       ,lr=10.0		)
        __A					:		Dict						=  get_linear_schedule_with_warmup(optimizer=snake_case_       ,num_warmup_steps=0       ,num_training_steps=20		)

        __A				, __A				, __A					:		Union[str, Any]						=  accelerator.prepare(snake_case_       ,snake_case_       ,snake_case_		)

        for i in range(10 * num_steps		):
            with accelerator.accumulate(snake_case_		):
                optimizer.step()
                scheduler.step()

            if i == (10 * num_steps - 2):
                assert (
                    scheduler.get_last_lr()[0] != 0
                ), F"""Wrong lr found at second-to-last step, expected non-zero, got {scheduler.get_last_lr()[0]}. num_steps: {num_steps}"""
        assert (
            scheduler.get_last_lr()[0] == 0
        ), F"""Wrong lr found at last step, expected 0, got {scheduler.get_last_lr()[0]}"""
        GradientState._reset_state()






@require_cpu
class 	__snake_case      (	unittest.TestCase  ):





 """simple docstring"""


 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1						)      ,		num_processes=1						)
     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1      ,		split_batches=__lowerCamelCase						)      ,		num_processes=1						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1						)      ,		num_processes=1						)
     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1      ,		split_batches=__lowerCamelCase						)      ,		num_processes=1						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1      ,		step_scheduler_with_optimizer=__lowerCamelCase						)      ,		num_processes=1						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1      ,		step_scheduler_with_optimizer=__lowerCamelCase						)      ,		num_processes=1						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     AcceleratorState._reset_state(__lowerCamelCase						)
     debug_launcher(__lowerCamelCase						)
     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1      ,		split_batches=__lowerCamelCase						)      ,		num_processes=1						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     AcceleratorState._reset_state(__lowerCamelCase						)
     debug_launcher(__lowerCamelCase						)
     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1      ,		split_batches=__lowerCamelCase						)      ,		num_processes=1						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     AcceleratorState._reset_state(__lowerCamelCase						)
     debug_launcher(partial(__lowerCamelCase      ,		step_scheduler_with_optimizer=__lowerCamelCase						)						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     AcceleratorState._reset_state(__lowerCamelCase						)
     debug_launcher(partial(__lowerCamelCase      ,		step_scheduler_with_optimizer=__lowerCamelCase						)						)







 @require_huggingface_suite
 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     AcceleratorState._reset_state(__lowerCamelCase						)
     debug_launcher(partial(__lowerCamelCase      ,		num_processes=1						)						)
     debug_launcher(__lowerCamelCase						)




