



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

a__      :				str   	=			logging.getLogger(__name__)

def   _lowerCAmelCase   (						A__=None						,  A__=None	):
      return field(default_factory=lambda: default						,  metadata=A__	)



@dataclass
class       UpperCAmelCase__:

   '''simple docstring'''




   A    :  str       				=    field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}	)
   A    :  Optional[str]       				=    field(
       default=lowerCamelCase     ,							metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}     ,							)
   A    :  Optional[bool]       				=    field(
       default=lowerCamelCase     ,							metadata={"help": "Whether to freeze the feature extractor layers of the model."}	)
   A    :  Optional[float]       				=    field(
       default=0.1     ,							metadata={"help": "The dropout ratio for the attention probabilities."}	)
   A    :  Optional[float]       				=    field(
       default=0.1     ,							metadata={"help": "The dropout ratio for activations inside the fully connected layer."}	)
   A    :  Optional[float]       				=    field(
       default=0.1     ,							metadata={
           "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."
       }     ,							)
   A    :  Optional[float]       				=    field(
       default=0.1     ,							metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."}     ,							)
   A    :  Optional[float]       				=    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``."
           )
       }     ,							)
   A    :  Optional[float]       				=    field(default=0.0     ,							metadata={"help": "The LayerDrop probability."}	)



@dataclass
class       UpperCAmelCase__:

   '''simple docstring'''




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



@dataclass
class       UpperCAmelCase__:

   '''simple docstring'''




   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  :			Any			,				lowerCAmelCase  :			List[Dict[str, Union[List[int], torch.Tensor]]])	->				Dict[str, torch.Tensor]:




         """simple docstring"""

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

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

         lowercase__     =  labels

         return batch



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




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




         """simple docstring"""

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

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

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

      lowercase__     =  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.
            lowercase__,	lowercase__,	lowercase__     =  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]	)	)
      else:
            lowercase__,	lowercase__,	lowercase__     =  parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      lowercase__     =  None
      if os.path.isdir(training_args.output_dir	) and training_args.do_train and not training_args.overwrite_output_dir:
            lowercase__     =  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'						,  A__	)

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

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

      # Create and save tokenizer
      lowercase__     =  F'''[{''.join(data_args.chars_to_ignore	)}]'''

      def remove_special_characters(A__	):
            lowercase__     =  re.sub(A__						,  ''						,  batch['sentence']	).lower() + ' '
            return batch

      lowercase__     =  train_dataset.map(A__						,  remove_columns=['sentence']	)
      lowercase__     =  eval_dataset.map(A__						,  remove_columns=['sentence']	)

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

      lowercase__     =  train_dataset.map(
          A__						,  batched=A__						,  batch_size=-1						,  keep_in_memory=A__						,  remove_columns=train_dataset.column_names						,  )
      lowercase__     =  train_dataset.map(
          A__						,  batched=A__						,  batch_size=-1						,  keep_in_memory=A__						,  remove_columns=eval_dataset.column_names						,  )

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

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

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      lowercase__     =  WavaVecaCTCTokenizer(
          'vocab.json'						,  unk_token='[UNK]'						,  pad_token='[PAD]'						,  word_delimiter_token='|'						,  )
      lowercase__     =  WavaVecaFeatureExtractor(
          feature_size=1						,  sampling_rate=16_000						,  padding_value=0.0						,  do_normalize=A__						,  return_attention_mask=A__	)
      lowercase__     =  WavaVecaProcessor(feature_extractor=A__						,  tokenizer=A__	)
      lowercase__     =  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:
            lowercase__     =  min(len(A__	)						,  data_args.max_train_samples	)
            lowercase__     =  train_dataset.select(range(A__	)	)

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

      lowercase__     =  torchaudio.transforms.Resample(48_000						,  16_000	)

      # Preprocessing the datasets.
      # We need to read the aduio files as arrays and tokenize the targets.
      def speech_file_to_array_fn(A__	):
            lowercase__,	lowercase__     =  torchaudio.load(batch['path']	)
            lowercase__     =  resampler(A__	).squeeze().numpy()
            lowercase__     =  16_000
            lowercase__     =  batch['text']
            return batch

      lowercase__     =  train_dataset.map(
          A__						,  remove_columns=train_dataset.column_names						,  num_proc=data_args.preprocessing_num_workers						,  )
      lowercase__     =  eval_dataset.map(
          A__						,  remove_columns=eval_dataset.column_names						,  num_proc=data_args.preprocessing_num_workers						,  )

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

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

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

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

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

            lowercase__     =  processor.tokenizer.pad_token_id

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

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

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      lowercase__     =  DataCollatorCTCWithPadding(processor=A__						,  padding=A__	)

      # Initialize our Trainer
      lowercase__     =  CTCTrainer(
          model=A__						,  data_collator=A__						,  args=A__						,  compute_metrics=A__						,  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:
                  lowercase__     =  last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path	):
                  lowercase__     =  model_args.model_name_or_path
            else:
                  lowercase__     =  None

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

            lowercase__     =  trainer.train(resume_from_checkpoint=A__	)
            trainer.save_model()

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

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

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

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

      return results


if __name__ == "__main__":
     main()





