

'''simple docstring'''
from abc import ABC, abstractmethod
from typing import List, Optional


class        a__  (							lowerCamelCase_  ):


   def __init__(			self  ):





      """simple docstring"""





      self.test()


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       0
      _lowercase      :				Dict      					=       False
      while not completed:
         if counter == 1:
            self.reset()
         _lowercase      :				List[str]      					=       self.advance()
         if not self.does_advance(_UpperCamelCase  ):
            raise Exception(
                "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."  )

         _lowercase					,				_lowercase					,				_lowercase      :				Any      					=       self.update(_UpperCamelCase  )
         counter += 1

         if counter > 10000:
            raise Exception("update() does not fulfill the constraint."  )

      if self.remaining() != 0:
         raise Exception("Custom Constraint is not defined correctly."  )


   @abstractmethod
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''  )


   @abstractmethod
   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''  )


   @abstractmethod
   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''  )


   @abstractmethod
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''  )


   @abstractmethod
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''  )






   @abstractmethod
   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase=False  ):





      """simple docstring"""





      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''  )




class        a__  (							lowerCamelCase_  ):


   def __init__(			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      super(_UpperCamelCase      ,    self  ).__init__()

      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) or len(_UpperCamelCase  ) == 0:
         raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.'''  )
      if any((not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) or token_id < 0) for token_id in token_ids  ):
         raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''  )

      _lowercase      :				Optional[Any]      					=       token_ids

      _lowercase      :				Optional[Any]      					=       len(self.token_ids  )
      _lowercase      :				Union[str, Any]      					=       -1  # the index of the currently fulfilled step
      _lowercase      :				int      					=       False


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      if self.completed:
         return None
      return self.token_ids[self.fulfilled_idx + 1]


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
         raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(_UpperCamelCase  )}'''  )

      if self.completed:
         return False

      return token_id == self.token_ids[self.fulfilled_idx + 1]


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
         raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(_UpperCamelCase  )}'''  )

      _lowercase      :				Union[str, Any]      					=       False
      _lowercase      :				str      					=       False
      _lowercase      :				List[Any]      					=       False

      if self.does_advance(_UpperCamelCase  ):
         self.fulfilled_idx += 1
         _lowercase      :				Optional[int]      					=       True
         if self.fulfilled_idx == (self.seqlen - 1):
            _lowercase      :				Union[str, Any]      					=       True
         _lowercase      :				Dict      					=       completed
      else:
         # failed to make progress.
         _lowercase      :				List[Any]      					=       True
         self.reset()
      return stepped, completed, reset


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       False
      _lowercase      :				Any      					=       0


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return self.seqlen - (self.fulfilled_idx + 1)






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase=False  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       PhrasalConstraint(self.token_ids  )

      if stateful:
         _lowercase      :				Any      					=       self.seqlen
         _lowercase      :				Optional[int]      					=       self.fulfilled_idx
         _lowercase      :				str      					=       self.completed

      return new_constraint




class        a__  :


   def __init__(			self      ,    _UpperCamelCase      ,    _UpperCamelCase=True  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       max([len(_UpperCamelCase  ) for one in nested_token_ids]  )

      _lowercase      :				List[str]      					=       {}
      for token_ids in nested_token_ids:
         _lowercase      :				List[str]      					=       root
         for tidx, token_id in enumerate(_UpperCamelCase  ):
            if token_id not in level:
               _lowercase      :				List[Any]      					=       {}

            _lowercase      :				Any      					=       level[token_id]

      if no_subsets and self.has_subsets(_UpperCamelCase      ,    _UpperCamelCase  ):
         raise ValueError(
             "Each list in `nested_token_ids` can't be a complete subset of another list, but is"
             f''' {nested_token_ids}.'''  )

      _lowercase      :				Tuple      					=       root


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       self.trie

      for current_token in current_seq:
         _lowercase      :				List[str]      					=       start[current_token]

      _lowercase      :				List[str]      					=       list(start.keys()  )

      return next_tokens


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       self.next_tokens(_UpperCamelCase  )

      return len(_UpperCamelCase  ) == 0


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       list(root.values()  )
      if len(_UpperCamelCase  ) == 0:
         return 1
      else:
         return sum([self.count_leaves(_UpperCamelCase  ) for nn in next_nodes]  )






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       self.count_leaves(_UpperCamelCase  )
      return len(_UpperCamelCase  ) != leaf_count




class        a__  (							lowerCamelCase_  ):


   def __init__(			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      super(_UpperCamelCase      ,    self  ).__init__()

      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) or len(_UpperCamelCase  ) == 0:
         raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''  )
      if any(not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) for token_ids in nested_token_ids  ):
         raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''  )
      if any(
          any((not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) or token_id < 0) for token_id in token_ids  )
          for token_ids in nested_token_ids  ):
         raise ValueError(
             f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''  )

      _lowercase      :				Optional[Any]      					=       DisjunctiveTrie(_UpperCamelCase  )
      _lowercase      :				List[str]      					=       nested_token_ids

      _lowercase      :				str      					=       self.trie.max_height
      _lowercase      :				Union[str, Any]      					=       []
      _lowercase      :				Optional[int]      					=       False


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       self.trie.next_tokens(self.current_seq  )

      if len(_UpperCamelCase  ) == 0:
         return None
      else:
         return token_list


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
         raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_UpperCamelCase  )}'''  )

      _lowercase      :				List[Any]      					=       self.trie.next_tokens(self.current_seq  )

      return token_id in next_tokens


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
         raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_UpperCamelCase  )}'''  )

      _lowercase      :				Any      					=       False
      _lowercase      :				Any      					=       False
      _lowercase      :				Optional[int]      					=       False

      if self.does_advance(_UpperCamelCase  ):
         self.current_seq.append(_UpperCamelCase  )
         _lowercase      :				Union[str, Any]      					=       True
      else:
         _lowercase      :				Tuple      					=       True
         self.reset()

      _lowercase      :				Dict      					=       self.trie.reached_leaf(self.current_seq  )
      _lowercase      :				str      					=       completed

      return stepped, completed, reset


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       False
      _lowercase      :				int      					=       []


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      if self.completed:
         # since this can be completed without reaching max height
         return 0
      else:
         return self.seqlen - len(self.current_seq  )






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase=False  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       DisjunctiveConstraint(self.token_ids  )

      if stateful:
         _lowercase      :				Dict      					=       self.seqlen
         _lowercase      :				Union[str, Any]      					=       self.current_seq
         _lowercase      :				Optional[int]      					=       self.completed

      return new_constraint




class        a__  :


   def __init__(			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Union[str, Any]      					=       constraints

      # max # of steps required to fulfill a given constraint
      _lowercase      :				List[Any]      					=       max([c.seqlen for c in constraints]  )
      _lowercase      :				str      					=       len(_UpperCamelCase  )
      _lowercase      :				Union[str, Any]      					=       False

      self.init_state()


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       []
      _lowercase      :				Union[str, Any]      					=       None
      _lowercase      :				List[Any]      					=       [constraint.copy(stateful=_UpperCamelCase  ) for constraint in self.constraints]


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       0
      if self.inprogress_constraint:
         # extra points for having a constraint mid-fulfilled
         add += self.max_seqlen - self.inprogress_constraint.remaining()

      return (len(self.complete_constraints  ) * self.max_seqlen) + add


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       []
      if self.inprogress_constraint is None:
         for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
            _lowercase      :				Tuple      					=       constraint.advance()
            if isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
               token_list.append(_UpperCamelCase  )
            elif isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
               token_list.extend(_UpperCamelCase  )
      else:
         _lowercase      :				str      					=       self.inprogress_constraint.advance()
         if isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
            token_list.append(_UpperCamelCase  )
         elif isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
            token_list.extend(_UpperCamelCase  )

      if len(_UpperCamelCase  ) == 0:
         return None
      else:
         return token_list


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      self.init_state()

      if token_ids is not None:
         for token in token_ids:
            # completes or steps **one** constraint
            _lowercase					,				_lowercase      :				Optional[int]      					=       self.add(_UpperCamelCase  )

            # the entire list of constraints are fulfilled
            if self.completed:
               break


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      if not isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
         raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.'''  )

      _lowercase					,				_lowercase      :				str      					=       False, False

      if self.completed:
         _lowercase      :				Tuple      					=       True
         _lowercase      :				int      					=       False
         return complete, stepped

      if self.inprogress_constraint is not None:
         # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
         # job, simply update the state

         _lowercase					,				_lowercase					,				_lowercase      :				Tuple      					=       self.inprogress_constraint.update(_UpperCamelCase  )
         if reset:
            # 1. If the next token breaks the progress, then we must restart.
            #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

            #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
            #     constraint, not the full list of constraints.

            self.pending_constraints.append(self.inprogress_constraint.copy(stateful=_UpperCamelCase  )  )
            _lowercase      :				Tuple      					=       None

         if complete:
            # 2. If the next token completes the constraint, move it to completed list, set
            #     inprogress to None. If there are no pending constraints either, then this full list of constraints
            #     is complete.

            self.complete_constraints.append(self.inprogress_constraint  )
            _lowercase      :				Dict      					=       None

            if len(self.pending_constraints  ) == 0:
               # we're done!
               _lowercase      :				str      					=       True

      else:
         # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
         # of constraints?

         for cidx, pending_constraint in enumerate(self.pending_constraints  ):
            if pending_constraint.does_advance(_UpperCamelCase  ):
               _lowercase					,				_lowercase					,				_lowercase      :				List[Any]      					=       pending_constraint.update(_UpperCamelCase  )

               if not stepped:
                  raise Exception(
                      "`constraint.update(token_id)` is not yielding incremental progress, "
                      "even though `constraint.does_advance(token_id)` is true."  )

               if complete:
                  self.complete_constraints.append(_UpperCamelCase  )
                  _lowercase      :				List[str]      					=       None

               if not complete and stepped:
                  _lowercase      :				Any      					=       pending_constraint

               if complete or stepped:
                  # If we made any progress at all, then it's at least not a "pending constraint".

                  _lowercase      :				Union[str, Any]      					=       (
                      self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
                  )

                  if len(self.pending_constraints  ) == 0 and self.inprogress_constraint is None:
                     # If there's no longer any pending after this and no inprogress either, then we must be
                     # complete.

                     _lowercase      :				Dict      					=       True

                  break  # prevent accidentally stepping through multiple constraints with just one token.

      return complete, stepped






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase=True  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       ConstraintListState(self.constraints  )  # we actually never though self.constraints objects
      # throughout this process. So it's at initialization state.

      if stateful:
         _lowercase      :				int      					=       [
             constraint.copy(stateful=_UpperCamelCase  ) for constraint in self.complete_constraints
         ]
         if self.inprogress_constraint is not None:
            _lowercase      :				Optional[Any]      					=       self.inprogress_constraint.copy(stateful=_UpperCamelCase  )
         _lowercase      :				Optional[int]      					=       [constraint.copy() for constraint in self.pending_constraints]

      return new_state









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

