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


UpperCAmelCase_    		=				logging.getLogger(__name__)





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


def 				UpperCamelCase					(     lowerCAmelCase_							,       lowerCAmelCase_ )		->    List[Any]:




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





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





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



     @classmethod
     def       a__	(       cls					,   lowerCAmelCase__							):
            if name == "librispeech":
                   return cls()
            if name == "timit":
                   return cls(
                       do_lower_case=lowerCAmelCase__					,   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(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       a__	(       self					,   lowerCAmelCase__							):
            # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
            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       a__	(       self					,   lowerCAmelCase__							):
            _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(lowerCAmelCase__					,   lowerCAmelCase__							)





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



     def __call__(       self					,   lowerCAmelCase__							):
            # split inputs and labels since they have to be of different lenghts and need
            # different padding methods
            _A=						[{'input_values': feature['input_values']} for feature in features]
            _A=						[{'input_ids': feature['labels']} for feature in features]

            _A=						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=						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=						labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1							)					,   -100							)

            _A=						labels

            return batch





class   lowerCAmelCase    (       _a      ):



     def       a__	(       self					,   lowerCAmelCase__					,   lowerCAmelCase__							):
            model.train()
            _A=						self._prepare_inputs(lowerCAmelCase__							)

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

            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(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 				UpperCamelCase					(     )		->    Union[str, Any]:




       '''simple docstring'''






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

       _A,      _A,      _A=						parser.parse_args_into_dataclasses()
       configure_logger(lowerCAmelCase_							,       lowerCAmelCase_ )

       _A=						Orthography.from_name(data_args.orthography.lower() )
       _A=						orthography.create_processor(lowerCAmelCase_ )
       _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(lowerCAmelCase_ ) == 1 )
       _A=						re.compile(  # remove characters not in vocabulary
           RF"[^\s{re.escape(lowerCAmelCase_ )}]"							,       flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0							,       )
       _A=						[]

       def prepare_example(lowerCAmelCase_ ):  # TODO(elgeish) make use of multiprocessing?
              _A,      _A=						librosa.load(example[data_args.speech_file_column]							,       sr=lowerCAmelCase_ )
              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(''							,       lowerCAmelCase_ )
              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(lowerCAmelCase_							,       remove_columns=[data_args.speech_file_column] )
       _A=						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

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

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

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

       _A=						DataCollatorCTCWithPadding(processor=lowerCAmelCase_							,       padding=lowerCAmelCase_ )

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

              _A=						processor.tokenizer.pad_token_id

              _A=						processor.batch_decode(lowerCAmelCase_ )
              # we do not want to group tokens when computing the metrics
              _A=						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_ )}\"" )

              _A=						wer_metric.compute(predictions=lowerCAmelCase_							,       references=lowerCAmelCase_ )

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       _A=						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()
import argparse
import os


UpperCAmelCase_    		=				{
    '''pytorch''': {
        '''1.13''': {
            '''torch''': '''1.13.1''',
            '''torchvision''': '''0.14.1''',
            '''torchaudio''': '''0.13.1''',
            '''python''': 3.9,
            '''cuda''': '''cu116''',
            '''install''': (
                '''python3 -m pip install --no-cache-dir -U torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1'''
                ''' --extra-index-url https://download.pytorch.org/whl/cu116'''
            ),
            '''base_image''': '''nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04''',
        },
        '''1.12''': {
            '''torch''': '''1.12.1''',
            '''torchvision''': '''0.13.1''',
            '''torchaudio''': '''0.12.1''',
            '''python''': 3.9,
            '''cuda''': '''cu113''',
            '''install''': (
                '''python3 -m pip install --no-cache-dir -U torch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1'''
                ''' --extra-index-url https://download.pytorch.org/whl/cu113'''
            ),
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''1.11''': {
            '''torch''': '''1.11.0''',
            '''torchvision''': '''0.12.0''',
            '''torchaudio''': '''0.11.0''',
            '''python''': 3.9,
            '''cuda''': '''cu113''',
            '''install''': (
                '''python3 -m pip install --no-cache-dir -U torch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0'''
                ''' --extra-index-url https://download.pytorch.org/whl/cu113'''
            ),
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''1.10''': {
            '''torch''': '''1.10.2''',
            '''torchvision''': '''0.11.3''',
            '''torchaudio''': '''0.10.2''',
            '''python''': 3.9,
            '''cuda''': '''cu113''',
            '''install''': (
                '''python3 -m pip install --no-cache-dir -U torch==1.10.2 torchvision==0.11.3 torchaudio==0.10.2'''
                ''' --extra-index-url https://download.pytorch.org/whl/cu113'''
            ),
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        # torchaudio < 0.10 has no CUDA-enabled binary distributions
        '''1.9''': {
            '''torch''': '''1.9.1''',
            '''torchvision''': '''0.10.1''',
            '''torchaudio''': '''0.9.1''',
            '''python''': 3.9,
            '''cuda''': '''cu111''',
            '''install''': (
                '''python3 -m pip install --no-cache-dir -U torch==1.9.1 torchvision==0.10.1 torchaudio==0.9.1'''
                ''' --extra-index-url https://download.pytorch.org/whl/cu111'''
            ),
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
    },
    '''tensorflow''': {
        '''2.11''': {
            '''tensorflow''': '''2.11.1''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.11.1''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''2.10''': {
            '''tensorflow''': '''2.10.1''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.10.1''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''2.9''': {
            '''tensorflow''': '''2.9.3''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.9.3''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''2.8''': {
            '''tensorflow''': '''2.8.2''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.8.2''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''2.7''': {
            '''tensorflow''': '''2.7.3''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.7.3''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''2.6''': {
            '''tensorflow''': '''2.6.5''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.6.5''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
        '''2.5''': {
            '''tensorflow''': '''2.5.3''',
            '''install''': '''python3 -m pip install --no-cache-dir -U tensorflow==2.5.3''',
            '''base_image''': '''nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04''',
        },
    },
}


if __name__ == "__main__":
      UpperCAmelCase_    		=				argparse.ArgumentParser('''Choose the framework and version to install''')
      parser.add_argument(
          '''--framework''', help='''The framework to install. Should be `torch` or `tensorflow`''', type=str, required=True
      )
      parser.add_argument('''--version''', help='''The version of the framework to install.''', type=str, required=True)
      UpperCAmelCase_    		=				parser.parse_args()

      UpperCAmelCase_    		=				past_versions_testing[args.framework][args.version]

      os.system(F"echo \"export INSTALL_CMD=\'{info['install']}\'\" >> ~/.profile")
      print(F"echo \"export INSTALL_CMD=\'{info['install']}\'\" >> ~/.profile")

      UpperCAmelCase_    		=				''''''
      if args.framework == "pytorch":
            UpperCAmelCase_    		=				info['''cuda''']
      os.system(F"echo \"export CUDA='{cuda}'\" >> ~/.profile")
      print(F"echo \"export CUDA='{cuda}'\" >> ~/.profile")