





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

A         =				logging.getLogger(__name__)

def 		SCREAMING_SNAKE_CASE   (       lowerCAmelCase__  :						Optional[Any]=None							,	lowerCAmelCase__  :						str=None)      ->    List[str]:

     '''simple docstring'''




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



@dataclass
class 				__SCREAMING_SNAKE_CASE      :
      '''simple docstring'''



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



@dataclass
class 				__SCREAMING_SNAKE_CASE      :
      '''simple docstring'''



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



@dataclass
class 				__SCREAMING_SNAKE_CASE      :
      '''simple docstring'''



      lowerCAmelCase__							:   WavaVecaProcessor
      lowerCAmelCase__							:   Union[bool, str]					=		True
      lowerCAmelCase__							:   Optional[int]					=		None
      lowerCAmelCase__							:   Optional[int]					=		None
      lowerCAmelCase__							:   Optional[int]					=		None
      lowerCAmelCase__							:   Optional[int]					=		None

      def __call__(				self     :			List[str] ,UpperCamelCase     :			Dict	)		->	Dict:
           _lowercase				:   Optional[int]	    =				[{'input_values': feature['input_values']} for feature in features]
           _lowercase				:   List[str]	    =				[{'input_ids': feature['labels']} for feature in features]

           _lowercase				:   Union[str, Any]	    =				self.processor.pad(
               UpperCamelCase ,padding=self.padding ,max_length=self.max_length ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors='pt' ,)
           _lowercase				:   Tuple	    =				self.processor.pad(
               labels=UpperCamelCase ,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				:   Tuple	    =				labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1	) ,-100	)

           _lowercase				:   Tuple	    =				labels

           return batch



class 				__SCREAMING_SNAKE_CASE      (							__snake_case   ):
      '''simple docstring'''



      def 	_lowerCamelCase		(				self     :			Dict ,UpperCamelCase     :			Optional[Any] ,UpperCamelCase     :			List[Any]	)		->	Dict:
           model.train()
           _lowercase				:   Optional[Any]	    =				self._prepare_inputs(UpperCamelCase	)

           if self.use_amp:
                with autocast():
                     _lowercase				:   int	    =				self.compute_loss(UpperCamelCase ,UpperCamelCase	)
           else:
                _lowercase				:   Optional[Any]	    =				self.compute_loss(UpperCamelCase ,UpperCamelCase	)

           if self.args.n_gpu > 1:
                if model.module.config.ctc_loss_reduction == "mean":
                     _lowercase				:   Tuple	    =				loss.mean()
                elif model.module.config.ctc_loss_reduction == "sum":
                     _lowercase				:   List[Any]	    =				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				:   Tuple	    =				loss / self.args.gradient_accumulation_steps

           if self.use_amp:
                self.scaler.scale(UpperCamelCase	).backward()
           elif self.use_apex:
                with amp.scale_loss(UpperCamelCase ,self.optimizer	) as scaled_loss:
                     scaled_loss.backward()
           elif self.deepspeed:
                self.deepspeed.backward(UpperCamelCase	)
           else:
                loss.backward()

           return loss.detach()