_snake_case         =  logging.getLogger(__name__)







def  _A		(     snake_case=None		,							snake_case=None					)      ->     Any:
   return field(default_factory=lambda: default		,							metadata=snake_case					)


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




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




@dataclass
class        a__  :
   _SCREAMING_SNAKE_CASE   :					WavaVecaProcessor
   _SCREAMING_SNAKE_CASE   :					Union[bool, str]     	=							True
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							None
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							None
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							None
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							None


   def __call__(			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       [{"input_values": feature["input_values"]} for feature in features]
      _lowercase      :				Dict      					=       [{"input_ids": feature["labels"]} for feature in features]

      _lowercase      :				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      :				Union[str, Any]      					=       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      :				List[str]      					=       labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1  )      ,    -100  )

      _lowercase      :				Optional[Any]      					=       labels

      return batch




class        a__  (							lowerCamelCase_  ):


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      model.train()
      _lowercase      :				str      					=       self._prepare_inputs(_UpperCamelCase  )

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

      if self.args.n_gpu > 1:
         if model.module.config.ctc_loss_reduction == "mean":
            _lowercase      :				int      					=       loss.mean()
         elif model.module.config.ctc_loss_reduction == "sum":
            _lowercase      :				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      :				Optional[int]      					=       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  _A		(     )      ->     Optional[Any]:
   # 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      :				Optional[int]      					=       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[Any]      					=       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]					)					)
   else:
      _lowercase					,				_lowercase					,				_lowercase      :				int      					=       parser.parse_args_into_dataclasses()

   # Detecting last checkpoint.
   _lowercase      :				Union[str, Any]      					=       None
   if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
      _lowercase      :				Union[str, Any]      					=       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"		,							snake_case					)

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

   # Get the datasets:
   _lowercase      :				Tuple      					=       datasets.load_dataset(
       "common_voice"		,							data_args.dataset_config_name		,							split=data_args.train_split_name					)
   _lowercase      :				Any      					=       datasets.load_dataset("common_voice"		,							data_args.dataset_config_name		,							split="test"					)

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

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

   _lowercase      :				int      					=       train_dataset.map(snake_case		,							remove_columns=["sentence"]					)
   _lowercase      :				int      					=       eval_dataset.map(snake_case		,							remove_columns=["sentence"]					)

   def extract_all_chars(snake_case					):
      _lowercase      :				Optional[int]      					=       " ".join(batch["text"]					)
      _lowercase      :				int      					=       list(set(snake_case					)					)
      return {"vocab": [vocab], "all_text": [all_text]}

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

   _lowercase      :				Dict      					=       list(set(vocab_train["vocab"][0]					) | set(vocab_test["vocab"][0]					)					)
   _lowercase      :				List[str]      					=       {v: k for k, v in enumerate(snake_case					)}
   _lowercase      :				Union[str, Any]      					=       vocab_dict[" "]
   del vocab_dict[" "]
   _lowercase      :				Dict      					=       len(snake_case					)
   _lowercase      :				Dict      					=       len(snake_case					)

   with open("vocab.json"		,							"w"					) as vocab_file:
      json.dump(snake_case		,							snake_case					)

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

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

   _lowercase      :				Dict      					=       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(snake_case					):
      _lowercase					,				_lowercase      :				List[str]      					=       torchaudio.load(batch["path"]					)
      _lowercase      :				List[Any]      					=       resampler(snake_case					).squeeze().numpy()
      _lowercase      :				str      					=       1_60_00
      _lowercase      :				Optional[int]      					=       batch["text"]
      return batch

   _lowercase      :				Dict      					=       train_dataset.map(
       snake_case		,							remove_columns=train_dataset.column_names		,							num_proc=data_args.preprocessing_num_workers		,							)
   _lowercase      :				List[str]      					=       eval_dataset.map(
       snake_case		,							remove_columns=eval_dataset.column_names		,							num_proc=data_args.preprocessing_num_workers		,							)

   def prepare_dataset(snake_case					):
      # 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(snake_case					)
      return batch

   _lowercase      :				Any      					=       train_dataset.map(
       snake_case		,							remove_columns=train_dataset.column_names		,							batch_size=training_args.per_device_train_batch_size		,							batched=snake_case		,							num_proc=data_args.preprocessing_num_workers		,							)
   _lowercase      :				Dict      					=       eval_dataset.map(
       snake_case		,							remove_columns=eval_dataset.column_names		,							batch_size=training_args.per_device_train_batch_size		,							batched=snake_case		,							num_proc=data_args.preprocessing_num_workers		,							)

   # Metric
   _lowercase      :				Optional[int]      					=       datasets.load_metric("wer"					)

   def compute_metrics(snake_case					):
      _lowercase      :				Dict      					=       pred.predictions
      _lowercase      :				int      					=       np.argmax(snake_case		,							axis=-1					)

      _lowercase      :				str      					=       processor.tokenizer.pad_token_id

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

      _lowercase      :				Optional[int]      					=       wer_metric.compute(predictions=snake_case		,							references=snake_case					)

      return {"wer": wer}

   if model_args.freeze_feature_extractor:
      model.freeze_feature_extractor()

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

   # Initialize our Trainer
   _lowercase      :				List[str]      					=       CTCTrainer(
       model=snake_case		,							data_collator=snake_case		,							args=snake_case		,							compute_metrics=snake_case		,							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      :				Tuple      					=       model_args.model_name_or_path
      else:
         _lowercase      :				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      :				str      					=       trainer.train(resume_from_checkpoint=snake_case					)
      trainer.save_model()

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

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

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

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

   return results


if __name__ == "__main__":
    main()






