




import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
 from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"):
 lowerCamelCase				:		List[str]     =   True
 from torch.cuda.amp import autocast

lowerCamelCase				:		Tuple     =   logging.getLogger(__name__)

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       int=None	,							lowercase	:       Tuple=None     ):


      '''simple docstring'''



      return field(default_factory=lambda: default	,							metadata=lowercase     )







@dataclass
class   A:



 '''simple docstring'''


 UpperCamelCase						   =						field(
     metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}   )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}							,      )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}   )
 UpperCamelCase						   =						field(
     default=0.1							,      metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}   )
 UpperCamelCase						   =						field(
     default=0.1							,      metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}   )
 UpperCamelCase						   =						field(
     default=0.1							,      metadata={
         '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
     }							,      )
 UpperCamelCase						   =						field(
     default=0.1							,      metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}							,      )
 UpperCamelCase						   =						field(
     default=0.05							,      metadata={
         '''help''': (
             '''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
             '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
             '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
         )
     }							,      )
 UpperCamelCase						   =						field(default=0.0							,      metadata={'''help''': '''The LayerDrop probability.'''}   )







@dataclass
class   A:



 '''simple docstring'''


 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}   )
 UpperCamelCase						   =						field(
     default='''train+validation'''							,      metadata={
         '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
     }							,      )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}   )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''The number of processes to use for the preprocessing.'''}							,      )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of training examples to this '''
             '''value if set.'''
         )
     }							,      )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
             '''value if set.'''
         )
     }							,      )
 UpperCamelCase						   =						list_field(
     default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']							,      metadata={'''help''': '''A list of characters to remove from the transcripts.'''}							,      )







@dataclass
class   A:



 '''simple docstring'''


 UpperCamelCase						   =						42
 UpperCamelCase						   =						True
 UpperCamelCase						   =						None
 UpperCamelCase						   =						None
 UpperCamelCase						   =						None
 UpperCamelCase						   =						None

 def __call__(				self					:  Optional[Any]						,							A_					:  List[Dict[str, Union[List[int], torch.Tensor]]]  )   ->	Dict[str, 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(
           A_						,							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=A_						,							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(						UpperCamelCase   ):



 '''simple docstring'''


 def 				a__ (				self					:  int						,							A_					:  nn.Module						,							A_					:  Dict[str, Union[torch.Tensor, Any]]  )   ->	torch.Tensor:

       """simple docstring"""






       model.train()
       lowerCamelCase_		     =    self._prepare_inputs(A_  )

       if self.use_amp:
             with autocast():
                   lowerCamelCase_		     =    self.compute_loss(A_						,							A_  )
       else:
             lowerCamelCase_		     =    self.compute_loss(A_						,							A_  )

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

       return loss.detach()

def 			_SCREAMING_SNAKE_CASE			(							):


      '''simple docstring'''



      lowerCamelCase_		     =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
      if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            lowerCamelCase_     ,				lowerCamelCase_     ,				lowerCamelCase_		     =    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
      else:
            lowerCamelCase_     ,				lowerCamelCase_     ,				lowerCamelCase_		     =    parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      lowerCamelCase_		     =    None
      if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
            lowerCamelCase_		     =    get_last_checkpoint(training_args.output_dir     )
            if last_checkpoint is None and len(os.listdir(training_args.output_dir     )     ) > 0:
                  raise ValueError(
                      f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                      'Use --overwrite_output_dir to overcome.'     )
            elif last_checkpoint is not None:
                  logger.info(
                      f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                      'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'     )

    # Setup logging
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'	,							datefmt='%m/%d/%Y %H:%M:%S'	,							handlers=[logging.StreamHandler(sys.stdout     )]	,							)
      logger.setLevel(logging.INFO if is_main_process(training_args.local_rank     ) else logging.WARN     )

      # Log on each process the small summary:
      logger.warning(
          f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
          + f"""distributed training: {bool(training_args.local_rank != -1     )}, 16-bits training: {training_args.fpaa}"""     )
      # Set the verbosity to info of the Transformers logger (on main process only):
      if is_main_process(training_args.local_rank     ):
            transformers.utils.logging.set_verbosity_info()
      logger.info('Training/evaluation parameters %s'	,							lowercase     )

      # Set seed before initializing model.
      set_seed(training_args.seed     )

      # Get the datasets:
      lowerCamelCase_		     =    datasets.load_dataset(
          'common_voice'	,							data_args.dataset_config_name	,							split=data_args.train_split_name     )
      lowerCamelCase_		     =    datasets.load_dataset('common_voice'	,							data_args.dataset_config_name	,							split='test'     )

      # Create and save tokenizer
      lowerCamelCase_		     =    f"""[{"".join(data_args.chars_to_ignore     )}]"""

      def remove_special_characters(lowercase	:       List[Any]     ):
            lowerCamelCase_		     =    re.sub(lowercase	,							''	,							batch['sentence']     ).lower() + ' '
            return batch

      lowerCamelCase_		     =    train_dataset.map(lowercase	,							remove_columns=['sentence']     )
      lowerCamelCase_		     =    eval_dataset.map(lowercase	,							remove_columns=['sentence']     )

      def extract_all_chars(lowercase	:       Tuple     ):
            lowerCamelCase_		     =    ' '.join(batch['text']     )
            lowerCamelCase_		     =    list(set(lowercase     )     )
            return {"vocab": [vocab], "all_text": [all_text]}

      lowerCamelCase_		     =    train_dataset.map(
          lowercase	,							batched=lowercase	,							batch_size=-1	,							keep_in_memory=lowercase	,							remove_columns=train_dataset.column_names	,							)
      lowerCamelCase_		     =    train_dataset.map(
          lowercase	,							batched=lowercase	,							batch_size=-1	,							keep_in_memory=lowercase	,							remove_columns=eval_dataset.column_names	,							)

      lowerCamelCase_		     =    list(set(vocab_train['vocab'][0]     ) | set(vocab_test['vocab'][0]     )     )
      lowerCamelCase_		     =    {v: k for k, v in enumerate(lowercase     )}
      lowerCamelCase_		     =    vocab_dict[' ']
      del vocab_dict[" "]
      lowerCamelCase_		     =    len(lowercase     )
      lowerCamelCase_		     =    len(lowercase     )

      with open('vocab.json'	,							'w'     ) as vocab_file:
            json.dump(lowercase	,							lowercase     )

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      lowerCamelCase_		     =    WavaVecaCTCTokenizer(
          'vocab.json'	,							unk_token='[UNK]'	,							pad_token='[PAD]'	,							word_delimiter_token='|'	,							)
      lowerCamelCase_		     =    WavaVecaFeatureExtractor(
          feature_size=1	,							sampling_rate=1_60_00	,							padding_value=0.0	,							do_normalize=lowercase	,							return_attention_mask=lowercase     )
      lowerCamelCase_		     =    WavaVecaProcessor(feature_extractor=lowercase	,							tokenizer=lowercase     )
      lowerCamelCase_		     =    WavaVecaForCTC.from_pretrained(
          model_args.model_name_or_path	,							cache_dir=model_args.cache_dir	,							activation_dropout=model_args.activation_dropout	,							attention_dropout=model_args.attention_dropout	,							hidden_dropout=model_args.hidden_dropout	,							feat_proj_dropout=model_args.feat_proj_dropout	,							mask_time_prob=model_args.mask_time_prob	,							gradient_checkpointing=training_args.gradient_checkpointing	,							layerdrop=model_args.layerdrop	,							ctc_loss_reduction='mean'	,							pad_token_id=processor.tokenizer.pad_token_id	,							vocab_size=len(processor.tokenizer     )	,							)

      if data_args.max_train_samples is not None:
            lowerCamelCase_		     =    min(len(lowercase     )	,							data_args.max_train_samples     )
            lowerCamelCase_		     =    train_dataset.select(range(lowercase     )     )

      if data_args.max_val_samples is not None:
            lowerCamelCase_		     =    eval_dataset.select(range(data_args.max_val_samples     )     )

      lowerCamelCase_		     =    torchaudio.transforms.Resample(4_80_00	,							1_60_00     )

      # Preprocessing the datasets.
      # We need to read the aduio files as arrays and tokenize the targets.
      def speech_file_to_array_fn(lowercase	:       Tuple     ):
            lowerCamelCase_     ,				lowerCamelCase_		     =    torchaudio.load(batch['path']     )
            lowerCamelCase_		     =    resampler(lowercase     ).squeeze().numpy()
            lowerCamelCase_		     =    1_60_00
            lowerCamelCase_		     =    batch['text']
            return batch

      lowerCamelCase_		     =    train_dataset.map(
          lowercase	,							remove_columns=train_dataset.column_names	,							num_proc=data_args.preprocessing_num_workers	,							)
      lowerCamelCase_		     =    eval_dataset.map(
          lowercase	,							remove_columns=eval_dataset.column_names	,							num_proc=data_args.preprocessing_num_workers	,							)

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

            lowerCamelCase_		     =    processor(
                audio=batch['speech']	,							text=batch['target_text']	,							sampling_rate=batch['sampling_rate'][0]     )
            batch.update(lowercase     )
            return batch

      lowerCamelCase_		     =    train_dataset.map(
          lowercase	,							remove_columns=train_dataset.column_names	,							batch_size=training_args.per_device_train_batch_size	,							batched=lowercase	,							num_proc=data_args.preprocessing_num_workers	,							)
      lowerCamelCase_		     =    eval_dataset.map(
          lowercase	,							remove_columns=eval_dataset.column_names	,							batch_size=training_args.per_device_train_batch_size	,							batched=lowercase	,							num_proc=data_args.preprocessing_num_workers	,							)

      # Metric
      lowerCamelCase_		     =    datasets.load_metric('wer'     )

      def compute_metrics(lowercase	:       int     ):
            lowerCamelCase_		     =    pred.predictions
            lowerCamelCase_		     =    np.argmax(lowercase	,							axis=-1     )

            lowerCamelCase_		     =    processor.tokenizer.pad_token_id

            lowerCamelCase_		     =    processor.batch_decode(lowercase     )
            # we do not want to group tokens when computing the metrics
            lowerCamelCase_		     =    processor.batch_decode(pred.label_ids	,							group_tokens=lowercase     )

            lowerCamelCase_		     =    wer_metric.compute(predictions=lowercase	,							references=lowercase     )

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      lowerCamelCase_		     =    DataCollatorCTCWithPadding(processor=lowercase	,							padding=lowercase     )

      # Initialize our Trainer
      lowerCamelCase_		     =    CTCTrainer(
          model=lowercase	,							data_collator=lowercase	,							args=lowercase	,							compute_metrics=lowercase	,							train_dataset=train_dataset if training_args.do_train else None	,							eval_dataset=eval_dataset if training_args.do_eval else None	,							tokenizer=processor.feature_extractor	,							)

      # Training
      if training_args.do_train:
            if last_checkpoint is not None:
                  lowerCamelCase_		     =    last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path     ):
                  lowerCamelCase_		     =    model_args.model_name_or_path
            else:
                  lowerCamelCase_		     =    None

            # Save the feature_extractor and the tokenizer
            if is_main_process(training_args.local_rank     ):
                  processor.save_pretrained(training_args.output_dir     )

            lowerCamelCase_		     =    trainer.train(resume_from_checkpoint=lowercase     )
            trainer.save_model()

            lowerCamelCase_		     =    train_result.metrics
            lowerCamelCase_		     =    (
                data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase     )
            )
            lowerCamelCase_		     =    min(lowercase	,							len(lowercase     )     )

            trainer.log_metrics('train'	,							lowercase     )
            trainer.save_metrics('train'	,							lowercase     )
            trainer.save_state()

      # Evaluation
      lowerCamelCase_		     =    {}
      if training_args.do_eval:
            logger.info('*** Evaluate ***'     )
            lowerCamelCase_		     =    trainer.evaluate()
            lowerCamelCase_		     =    data_args.max_val_samples if data_args.max_val_samples is not None else len(lowercase     )
            lowerCamelCase_		     =    min(lowercase	,							len(lowercase     )     )

            trainer.log_metrics('eval'	,							lowercase     )
            trainer.save_metrics('eval'	,							lowercase     )

      return results


if __name__ == "__main__":
 main()









import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
 from .tokenization_fnet import FNetTokenizer
else:
 lowerCamelCase				:		List[Any]     =   None

lowerCamelCase				:		int     =   logging.get_logger(__name__)
lowerCamelCase				:		Optional[int]     =   {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}

lowerCamelCase				:		Optional[int]     =   {
    "vocab_file": {
        "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
        "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
    },
    "tokenizer_file": {
        "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json",
        "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json",
    },
}

lowerCamelCase				:		List[Any]     =   {
    "google/fnet-base": 512,
    "google/fnet-large": 512,
}

lowerCamelCase				:		Any     =   "▁"







class   A(						UpperCamelCase   ):



 '''simple docstring'''


 UpperCamelCase						   =						VOCAB_FILES_NAMES
 UpperCamelCase						   =						PRETRAINED_VOCAB_FILES_MAP
 UpperCamelCase						   =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 UpperCamelCase						   =						['''input_ids''', '''token_type_ids''']
 UpperCamelCase						   =						FNetTokenizer

 def __init__(				self					:  Optional[int]						,							A_					:  Any=None						,							A_					:  int=None						,							A_					:  int=False						,							A_					:  Optional[int]=True						,							A_					:  List[Any]=True						,							A_					:  Tuple="<unk>"						,							A_					:  Optional[int]="[SEP]"						,							A_					:  List[Any]="<pad>"						,							A_					:  Optional[int]="[CLS]"						,							A_					:  Optional[Any]="[MASK]"						,							**A_					:  Dict						,							)   ->	List[str]:

       """simple docstring"""






       lowerCamelCase_		     =    (
           AddedToken(A_						,							lstrip=A_						,							rstrip=A_						,							normalized=A_  )
           if isinstance(A_						,							A_  )
           else mask_token
       )

       super().__init__(
           A_						,							tokenizer_file=A_						,							do_lower_case=A_						,							remove_space=A_						,							keep_accents=A_						,							unk_token=A_						,							sep_token=A_						,							pad_token=A_						,							cls_token=A_						,							mask_token=A_						,							**A_						,							)

       lowerCamelCase_		     =    do_lower_case
       lowerCamelCase_		     =    remove_space
       lowerCamelCase_		     =    keep_accents
       lowerCamelCase_		     =    vocab_file
       lowerCamelCase_		     =    False if not self.vocab_file else True

 def 				a__ (				self					:  List[Any]						,							A_					:  List[int]						,							A_					:  Optional[List[int]] = None  )   ->	List[int]:

       """simple docstring"""






       lowerCamelCase_		     =    [self.sep_token_id]
       lowerCamelCase_		     =    [self.cls_token_id]
       if token_ids_a is None:
             return cls + token_ids_a + sep
       return cls + token_ids_a + sep + token_ids_a + sep

 def 				a__ (				self					:  Tuple						,							A_					:  List[int]						,							A_					:  Optional[List[int]] = None  )   ->	List[int]:

       """simple docstring"""






       lowerCamelCase_		     =    [self.sep_token_id]
       lowerCamelCase_		     =    [self.cls_token_id]

       if token_ids_a is None:
             return len(cls + token_ids_a + sep  ) * [0]
       return len(cls + token_ids_a + sep  ) * [0] + len(token_ids_a + sep  ) * [1]





 def 				a__ (				self					:  Dict						,							A_					:  str						,							A_					:  Optional[str] = None  )   ->	Tuple[str]:

       """simple docstring"""






       if not os.path.isdir(A_  ):
             logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""  )
             return
       lowerCamelCase_		     =    os.path.join(
           A_						,							(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']  )

       if os.path.abspath(self.vocab_file  ) != os.path.abspath(A_  ):
             copyfile(self.vocab_file						,							A_  )

       return (out_vocab_file,)



