





'''simple docstring'''







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

_lowercase       						=			logging.getLogger(__name__)

def    __UpperCamelCase	(	a    : str=None					,   a    : Dict=None     ) ->Any:
 return field(default_factory=lambda: default					,   metadata=a     )
@dataclass
class 			_lowercase						:
     _UpperCAmelCase										=					field(
         metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}					)
     _UpperCAmelCase										=					field(
         default=__a				,		metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}				,		)
     _UpperCAmelCase										=					field(
         default=__a				,		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 			_lowercase						:
     _UpperCAmelCase										=					field(
         default=__a				,		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=__a				,		metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}					)
     _UpperCAmelCase										=					field(
         default=__a				,		metadata={'''help''': '''The number of processes to use for the preprocessing.'''}				,		)
     _UpperCAmelCase										=					field(
         default=__a				,		metadata={
             '''help''': (
                 '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                 '''value if set.'''
             )
         }				,		)
     _UpperCAmelCase										=					field(
         default=__a				,		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 			_lowercase						:
     _UpperCAmelCase										=					42
     _UpperCAmelCase										=					True
     _UpperCAmelCase										=					None
     _UpperCAmelCase										=					None
     _UpperCAmelCase										=					None
     _UpperCAmelCase										=					None







     def __call__( self    ,   A__    ) ->	Dict[str, torch.Tensor]:
      # split inputs and labels since they have to be of different lenghts and need
      # different padding methods
      snake_case				=			[{'''input_values''': feature['''input_values''']} for feature in features]
      snake_case				=			[{'''input_ids''': feature['''labels''']} for feature in features]

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

      snake_case				=			labels

      return batch




class 			_lowercase						(       __a					):







     def     UpperCamelCase			( self    ,   A__    ,   A__    ) ->	torch.Tensor:
      model.train()
      snake_case				=			self._prepare_inputs(A__    )

      if self.use_amp:
       with autocast():
        snake_case				=			self.compute_loss(A__    ,   A__    )
      else:
       snake_case				=			self.compute_loss(A__    ,   A__    )

      if self.args.n_gpu > 1:
       if model.module.config.ctc_loss_reduction == "mean":
        snake_case				=			loss.mean()
       elif model.module.config.ctc_loss_reduction == "sum":
        snake_case				=			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:
       snake_case				=			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    __UpperCamelCase	(	) ->Optional[int]:
 # 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.

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

 # Detecting last checkpoint.
 snake_case				=			None
 if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
  snake_case				=			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:
 snake_case				=			datasets.load_dataset(
     '''common_voice'''					,   data_args.dataset_config_name					,   split=data_args.train_split_name     )
 snake_case				=			datasets.load_dataset('''common_voice'''					,   data_args.dataset_config_name					,   split='''test'''     )

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

 def remove_special_characters(a    : str     ):
  snake_case				=			re.sub(a					,   ''''''					,   batch['''sentence''']     ).lower() + ''' '''
  return batch

 snake_case				=			train_dataset.map(a					,   remove_columns=['''sentence''']     )
 snake_case				=			eval_dataset.map(a					,   remove_columns=['''sentence''']     )

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

 snake_case				=			train_dataset.map(
     a					,   batched=a					,   batch_size=-1					,   keep_in_memory=a					,   remove_columns=train_dataset.column_names					,   )
 snake_case				=			train_dataset.map(
     a					,   batched=a					,   batch_size=-1					,   keep_in_memory=a					,   remove_columns=eval_dataset.column_names					,   )

 snake_case				=			list(set(vocab_train['''vocab'''][0]     ) | set(vocab_test['''vocab'''][0]     )     )
 snake_case				=			{v: k for k, v in enumerate(a     )}
 snake_case				=			vocab_dict[''' ''']
 del vocab_dict[" "]
 snake_case				=			len(a     )
 snake_case				=			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.
 snake_case				=			WavaVecaCTCTokenizer(
     '''vocab.json'''					,   unk_token='''[UNK]'''					,   pad_token='''[PAD]'''					,   word_delimiter_token='''|'''					,   )
 snake_case				=			WavaVecaFeatureExtractor(
     feature_size=1					,   sampling_rate=1_6000					,   padding_value=0.0					,   do_normalize=a					,   return_attention_mask=a     )
 snake_case				=			WavaVecaProcessor(feature_extractor=a					,   tokenizer=a     )
 snake_case				=			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:
  snake_case				=			min(len(a     )					,   data_args.max_train_samples     )
  snake_case				=			train_dataset.select(range(a     )     )

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

 snake_case				=			torchaudio.transforms.Resample(4_8000					,   1_6000     )

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

 snake_case				=			train_dataset.map(
     a					,   remove_columns=train_dataset.column_names					,   num_proc=data_args.preprocessing_num_workers					,   )
 snake_case				=			eval_dataset.map(
     a					,   remove_columns=eval_dataset.column_names					,   num_proc=data_args.preprocessing_num_workers					,   )

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

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

 snake_case				=			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					,   )
 snake_case				=			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
 snake_case				=			datasets.load_metric('''wer'''     )

 def compute_metrics(a    : Union[str, Any]     ):
  snake_case				=			pred.predictions
  snake_case				=			np.argmax(a					,   axis=-1     )

  snake_case				=			processor.tokenizer.pad_token_id

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

  snake_case				=			wer_metric.compute(predictions=a					,   references=a     )

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 snake_case				=			DataCollatorCTCWithPadding(processor=a					,   padding=a     )

 # Initialize our Trainer
 snake_case				=			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:
   snake_case				=			last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path     ):
   snake_case				=			model_args.model_name_or_path
  else:
   snake_case				=			None

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

  snake_case				=			trainer.train(resume_from_checkpoint=a     )
  trainer.save_model()

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

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

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

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

 return results


if __name__ == "__main__":
   main()








'''simple docstring'''







import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
   import torch
class 			_lowercase						(       __a					):
     _UpperCAmelCase										=					'''char'''
     _UpperCAmelCase										=					'''bpe'''
     _UpperCAmelCase										=					'''wp'''




_lowercase       						=			(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class 			_lowercase						(       __a					):
     _UpperCAmelCase										=					['''image_processor''', '''char_tokenizer''']
     _UpperCAmelCase										=					'''ViTImageProcessor'''
     _UpperCAmelCase										=					'''MgpstrTokenizer'''







     def __init__( self    ,   A__=None    ,   A__=None    ,   **A__    ) ->	List[Any]:
      snake_case				=			None
      if "feature_extractor" in kwargs:
       warnings.warn(
           '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
           ''' instead.'''    ,   A__    ,   )
       snake_case				=			kwargs.pop('''feature_extractor'''    )

      snake_case				=			image_processor if image_processor is not None else feature_extractor
      if image_processor is None:
       raise ValueError('''You need to specify an `image_processor`.'''    )
      if tokenizer is None:
       raise ValueError('''You need to specify a `tokenizer`.'''    )

      snake_case				=			tokenizer
      snake_case				=			AutoTokenizer.from_pretrained('''gpt2'''    )
      snake_case				=			AutoTokenizer.from_pretrained('''bert-base-uncased'''    )

      super().__init__(A__    ,   A__    )







     def __call__( self    ,   A__=None    ,   A__=None    ,   A__=None    ,   **A__    ) ->	List[str]:
      if images is None and text is None:
       raise ValueError('''You need to specify either an `images` or `text` input to process.'''    )

      if images is not None:
       snake_case				=			self.image_processor(A__    ,   return_tensors=A__    ,   **A__    )
      if text is not None:
       snake_case				=			self.char_tokenizer(A__    ,   return_tensors=A__    ,   **A__    )

      if text is None:
       return inputs
      elif images is None:
       return encodings
      else:
       snake_case				=			encodings['''input_ids''']
       return inputs







     def     UpperCamelCase			( self    ,   A__    ) ->	Dict:
      snake_case				,		snake_case				,		snake_case				=			sequences
      snake_case				=			char_preds.size(0    )

      snake_case				,		snake_case				=			self._decode_helper(A__    ,   '''char'''    )
      snake_case				,		snake_case				=			self._decode_helper(A__    ,   '''bpe'''    )
      snake_case				,		snake_case				=			self._decode_helper(A__    ,   '''wp'''    )

      snake_case				=			[]
      snake_case				=			[]
      for i in range(A__    ):
       snake_case				=			[char_scores[i], bpe_scores[i], wp_scores[i]]
       snake_case				=			[char_strs[i], bpe_strs[i], wp_strs[i]]
       snake_case				=			scores.index(max(A__    )    )
       final_strs.append(strs[max_score_index]    )
       final_scores.append(scores[max_score_index]    )

      snake_case				=			{}
      snake_case				=			final_strs
      snake_case				=			final_scores
      snake_case				=			char_strs
      snake_case				=			bpe_strs
      snake_case				=			wp_strs
      return out







     def     UpperCamelCase			( self    ,   A__    ,   A__    ) ->	Optional[Any]:
      if format == DecodeType.CHARACTER:
       snake_case				=			self.char_decode
       snake_case				=			1
       snake_case				=			'''[s]'''
      elif format == DecodeType.BPE:
       snake_case				=			self.bpe_decode
       snake_case				=			2
       snake_case				=			'''#'''
      elif format == DecodeType.WORDPIECE:
       snake_case				=			self.wp_decode
       snake_case				=			1_02
       snake_case				=			'''[SEP]'''
      else:
       raise ValueError(F"""Format {format} is not supported."""    )

      snake_case				,		snake_case				=			[], []
      snake_case				=			pred_logits.size(0    )
      snake_case				=			pred_logits.size(1    )
      snake_case				,		snake_case				=			pred_logits.topk(1    ,   dim=-1    ,   largest=A__    ,   sorted=A__    )
      snake_case				=			preds_index.view(-1    ,   A__    )[:, 1:]
      snake_case				=			decoder(A__    )
      snake_case				,		snake_case				=			torch.nn.functional.softmax(A__    ,   dim=2    ).max(dim=2    )
      snake_case				=			preds_max_prob[:, 1:]

      for index in range(A__    ):
       snake_case				=			preds_str[index].find(A__    )
       snake_case				=			preds_str[index][:pred_eos]
       snake_case				=			preds_index[index].cpu().tolist()
       snake_case				=			pred_index.index(A__    ) if eos_token in pred_index else -1
       snake_case				=			preds_max_prob[index][: pred_eos_index + 1]
       snake_case				=			pred_max_prob.cumprod(dim=0    )[-1] if pred_max_prob.nelement() != 0 else 0.0
       dec_strs.append(A__    )
       conf_scores.append(A__    )

      return dec_strs, conf_scores







     def     UpperCamelCase			( self    ,   A__    ) ->	int:
      snake_case				=			[seq.replace(''' '''    ,   ''''''    ) for seq in self.char_tokenizer.batch_decode(A__    )]
      return decode_strs







     def     UpperCamelCase			( self    ,   A__    ) ->	List[str]:
      return self.bpe_tokenizer.batch_decode(A__    )







     def     UpperCamelCase			( self    ,   A__    ) ->	Union[str, Any]:
      snake_case				=			[seq.replace(''' '''    ,   ''''''    ) for seq in self.wp_tokenizer.batch_decode(A__    )]
      return decode_strs

