

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


lowercase_									=    logging.getLogger(__name__)


@dataclass
class 					A		:







    """simple docstring"""





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




def 		_snake_case(       SCREAMING_SNAKE_CASE__     :      ModelArguments       ,     SCREAMING_SNAKE_CASE__     :      TrainingArguments )				-> Optional[int]:





    '''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(SCREAMING_SNAKE_CASE__ )


@dataclass
class 					A		:







    """simple docstring"""





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




@dataclass
class 					A		:







    """simple docstring"""





    lowerCamelCase						      =				False
    lowerCamelCase						      =				None
    lowerCamelCase						      =				"|"
    lowerCamelCase						      =				field(default_factory=_UpperCAmelCase					)
    lowerCamelCase						      =				field(default_factory=_UpperCAmelCase					)
    lowerCamelCase						      =				None


    @classmethod
    def 		snake_case__	( cls					:			int,lowercase_					:			str						)->       int:





        '''simple docstring'''







        if name == "librispeech":
            return cls()
        if name == "timit":
            return cls(
                do_lower_case=lowercase_,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(lowercase_						).parent.joinpath('vocab/buckwalter.json'						),word_delimiter_token='/',translation_table=str.maketrans(lowercase_						),words_to_remove={'sil'},untransliterator=arabic.buckwalter.untransliterate,)
        raise ValueError(F'Unsupported orthography: \'{name}\'.'						)


    def 		snake_case__	( self					:			List[str],lowercase_					:			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 		snake_case__	( self					:			Optional[int],lowercase_					:			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(lowercase_,lowercase_						)




@dataclass
class 					A		:







    """simple docstring"""





    lowerCamelCase						      =				42
    lowerCamelCase						      =				True
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None


    def __call__( self					:			Any,lowercase_					:			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(
            lowercase_,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=lowercase_,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_0_0						)

        A__        =  labels

        return batch




class 					A		(				_UpperCAmelCase					):







    """simple docstring"""





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





        '''simple docstring'''







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

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

        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(lowercase_						).backward()
        elif self.use_apex:
            with amp.scale_loss(lowercase_,self.optimizer						) as scaled_loss:
                scaled_loss.backward()
        elif self.deepspeed:
            self.deepspeed.backward(lowercase_						)
        else:
            loss.backward()

        return loss.detach()




def 		_snake_case(       )				-> List[Any]:





    '''simple docstring'''






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

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

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

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

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

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

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

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

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

        A__        =  processor.tokenizer.pad_token_id

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

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

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

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




import unittest

from cer import CER


lowercase_									=    CER()


class 					A		(				unittest.TestCase					):







    """simple docstring"""





    def 		snake_case__	( self					:			str						)->       Dict:





        '''simple docstring'''







        A__        =  ['White House']
        A__        =  ['white house']
        # S = 2, D = 0, I = 0, N = 11, CER = 2 / 11
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.1_818_181_818						) < 1E-6						)


    def 		snake_case__	( self					:			str						)->       Dict:





        '''simple docstring'''







        A__        =  ['were wolf']
        A__        =  ['werewolf']
        # S = 0, D = 0, I = 1, N = 9, CER = 1 / 9
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.1_111_111						) < 1E-6						)

        A__        =  ['werewolf']
        A__        =  ['weae     wolf']
        # S = 1, D = 1, I = 0, N = 8, CER = 0.25
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.25						) < 1E-6						)

        # consecutive whitespaces case 1
        A__        =  ['were wolf']
        A__        =  ['were               wolf']
        # S = 0, D = 0, I = 0, N = 9, CER = 0
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.0						) < 1E-6						)

        # consecutive whitespaces case 2
        A__        =  ['were   wolf']
        A__        =  ['were               wolf']
        # S = 0, D = 0, I = 0, N = 9, CER = 0
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.0						) < 1E-6						)


    def 		snake_case__	( self					:			int						)->       str:





        '''simple docstring'''







        A__        =  ['werewolf']
        A__        =  ['weaewolf']
        # S = 1, D = 0, I = 0, N = 8, CER = 0.125
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.125						) < 1E-6						)


    def 		snake_case__	( self					:			Optional[int]						)->       Optional[int]:





        '''simple docstring'''







        A__        =  ['werewolf']
        A__        =  ['wereawolf']
        # S = 0, D = 1, I = 0, N = 8, CER = 0.125
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.125						) < 1E-6						)


    def 		snake_case__	( self					:			List[Any]						)->       Optional[Any]:





        '''simple docstring'''







        A__        =  ['werewolf']
        A__        =  ['wereolf']
        # S = 0, D = 0, I = 1, N = 8, CER = 0.125
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.125						) < 1E-6						)


    def 		snake_case__	( self					:			str						)->       Tuple:





        '''simple docstring'''







        A__        =  ['werewolf']
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertEqual(lowercase_,0.0						)


    def 		snake_case__	( self					:			Optional[int]						)->       Union[str, Any]:





        '''simple docstring'''







        A__        =  ['werewolf', 'I am your father']
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertEqual(lowercase_,0.0						)

        A__        =  ['werewolf', 'I am your father', 'doge']
        A__        =  ['werxwolf', 'I       am your father', 'doge']
        # S = 1, D = 0, I = 0, N = 28, CER = 1 / 28
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.03_571_428						) < 1E-6						)


    def 		snake_case__	( self					:			List[str]						)->       Union[str, Any]:





        '''simple docstring'''







        A__        =  ['My hovercraft', 'is full of eels']
        A__        =  ['My hovercraft is full', ' of eels']
        # S = 0, D = 0, I = 2, N = 28, CER = 2 / 28
        # whitespace at the front of " of eels" will be strip during preporcessing
        # so need to insert 2 whitespaces
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_,concatenate_texts=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.071_428						) < 1E-6						)


    def 		snake_case__	( self					:			Dict						)->       List[str]:





        '''simple docstring'''







        A__        =  ['我能吞下玻璃而不伤身体']
        A__        =  [' 能吞虾玻璃而 不霜身体啦']
        # S = 3, D = 2, I = 0, N = 11, CER = 5 / 11
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.4_545_454_545						) < 1E-6						)

        A__        =  ['我能吞下玻璃', '而不伤身体']
        A__        =  ['我    能 吞 下 玻 璃', '而不伤身体']
        # S = 0, D = 5, I = 0, N = 11, CER = 5 / 11
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertTrue(abs(char_error_rate - 0.454_545_454_545						) < 1E-6						)

        A__        =  ['我能吞下玻璃而不伤身体']
        A__        =  cer.compute(predictions=lowercase_,references=lowercase_						)
        self.assertFalse(lowercase_,0.0						)


    def 		snake_case__	( self					:			Any						)->       List[str]:





        '''simple docstring'''







        A__        =  ['']
        A__        =  ['Hypothesis']
        with self.assertRaises(lowercase_						):
            cer.compute(predictions=lowercase_,references=lowercase_						)


if __name__ == "__main__":
     unittest.main()

