
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						:      Optional[Any]									= True
  from torch.cuda.amp import autocast

lowercase						:      int									= logging.getLogger(__name__)




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Union[str, Any]=None		,						_lowerCamelCase				:    Tuple=None)      ->					Union[str, Any]:






       '''simple docstring'''





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




@dataclass
class 				lowerCamelCase__							:




 '''simple docstring'''




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




@dataclass
class 				lowerCamelCase__							:




 '''simple docstring'''




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




@dataclass
class 				lowerCamelCase__							:




 '''simple docstring'''




 _A			=  42
 _A			=  True
 _A			=  None
 _A			=  None
 _A			=  None
 _A			=  None







 def __call__(      self	:Union[str, Any]  ,     a	:Tuple		)	->				Optional[Any]:
        # split inputs and labels since they have to be of different lenghts and need
        # different padding methods
        __UpperCamelCase			:     Tuple         =      [{"""input_values""": feature["""input_values"""]} for feature in features]
        __UpperCamelCase			:     List[str]         =      [{"""input_ids""": feature["""labels"""]} for feature in features]

        __UpperCamelCase			:     List[Any]         =      self.processor.pad(
            A__  ,     padding=self.padding  ,     max_length=self.max_length  ,     pad_to_multiple_of=self.pad_to_multiple_of  ,     return_tensors="pt"  ,     )
        __UpperCamelCase			:     Optional[Any]         =      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
        __UpperCamelCase			:     Optional[Any]         =      labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1		)  ,     -1_0_0		)

        __UpperCamelCase			:     str         =      labels

        return batch




class 				lowerCamelCase__							(       __lowercase):




 '''simple docstring'''




 def      _lowerCamelCase       (      self	:Optional[int]  ,     a	:Optional[Any]  ,     a	:Union[str, Any]		)	->				Any:
        model.train()
        __UpperCamelCase			:     Optional[Any]         =      self._prepare_inputs(A__		)

        if self.use_amp:
               with autocast():
                      __UpperCamelCase			:     Any         =      self.compute_loss(A__  ,     A__		)
        else:
               __UpperCamelCase			:     Union[str, Any]         =      self.compute_loss(A__  ,     A__		)

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






       '''simple docstring'''





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

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

       # Create and save tokenizer
       __UpperCamelCase			:     Dict         =      F'[{"".join(data_args.chars_to_ignore)}]'

       def remove_special_characters(_lowerCamelCase				:    List[str]):
              __UpperCamelCase			:     int         =      re.sub(lowercase_		,						""		,						batch["sentence"]).lower() + """ """
              return batch

       __UpperCamelCase			:     Any         =      train_dataset.map(lowercase_		,						remove_columns=["sentence"])
       __UpperCamelCase			:     Tuple         =      eval_dataset.map(lowercase_		,						remove_columns=["sentence"])

       def extract_all_chars(_lowerCamelCase				:    Optional[Any]):
              __UpperCamelCase			:     Optional[int]         =      """ """.join(batch["text"])
              __UpperCamelCase			:     Union[str, Any]         =      list(set(lowercase_))
              return {"vocab": [vocab], "all_text": [all_text]}

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

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

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

       __UpperCamelCase			:     Union[str, Any]         =      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(_lowerCamelCase				:    Any):
              __UpperCamelCase			:     Any         =      torchaudio.load(batch["path"])
              __UpperCamelCase			:     List[Any]         =      resampler(lowercase_).squeeze().numpy()
              __UpperCamelCase			:     Tuple         =      16_000
              __UpperCamelCase			:     Any         =      batch["""text"""]
              return batch

       __UpperCamelCase			:     Optional[Any]         =      train_dataset.map(
           lowercase_		,						remove_columns=train_dataset.column_names		,						num_proc=data_args.preprocessing_num_workers		,						)
       __UpperCamelCase			:     Optional[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}.'

              __UpperCamelCase			:     int         =      processor(
                  audio=batch["speech"]		,						text=batch["target_text"]		,						sampling_rate=batch["sampling_rate"][0])
              batch.update(lowercase_)
              return batch

       __UpperCamelCase			:     Any         =      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		,						)
       __UpperCamelCase			:     Union[str, 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
       __UpperCamelCase			:     int         =      datasets.load_metric("wer")

       def compute_metrics(_lowerCamelCase				:    str):
              __UpperCamelCase			:     Any         =      pred.predictions
              __UpperCamelCase			:     Optional[Any]         =      np.argmax(lowercase_		,						axis=-1)

              __UpperCamelCase			:     List[str]         =      processor.tokenizer.pad_token_id

              __UpperCamelCase			:     List[Any]         =      processor.batch_decode(lowercase_)
              # we do not want to group tokens when computing the metrics
              __UpperCamelCase			:     List[str]         =      processor.batch_decode(pred.label_ids		,						group_tokens=lowercase_)

              __UpperCamelCase			:     int         =      wer_metric.compute(predictions=lowercase_		,						references=lowercase_)

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       # Data collator
       __UpperCamelCase			:     int         =      DataCollatorCTCWithPadding(processor=lowercase_		,						padding=lowercase_)

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

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

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

              __UpperCamelCase			:     Tuple         =      train_result.metrics
              __UpperCamelCase			:     Dict         =      (
                  data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase_)
              )
              __UpperCamelCase			:     List[Any]         =      min(lowercase_		,						len(lowercase_))

              trainer.log_metrics("train"		,						lowercase_)
              trainer.save_metrics("train"		,						lowercase_)
              trainer.save_state()

       # Evaluation
       __UpperCamelCase			:     str         =      {}
       if training_args.do_eval:
              logger.info("*** Evaluate ***")
              __UpperCamelCase			:     Optional[int]         =      trainer.evaluate()
              __UpperCamelCase			:     str         =      data_args.max_val_samples if data_args.max_val_samples is not None else len(lowercase_)
              __UpperCamelCase			:     Tuple         =      min(lowercase_		,						len(lowercase_))

              trainer.log_metrics("eval"		,						lowercase_)
              trainer.save_metrics("eval"		,						lowercase_)

       return results