def 		SCREAMING_SNAKE_CASE   (       )      ->    Tuple:

     '''simple docstring'''




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

     # Detecting last checkpoint.
     _lowercase				:   List[str]	    =				None
     if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
          _lowercase				:   Dict	    =				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:
     _lowercase				:   Optional[Any]	    =				datasets.load_dataset(
         'common_voice'							,	data_args.dataset_config_name							,	split=data_args.train_split_name)
     _lowercase				:   Union[str, Any]	    =				datasets.load_dataset('common_voice'							,	data_args.dataset_config_name							,	split='test')

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

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

     _lowercase				:   Any	    =				train_dataset.map(_lowercase							,	remove_columns=['sentence'])
     _lowercase				:   Any	    =				eval_dataset.map(_lowercase							,	remove_columns=['sentence'])

     def extract_all_chars(lowerCAmelCase__  :						str):
          _lowercase				:   Union[str, Any]	    =				' '.join(batch['text'])
          _lowercase				:   List[Any]	    =				list(set(_lowercase))
          return {"vocab": [vocab], "all_text": [all_text]}

     _lowercase				:   List[Any]	    =				train_dataset.map(
         _lowercase							,	batched=_lowercase							,	batch_size=-1							,	keep_in_memory=_lowercase							,	remove_columns=train_dataset.column_names							,	)
     _lowercase				:   Any	    =				train_dataset.map(
         _lowercase							,	batched=_lowercase							,	batch_size=-1							,	keep_in_memory=_lowercase							,	remove_columns=eval_dataset.column_names							,	)

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

     if data_args.max_val_samples is not None:
          _lowercase				:   Union[str, Any]	    =				eval_dataset.select(range(data_args.max_val_samples))

     _lowercase				:   Any	    =				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(lowerCAmelCase__  :						Union[str, Any]):
          _lowercase    ,			_lowercase				:   Any	    =				torchaudio.load(batch['path'])
          _lowercase				:   str	    =				resampler(_lowercase).squeeze().numpy()
          _lowercase				:   Tuple	    =				1_60_00
          _lowercase				:   int	    =				batch['text']
          return batch

     _lowercase				:   Optional[Any]	    =				train_dataset.map(
         _lowercase							,	remove_columns=train_dataset.column_names							,	num_proc=data_args.preprocessing_num_workers							,	)
     _lowercase				:   List[Any]	    =				eval_dataset.map(
         _lowercase							,	remove_columns=eval_dataset.column_names							,	num_proc=data_args.preprocessing_num_workers							,	)

     def prepare_dataset(lowerCAmelCase__  :						str):
          # 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				:   str	    =				processor(
              audio=batch['speech']							,	text=batch['target_text']							,	sampling_rate=batch['sampling_rate'][0])
          batch.update(_lowercase)
          return batch

     _lowercase				:   Optional[int]	    =				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							,	)
     _lowercase				:   Any	    =				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
     _lowercase				:   Dict	    =				datasets.load_metric('wer')

     def compute_metrics(lowerCAmelCase__  :						Optional[int]):
          _lowercase				:   Union[str, Any]	    =				pred.predictions
          _lowercase				:   List[str]	    =				np.argmax(_lowercase							,	axis=-1)

          _lowercase				:   Dict	    =				processor.tokenizer.pad_token_id

          _lowercase				:   Optional[int]	    =				processor.batch_decode(_lowercase)
          # we do not want to group tokens when computing the metrics
          _lowercase				:   Any	    =				processor.batch_decode(pred.label_ids							,	group_tokens=_lowercase)

          _lowercase				:   Union[str, Any]	    =				wer_metric.compute(predictions=_lowercase							,	references=_lowercase)

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     # Data collator
     _lowercase				:   Any	    =				DataCollatorCTCWithPadding(processor=_lowercase							,	padding=_lowercase)

     # Initialize our Trainer
     _lowercase				:   Union[str, Any]	    =				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:
               _lowercase				:   Any	    =				last_checkpoint
          elif os.path.isdir(model_args.model_name_or_path):
               _lowercase				:   List[str]	    =				model_args.model_name_or_path
          else:
               _lowercase				:   List[Any]	    =				None

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

          _lowercase				:   List[Any]	    =				trainer.train(resume_from_checkpoint=_lowercase)
          trainer.save_model()

          _lowercase				:   Optional[int]	    =				train_result.metrics
          _lowercase				:   Union[str, Any]	    =				(
              data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase)
          )
          _lowercase				:   Union[str, Any]	    =				min(_lowercase							,	len(_lowercase))

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

     # Evaluation
     _lowercase				:   Union[str, Any]	    =				{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***')
          _lowercase				:   Tuple	    =				trainer.evaluate()
          _lowercase				:   Optional[Any]	    =				data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowercase)
          _lowercase				:   Dict	    =				min(_lowercase							,	len(_lowercase))

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

     return results


if __name__ == "__main__":
    main()



"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowercase_							=							logging.get_logger(__name__)

lowercase_							=							{
    'google/mobilenet_v2_1.4_224': 'https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json',
    'google/mobilenet_v2_1.0_224': 'https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json',
    'google/mobilenet_v2_0.75_160': 'https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json',
    'google/mobilenet_v2_0.35_96': 'https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json',
    # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2
}







class    __a						( __snake_case							):
				lowerCamelCase     :       List[Any]			       ='mobilenet_v2'







				def __init__( self      ,	UpperCAmelCase=3      ,	UpperCAmelCase=224      ,	UpperCAmelCase=1.0      ,	UpperCAmelCase=8      ,	UpperCAmelCase=8      ,	UpperCAmelCase=6      ,	UpperCAmelCase=32      ,	UpperCAmelCase=True      ,	UpperCAmelCase=True      ,	UpperCAmelCase="relu6"      ,	UpperCAmelCase=True      ,	UpperCAmelCase=0.8      ,	UpperCAmelCase=0.0_2      ,	UpperCAmelCase=0.0_0_1      ,	UpperCAmelCase=255      ,	**UpperCAmelCase      ,	):

					'''simple docstring'''






					super().__init__(**UpperCAmelCase   )

					if depth_multiplier <= 0:
						raise ValueError('''depth_multiplier must be greater than zero.'''   )

					lowerCAmelCase_      							=			num_channels
					lowerCAmelCase_      							=			image_size
					lowerCAmelCase_      							=			depth_multiplier
					lowerCAmelCase_      							=			depth_divisible_by
					lowerCAmelCase_      							=			min_depth
					lowerCAmelCase_      							=			expand_ratio
					lowerCAmelCase_      							=			output_stride
					lowerCAmelCase_      							=			first_layer_is_expansion
					lowerCAmelCase_      							=			finegrained_output
					lowerCAmelCase_      							=			hidden_act
					lowerCAmelCase_      							=			tf_padding
					lowerCAmelCase_      							=			classifier_dropout_prob
					lowerCAmelCase_      							=			initializer_range
					lowerCAmelCase_      							=			layer_norm_eps
					lowerCAmelCase_      							=			semantic_loss_ignore_index







class    __a						( __snake_case							):
				lowerCamelCase     :       Optional[int]			       =version.parse('1.11'							)







				@property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					return OrderedDict([('''pixel_values''', {0: '''batch'''})]   )







				@property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					if self.task == "image-classification":
						return OrderedDict([('''logits''', {0: '''batch'''})]   )
					else:
						return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]   )







				@property
				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					return 1E-4