import os
from typing import List, Optional, Union

from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import logging


a__      :				int   	=			logging.get_logger(__name__)

a__      :				Tuple   	=			{"vocab_file": "vocab.txt"}

a__      :				int   	=			{
    "vocab_file": {
        "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt",
        "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt",
    },
}

a__      :				Dict   	=			{
    "facebook/esm2_t6_8M_UR50D": 10_24,
    "facebook/esm2_t12_35M_UR50D": 10_24,
}

def   _lowerCAmelCase   (						A__	):
      with open(A__						,  'r'	) as f:
            lowercase__     =  f.read().splitlines()
            return [l.strip() for l in lines]



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   A    :  Union[str, Any]       				=    VOCAB_FILES_NAMES
   A    :  str       				=    PRETRAINED_VOCAB_FILES_MAP
   A    :  int       				=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A    :  List[Any]       				=    ["input_ids", "attention_mask"]


   def __init__(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Any			,				lowerCAmelCase  :			Optional[int]="<unk>"			,				lowerCAmelCase  :			Dict="<cls>"			,				lowerCAmelCase  :			List[str]="<pad>"			,				lowerCAmelCase  :			Union[str, Any]="<mask>"			,				lowerCAmelCase  :			Optional[Any]="<eos>"			,				**lowerCAmelCase  :			Any			,				)	->				Optional[Any]:




         """simple docstring"""

         super().__init__(**lowerCAmelCase)
         lowercase__     =  load_vocab_file(lowerCAmelCase)
         lowercase__     =  dict(enumerate(self.all_tokens))
         lowercase__     =  {tok: ind for ind, tok in enumerate(self.all_tokens)}
         lowercase__     =  unk_token
         lowercase__     =  cls_token
         lowercase__     =  pad_token
         lowercase__     =  mask_token
         lowercase__     =  eos_token
         lowercase__     =  self.all_tokens
         self._create_trie(self.unique_no_split_tokens)


   def 			UpperCAmelCase		(						self  :			List[Any]			,				lowerCAmelCase  :			int)	->				str:




         """simple docstring"""

         return self._id_to_token.get(lowerCAmelCase			,				self.unk_token)


   def 			UpperCAmelCase		(						self  :			Dict			,				lowerCAmelCase  :			str)	->				int:




         """simple docstring"""

         return self._token_to_id.get(lowerCAmelCase			,				self._token_to_id.get(self.unk_token))


   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				lowerCAmelCase  :			str			,				**lowerCAmelCase  :			Union[str, Any])	->				Dict:




         """simple docstring"""

         return text.split()


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Any=False)	->				Union[str, Any]:




         """simple docstring"""

         return len(self._id_to_token)


   def 			UpperCAmelCase		(						self  :			Tuple)	->				int:




         """simple docstring"""

         return {token: i for i, token in enumerate(self.all_tokens)}


   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				lowerCAmelCase  :			str)	->				int:




         """simple docstring"""

         return self._token_to_id.get(lowerCAmelCase			,				self._token_to_id.get(self.unk_token))


   def 			UpperCAmelCase		(						self  :			Dict			,				lowerCAmelCase  :			int)	->				str:




         """simple docstring"""

         return self._id_to_token.get(lowerCAmelCase			,				self.unk_token)


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




         """simple docstring"""

         lowercase__     =  [self.cls_token_id]
         lowercase__     =  [self.eos_token_id]  # No sep token in ESM vocabulary
         if token_ids_a is None:
               if self.eos_token_id is None:
                     return cls + token_ids_a
               else:
                     return cls + token_ids_a + sep
         elif self.eos_token_id is None:
               raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!')
         return cls + token_ids_a + sep + token_ids_a + sep  # Multiple inputs always have an EOS token


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			List			,				lowerCAmelCase  :			Optional[List] = None			,				lowerCAmelCase  :			bool = False)	->				List[int]:




         """simple docstring"""

         if already_has_special_tokens:
               if token_ids_a is not None:
                     raise ValueError(
                         'You should not supply a second sequence if the provided sequence of '
                         'ids is already formatted with special tokens for the model.')

               return [1 if token in self.all_special_ids else 0 for token in token_ids_a]
         lowercase__     =  [1] + ([0] * len(lowerCAmelCase)) + [1]
         if token_ids_a is not None:
               mask += [0] * len(lowerCAmelCase) + [1]
         return mask


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Tuple			,				lowerCAmelCase  :			Optional[int])	->				Dict:




         """simple docstring"""

         lowercase__     =  os.path.join(lowerCAmelCase			,				(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt')
         with open(lowerCAmelCase			,				'w') as f:
               f.write('\n'.join(self.all_tokens))
         return (vocab_file,)


   @property
   def 			UpperCAmelCase		(						self  :			Optional[int])	->				int:




         """simple docstring"""

         return self.get_vocab_size(with_added_tokens=lowerCAmelCase)



   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				lowerCAmelCase  :			Union[List[str], List[AddedToken]]			,				lowerCAmelCase  :			bool = False)	->				int:




         """simple docstring"""

         return super()._add_tokens(lowerCAmelCase			,				special_tokens=lowerCAmelCase)
