






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


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







def 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )       ->						Dict:
    """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       )]			,						)
    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  __lowerCamelCase     :
   a   :					str			    =field(
       default=_a				,						metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}	)
   a   :					Optional[str]			    =field(
       default=_a				,						metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}	)
   a   :					Optional[str]			    =field(
       default="""train"""				,						metadata={
           """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
       }				,						)
   a   :					Optional[str]			    =field(
       default="""validation"""				,						metadata={
           """help""": (
               """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"""
           )
       }				,						)
   a   :					Optional[str]			    =field(
       default="""text"""				,						metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}				,						)
   a   :					Optional[str]			    =field(
       default="""file"""				,						metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}				,						)
   a   :					Optional[bool]			    =field(
       default=_a				,						metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}				,						)
   a   :					Optional[float]			    =field(
       default=_a				,						metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}				,						)
   a   :					Optional[str]			    =field(
       default="""librispeech"""				,						metadata={
           """help""": (
               """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
               """ 'buckwalter'."""
           )
       }				,						)
   a   :					bool			    =field(
       default=_a				,						metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}	)
   a   :					Optional[int]			    =field(
       default=_a				,						metadata={"""help""": """The number of processes to use for the preprocessing."""}				,						)







@dataclass
class  __lowerCamelCase     :
   a   :					bool			    =False
   a   :					Optional[str]			    =None
   a   :					Optional[str]			    ="|"
   a   :					Optional[Dict[str, str]]			    =field(default_factory=_a	)
   a   :					Optional[Set[str]]			    =field(default_factory=_a	)
   a   :					Optional[Callable[[str], str]]			    =None

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

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_   )		->							str:
       # 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     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_   )		->							WavaVecaProcessor:
       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(snake_case_			,					snake_case_   )







@dataclass
class  __lowerCamelCase     :
   a   :					WavaVecaProcessor
   a   :					Union[bool, str]			    =True
   a   :					Optional[int]			    =None
   a   :					Optional[int]			    =None
   a   :					Optional[int]			    =None
   a   :					Optional[int]			    =None

   def __call__(       self			,					snake_case_   )		->							Dict[str, torch.Tensor]:
       # 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(
           snake_case_			,					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=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
       UpperCamelCase__								=     labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1   )			,					-100   )

       UpperCamelCase__								=     labels

       return batch







class  __lowerCamelCase     (	_a	):

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_			,					snake_case_   )		->							torch.Tensor:
       model.train()
       UpperCamelCase__								=     self._prepare_inputs(snake_case_   )

       if self.use_amp:
           with autocast():
               UpperCamelCase__								=     self.compute_loss(snake_case_			,					snake_case_   )
       else:
           UpperCamelCase__								=     self.compute_loss(snake_case_			,					snake_case_   )

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

       return loss.detach()







def 	lowerCAmelCase_(			)       ->						Optional[Any]:
    """simple docstring"""

    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       ):  # 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       ):
            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       ):
        # 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       ):
        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()












"""simple docstring"""





import torch

from transformers import PreTrainedModel

from .custom_configuration import CustomConfig, NoSuperInitConfig
class  __lowerCamelCase     (	_a	):
   a   :					List[Any]			    =CustomConfig

   def __init__(       self			,					snake_case_   )		->							str:
       super().__init__(snake_case_   )
       UpperCamelCase__								=     torch.nn.Linear(config.hidden_size			,					config.hidden_size   )

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_   )		->							Optional[int]:
       return self.linear(snake_case_   )







   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_   )		->							Union[str, Any]:
       pass







class  __lowerCamelCase     (	_a	):
   a   :					Optional[int]			    =NoSuperInitConfig

   def __init__(       self			,					snake_case_   )		->							Optional[int]:
       super().__init__(snake_case_   )
       UpperCamelCase__								=     torch.nn.Linear(config.attribute			,					config.attribute   )

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_   )		->							int:
       return self.linear(snake_case_   )







   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_   )		->							Union[str, Any]:
       pass