if __name__ == "__main__":
  main()

from __future__ import annotations

import time
from collections.abc import Sequence
from random import randint

from matplotlib import pyplot as plt




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Sequence[float]		,						_lowerCamelCase				:    int		,						_lowerCamelCase				:    int)      ->					tuple[int | None, int | None, float]:






							'''simple docstring'''





							if not arr:
														return None, None, 0
							if low == high:
														return low, high, arr[low]

							__UpperCamelCase			:     Tuple         =      (low + high) // 2
							__UpperCamelCase     ,		__UpperCamelCase     ,		__UpperCamelCase			:     Dict         =      max_subarray(_lowerCamelCase		,						_lowerCamelCase		,						_lowerCamelCase)
							__UpperCamelCase     ,		__UpperCamelCase     ,		__UpperCamelCase			:     Optional[int]         =      max_subarray(_lowerCamelCase		,						mid + 1		,						_lowerCamelCase)
							__UpperCamelCase     ,		__UpperCamelCase     ,		__UpperCamelCase			:     Dict         =      max_cross_sum(_lowerCamelCase		,						_lowerCamelCase		,						_lowerCamelCase		,						_lowerCamelCase)
							if left_sum >= right_sum and left_sum >= cross_sum:
														return left_low, left_high, left_sum
							elif right_sum >= left_sum and right_sum >= cross_sum:
														return right_low, right_high, right_sum
							return cross_left, cross_right, cross_sum




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Sequence[float]		,						_lowerCamelCase				:    int		,						_lowerCamelCase				:    int		,						_lowerCamelCase				:    int)      ->					tuple[int, int, float]:






							'''simple docstring'''





							__UpperCamelCase     ,		__UpperCamelCase			:     Union[str, Any]         =      float("-inf"), -1
							__UpperCamelCase     ,		__UpperCamelCase			:     Optional[int]         =      float("-inf"), -1

							__UpperCamelCase			:     int | float         =      0
							for i in range(_lowerCamelCase		,						low - 1		,						-1):
														summ += arr[i]
														if summ > left_sum:
																					__UpperCamelCase			:     Tuple         =      summ
																					__UpperCamelCase			:     Optional[int]         =      i

							__UpperCamelCase			:     Union[str, Any]         =      0
							for i in range(mid + 1		,						high + 1):
														summ += arr[i]
														if summ > right_sum:
																					__UpperCamelCase			:     Union[str, Any]         =      summ
																					__UpperCamelCase			:     Optional[int]         =      i

							return max_left, max_right, (left_sum + right_sum)




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    int)      ->					float:






							'''simple docstring'''





							__UpperCamelCase			:     Tuple         =      [randint(1		,						_lowerCamelCase) for _ in range(_lowerCamelCase)]
							__UpperCamelCase			:     Optional[Any]         =      time.time()
							max_subarray(_lowerCamelCase		,						0		,						input_size - 1)
							__UpperCamelCase			:     Any         =      time.time()
							return end - start




def 			_SCREAMING_SNAKE_CASE      (	)      ->					None:






							'''simple docstring'''





							__UpperCamelCase			:     Dict         =      [10, 100, 1_000, 10_000, 50_000, 100_000, 200_000, 300_000, 400_000, 500_000]
							__UpperCamelCase			:     Union[str, Any]         =      [time_max_subarray(_lowerCamelCase) for input_size in input_sizes]
							print("No of Inputs\t\tTime Taken")
							for input_size, runtime in zip(_lowerCamelCase		,						_lowerCamelCase):
														print(_lowerCamelCase		,						"\t\t"		,						_lowerCamelCase)
							plt.plot(_lowerCamelCase		,						_lowerCamelCase)
							plt.xlabel("Number of Inputs")
							plt.ylabel("Time taken in seconds")
							plt.show()


if __name__ == "__main__":
		from doctest import testmod

		testmod()