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 				a_ :






 '''simple docstring'''






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






def       __lowerCamelCase		(						lowerCAmelCase__	,  lowerCAmelCase__	):
       logging.basicConfig(
           format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'	,  datefmt='%m/%d/%Y %H:%M:%S'	,  handlers=[logging.StreamHandler(sys.stdout	)]	,  )
       lowerCAmelCase__     	=					logging.WARNING
       if model_args.verbose_logging:
              lowerCAmelCase__     	=					logging.DEBUG
       elif trainer_utils.is_main_process(training_args.local_rank	):
              lowerCAmelCase__     	=					logging.INFO
       logger.setLevel(lowerCAmelCase__	)
@dataclass
class 				a_ :






 '''simple docstring'''






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






@dataclass
class 				a_ :






 '''simple docstring'''






 UpperCAmelCase_	 =					False
 UpperCAmelCase_	 =					None
 UpperCAmelCase_	 =					"|"
 UpperCAmelCase_	 =					field(default_factory=SCREAMING_SNAKE_CASE						)
 UpperCAmelCase_	 =					field(default_factory=SCREAMING_SNAKE_CASE						)
 UpperCAmelCase_	 =					None




 @classmethod
 def 		__snake_case						(			cls					:  List[str]			,    lowercase__					:  str):







        '''simple docstring'''



        if name == "librispeech":
               return cls()
        if name == "timit":
               return cls(
                   do_lower_case=lowercase__			,    translation_table=str.maketrans({'-': ' '})			,    )
        if name == "buckwalter":
               lowerCAmelCase__     	=					{
                   '-': ' ',  # 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					:  str			,    lowercase__					:  str):







        '''simple docstring'''



        if len(self.translation_table) > 0:
               lowerCAmelCase__     	=					text.translate(self.translation_table)
        if len(self.words_to_remove) == 0:
               lowerCAmelCase__     	=					' '.join(text.split())  # clean up whitespaces
        else:
               lowerCAmelCase__     	=					' '.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					:  Union[str, Any]			,    lowercase__					:  ModelArguments):







        '''simple docstring'''



        lowerCAmelCase__     	=					WavaVecaFeatureExtractor.from_pretrained(
            model_args.model_name_or_path			,    cache_dir=model_args.cache_dir)
        if self.vocab_file:
               lowerCAmelCase__     	=					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:
               lowerCAmelCase__     	=					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'''






 UpperCAmelCase_	 =					42
 UpperCAmelCase_	 =					True
 UpperCAmelCase_	 =					None
 UpperCAmelCase_	 =					None
 UpperCAmelCase_	 =					None
 UpperCAmelCase_	 =					None




 def __call__(			self					:  Optional[int]			,    lowercase__					:  List[Dict[str, Union[List[int], torch.Tensor]]]):







        '''simple docstring'''



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

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

        lowerCAmelCase__     	=					labels

        return batch






class 				a_ (						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 def 		__snake_case						(			self					:  Any			,    lowercase__					:  nn.Module			,    lowercase__					:  Dict[str, Union[torch.Tensor, Any]]):







        '''simple docstring'''



        model.train()
        lowerCAmelCase__     	=					self._prepare_inputs(lowercase__)

        if self.use_amp:
               with autocast():
                      lowerCAmelCase__     	=					self.compute_loss(lowercase__			,    lowercase__)
        else:
               lowerCAmelCase__     	=					self.compute_loss(lowercase__			,    lowercase__)

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

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

       lowerCAmelCase__	,					lowerCAmelCase__	,					lowerCAmelCase__     	=					parser.parse_args_into_dataclasses()
       configure_logger(lowerCAmelCase__	,  lowerCAmelCase__	)

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

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

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

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

       lowerCAmelCase__     	=					train_dataset.map(lowerCAmelCase__	,  remove_columns=[data_args.speech_file_column]	)
       lowerCAmelCase__     	=					val_dataset.map(lowerCAmelCase__	,  remove_columns=[data_args.speech_file_column]	)

       if data_args.max_duration_in_seconds is not None:

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

              lowerCAmelCase__     	=					len(lowerCAmelCase__	)
              lowerCAmelCase__     	=					len(lowerCAmelCase__	)
              lowerCAmelCase__     	=					train_dataset.filter(lowerCAmelCase__	,  remove_columns=['duration_in_seconds']	)
              lowerCAmelCase__     	=					val_dataset.filter(lowerCAmelCase__	,  remove_columns=['duration_in_seconds']	)
              if len(lowerCAmelCase__	) > old_train_size:
                     logger.warning(
                         F"""Filtered out {len(lowerCAmelCase__	) - old_train_size} train example(s) longer than"""
                         F""" {data_args.max_duration_in_seconds} second(s)."""	)
              if len(lowerCAmelCase__	) > old_val_size:
                     logger.warning(
                         F"""Filtered out {len(lowerCAmelCase__	) - old_val_size} validation example(s) longer than"""
                         F""" {data_args.max_duration_in_seconds} second(s)."""	)
       logger.info(F"""Split sizes: {len(lowerCAmelCase__	)} train and {len(lowerCAmelCase__	)} validation."""	)

       logger.warning(F"""Updated {len(lowerCAmelCase__	)} 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}\""""	)
       lowerCAmelCase__     	=					None

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

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

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

       lowerCAmelCase__     	=					DataCollatorCTCWithPadding(processor=lowerCAmelCase__	,  padding=lowerCAmelCase__	)

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

              lowerCAmelCase__     	=					processor.tokenizer.pad_token_id

              lowerCAmelCase__     	=					processor.batch_decode(lowerCAmelCase__	)
              # we do not want to group tokens when computing the metrics
              lowerCAmelCase__     	=					processor.batch_decode(pred.label_ids	,  group_tokens=lowerCAmelCase__	)
              if logger.isEnabledFor(logging.DEBUG	):
                     for reference, predicted in zip(lowerCAmelCase__	,  lowerCAmelCase__	):
                            logger.debug(F"""reference: \"{reference}\""""	)
                            logger.debug(F"""predicted: \"{predicted}\""""	)
                            if orthography.untransliterator is not None:
                                   logger.debug(F"""reference (untransliterated): \"{orthography.untransliterator(lowerCAmelCase__	)}\""""	)
                                   logger.debug(F"""predicted (untransliterated): \"{orthography.untransliterator(lowerCAmelCase__	)}\""""	)

              lowerCAmelCase__     	=					wer_metric.compute(predictions=lowerCAmelCase__	,  references=lowerCAmelCase__	)

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       lowerCAmelCase__     	=					CTCTrainer(
           model=lowerCAmelCase__	,  data_collator=lowerCAmelCase__	,  args=lowerCAmelCase__	,  compute_metrics=lowerCAmelCase__	,  train_dataset=lowerCAmelCase__	,  eval_dataset=lowerCAmelCase__	,  tokenizer=processor.feature_extractor	,  )

       trainer.train()


if __name__ == "__main__":
    main()

from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_clip import CLIPTokenizer


lowerCAmelCase__							= logging.get_logger(__name__)

lowerCAmelCase__							= {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

lowerCAmelCase__							= {
    'vocab_file': {
        'openai/clip-vit-base-patch32': 'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/vocab.json',
    },
    'merges_file': {
        'openai/clip-vit-base-patch32': 'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'openai/clip-vit-base-patch32': (
            'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/tokenizer.json'
        ),
    },
}

lowerCAmelCase__							= {
    'openai/clip-vit-base-patch32': 77,
}
class 				a_ (						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_	 =					VOCAB_FILES_NAMES
 UpperCAmelCase_	 =					PRETRAINED_VOCAB_FILES_MAP
 UpperCAmelCase_	 =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 UpperCAmelCase_	 =					['input_ids', 'attention_mask']
 UpperCAmelCase_	 =					CLIPTokenizer




 def __init__(			self					:  Optional[int]			,    lowercase__					:  Optional[int]=None			,    lowercase__					:  Tuple=None			,    lowercase__					:  Tuple=None			,    lowercase__					:  str="<|endoftext|>"			,    lowercase__					:  List[str]="<|startoftext|>"			,    lowercase__					:  Union[str, Any]="<|endoftext|>"			,    lowercase__					:  Any="<|endoftext|>"			,    **lowercase__					:  Any			,    ):







        '''simple docstring'''



        super().__init__(
            lowercase__			,    lowercase__			,    tokenizer_file=lowercase__			,    unk_token=lowercase__			,    bos_token=lowercase__			,    eos_token=lowercase__			,    pad_token=lowercase__			,    **lowercase__			,    )

        if not isinstance(self.backend_tokenizer.pre_tokenizer			,    pre_tokenizers.Sequence):
               raise ValueError(
                   'The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been'
                   ' heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using'
                   ' to be compatible with this version.The easiest way to do so is'
                   ' `CLIPTokenizerFast.from_pretrained("path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'
                   ' to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of'
                   ' transformers.')

        self._wrap_decode_method_backend_tokenizer()




 def 		__snake_case						(			self					:  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.backend_tokenizer.decode

        def new_decode_method(*lowercase__					:  str			,    **lowercase__					:  int):
               lowerCAmelCase__     	=					orig_decode_method(*lowercase__			,    **lowercase__)
               lowerCAmelCase__     	=					text.replace(self.backend_tokenizer.model.end_of_word_suffix			,    ' ').strip()
               return text

        lowerCAmelCase__     	=					new_decode_method




 def 		__snake_case						(			self					:  Tuple			,    lowercase__					:  List[int]			,    lowercase__					:  Optional[List[int]] = None):







        '''simple docstring'''



        lowerCAmelCase__     	=					[self.bos_token_id]
        lowerCAmelCase__     	=					[self.eos_token_id]

        if token_ids_a is None:
               return bos_token + token_ids_a + eos_token
        return bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token




 def 		__snake_case						(			self					:  Any			,    lowercase__					:  List[int]			,    lowercase__					:  Optional[List[int]] = None):







        '''simple docstring'''



        lowerCAmelCase__     	=					[self.bos_token_id]
        lowerCAmelCase__     	=					[self.eos_token_id]

        if token_ids_a is None:
               return len(bos_token + token_ids_a + eos_token) * [0]
        return len(bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token) * [0]




 def 		__snake_case						(			self					:  Dict			,    lowercase__					:  str			,    lowercase__					:  Optional[str] = None):







        '''simple docstring'''



        lowerCAmelCase__     	=					self._tokenizer.model.save(lowercase__			,    name=lowercase__)
        return tuple(lowercase__)
