





'''simple docstring'''





from abc import ABC, abstractmethod
from typing import List, Optional

class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def __init__(							self		:					Tuple )  ->	List[Any]:




           '''simple docstring'''


           self.test()






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		0
           SCREAMING_SNAKE_CASE	=		False
           while not completed:
                 if counter == 1:
                       self.reset()
                 SCREAMING_SNAKE_CASE	=		self.advance()
                 if not self.does_advance(lowerCamelCase__ ):
                       raise Exception(
                           """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.""" )

                 SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.update(lowerCamelCase__ )
                 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        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	Optional[Any]:




           '''simple docstring'''


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






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int]		,lowerCamelCase__		:					int )  ->	Optional[Any]:




           '''simple docstring'''


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






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__						(							self		:					str		,lowerCamelCase__		:					int )  ->	List[Any]:




           '''simple docstring'''


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






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	Optional[Any]:




           '''simple docstring'''


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






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	Dict:




           '''simple docstring'''


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






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					Dict=False )  ->	str:




           '''simple docstring'''


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

class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def __init__(							self		:					List[Any]		,lowerCamelCase__		:					List[int] )  ->	List[Any]:




           '''simple docstring'''


           super(lowerCamelCase__		,self ).__init__()

           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ) or len(lowerCamelCase__ ) == 0:
                 raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""" )
           if any((not isinstance(lowerCamelCase__		,lowerCamelCase__ ) 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}.""" )

           SCREAMING_SNAKE_CASE	=		token_ids

           SCREAMING_SNAKE_CASE	=		len(self.token_ids )
           SCREAMING_SNAKE_CASE	=		-1  # the index of the currently fulfilled step
           SCREAMING_SNAKE_CASE	=		False






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	Optional[Any]:




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					int		,lowerCamelCase__		:					int )  ->	List[Any]:




           '''simple docstring'''


           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ):
                 raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(lowerCamelCase__ )}""" )

           if self.completed:
                 return False

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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any]		,lowerCamelCase__		:					int )  ->	Optional[Any]:




           '''simple docstring'''


           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ):
                 raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(lowerCamelCase__ )}""" )

           SCREAMING_SNAKE_CASE	=		False
           SCREAMING_SNAKE_CASE	=		False
           SCREAMING_SNAKE_CASE	=		False

           if self.does_advance(lowerCamelCase__ ):
                 self.fulfilled_idx += 1
                 SCREAMING_SNAKE_CASE	=		True
                 if self.fulfilled_idx == (self.seqlen - 1):
                       SCREAMING_SNAKE_CASE	=		True
                 SCREAMING_SNAKE_CASE	=		completed
           else:
                 # failed to make progress.
                 SCREAMING_SNAKE_CASE	=		True
                 self.reset()
           return stepped, completed, reset






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		False
           SCREAMING_SNAKE_CASE	=		0






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Optional[Any]:




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any]		,lowerCamelCase__		:					List[str]=False )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		PhrasalConstraint(self.token_ids )

           if stateful:
                 SCREAMING_SNAKE_CASE	=		self.seqlen
                 SCREAMING_SNAKE_CASE	=		self.fulfilled_idx
                 SCREAMING_SNAKE_CASE	=		self.completed

           return new_constraint

class 	UpperCamelCase__				:



     '''simple docstring'''

     def __init__(							self		:					Any		,lowerCamelCase__		:					List[List[int]]		,lowerCamelCase__		:					Dict=True )  ->	Dict:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		max([len(lowerCamelCase__ ) for one in nested_token_ids] )

           SCREAMING_SNAKE_CASE	=		{}
           for token_ids in nested_token_ids:
                 SCREAMING_SNAKE_CASE	=		root
                 for tidx, token_id in enumerate(lowerCamelCase__ ):
                       if token_id not in level:
                             SCREAMING_SNAKE_CASE	=		{}

                       SCREAMING_SNAKE_CASE	=		level[token_id]

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

           SCREAMING_SNAKE_CASE	=		root






     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any]		,lowerCamelCase__		:					Union[str, Any] )  ->	Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.trie

           for current_token in current_seq:
                 SCREAMING_SNAKE_CASE	=		start[current_token]

           SCREAMING_SNAKE_CASE	=		list(start.keys() )

           return next_tokens






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any]		,lowerCamelCase__		:					int )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.next_tokens(lowerCamelCase__ )

           return len(lowerCamelCase__ ) == 0






     def        SCREAMING_SNAKE_CASE__						(							self		:					int		,lowerCamelCase__		:					List[Any] )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		list(root.values() )
           if len(lowerCamelCase__ ) == 0:
                 return 1
           else:
                 return sum([self.count_leaves(lowerCamelCase__ ) for nn in next_nodes] )






     def        SCREAMING_SNAKE_CASE__						(							self		:					Any		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					Dict )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.count_leaves(lowerCamelCase__ )
           return len(lowerCamelCase__ ) != leaf_count

class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def __init__(							self		:					str		,lowerCamelCase__		:					List[List[int]] )  ->	Optional[int]:




           '''simple docstring'''


           super(lowerCamelCase__		,self ).__init__()

           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ) or len(lowerCamelCase__ ) == 0:
                 raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" )
           if any(not isinstance(lowerCamelCase__		,lowerCamelCase__ ) 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(lowerCamelCase__		,lowerCamelCase__ ) 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}.""" )

           SCREAMING_SNAKE_CASE	=		DisjunctiveTrie(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		nested_token_ids

           SCREAMING_SNAKE_CASE	=		self.trie.max_height
           SCREAMING_SNAKE_CASE	=		[]
           SCREAMING_SNAKE_CASE	=		False






     def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.trie.next_tokens(self.current_seq )

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






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					int )  ->	int:




           '''simple docstring'''


           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ):
                 raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCamelCase__ )}""" )

           SCREAMING_SNAKE_CASE	=		self.trie.next_tokens(self.current_seq )

           return token_id in next_tokens






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					int )  ->	Tuple:




           '''simple docstring'''


           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ):
                 raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCamelCase__ )}""" )

           SCREAMING_SNAKE_CASE	=		False
           SCREAMING_SNAKE_CASE	=		False
           SCREAMING_SNAKE_CASE	=		False

           if self.does_advance(lowerCamelCase__ ):
                 self.current_seq.append(lowerCamelCase__ )
                 SCREAMING_SNAKE_CASE	=		True
           else:
                 SCREAMING_SNAKE_CASE	=		True
                 self.reset()

           SCREAMING_SNAKE_CASE	=		self.trie.reached_leaf(self.current_seq )
           SCREAMING_SNAKE_CASE	=		completed

           return stepped, completed, reset






     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any] )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		False
           SCREAMING_SNAKE_CASE	=		[]






     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	Tuple:




           '''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        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					List[Any]=False )  ->	Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		DisjunctiveConstraint(self.token_ids )

           if stateful:
                 SCREAMING_SNAKE_CASE	=		self.seqlen
                 SCREAMING_SNAKE_CASE	=		self.current_seq
                 SCREAMING_SNAKE_CASE	=		self.completed

           return new_constraint

class 	UpperCamelCase__				:



     '''simple docstring'''

     def __init__(							self		:					Union[str, Any]		,lowerCamelCase__		:					List[Constraint] )  ->	Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		constraints

           # max # of steps required to fulfill a given constraint
           SCREAMING_SNAKE_CASE	=		max([c.seqlen for c in constraints] )
           SCREAMING_SNAKE_CASE	=		len(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		False

           self.init_state()






     def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		[]
           SCREAMING_SNAKE_CASE	=		None
           SCREAMING_SNAKE_CASE	=		[constraint.copy(stateful=lowerCamelCase__ ) for constraint in self.constraints]






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		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        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	List[str]:




           '''simple docstring'''


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

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






     def        SCREAMING_SNAKE_CASE__						(							self		:					str		,lowerCamelCase__		:					Optional[List[int]] )  ->	Union[str, Any]:




           '''simple docstring'''


           self.init_state()

           if token_ids is not None:
                 for token in token_ids:
                       # completes or steps **one** constraint
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.add(lowerCamelCase__ )

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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int]		,lowerCamelCase__		:					int )  ->	Optional[int]:




           '''simple docstring'''


           if not isinstance(lowerCamelCase__		,lowerCamelCase__ ):
                 raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""" )

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		False, False

           if self.completed:
                 SCREAMING_SNAKE_CASE	=		True
                 SCREAMING_SNAKE_CASE	=		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

                 SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.inprogress_constraint.update(lowerCamelCase__ )
                 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=lowerCamelCase__ ) )
                       SCREAMING_SNAKE_CASE	=		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 )
                       SCREAMING_SNAKE_CASE	=		None

                       if len(self.pending_constraints ) == 0:
                             # we're done!
                             SCREAMING_SNAKE_CASE	=		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(lowerCamelCase__ ):
                             SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		pending_constraint.update(lowerCamelCase__ )

                             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(lowerCamelCase__ )
                                   SCREAMING_SNAKE_CASE	=		None

                             if not complete and stepped:
                                   SCREAMING_SNAKE_CASE	=		pending_constraint

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

                                   SCREAMING_SNAKE_CASE	=		(
                                       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.

                                         SCREAMING_SNAKE_CASE	=		True

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

           return complete, stepped






     def        SCREAMING_SNAKE_CASE__						(							self		:					str		,lowerCamelCase__		:					List[Any]=True )  ->	int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		ConstraintListState(self.constraints )  # we actually never though self.constraints objects
           # throughout this process. So it's at initialization state.

           if stateful:
                 SCREAMING_SNAKE_CASE	=		[
                     constraint.copy(stateful=lowerCamelCase__ ) for constraint in self.complete_constraints
                 ]
                 if self.inprogress_constraint is not None:
                       SCREAMING_SNAKE_CASE	=		self.inprogress_constraint.copy(stateful=lowerCamelCase__ )
                 SCREAMING_SNAKE_CASE	=		[constraint.copy() for constraint in self.pending_constraints]

           return new_state









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

SCREAMING_SNAKE_CASE_		     = logging.getLogger(__name__)



def      __lowercase     (   _SCREAMING_SNAKE_CASE=None				,		_SCREAMING_SNAKE_CASE=None			)				->     int:


      '''simple docstring'''


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

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

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

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

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

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

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






     def __call__(							self		:					Any		,lowerCamelCase__		:					List[Dict[str, Union[List[int], torch.Tensor]]] )  ->	Dict[str, torch.Tensor]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		[{"""input_values""": feature["""input_values"""]} for feature in features]
           SCREAMING_SNAKE_CASE	=		[{"""input_ids""": feature["""labels"""]} for feature in features]

           SCREAMING_SNAKE_CASE	=		self.processor.pad(
               lowerCamelCase__		,padding=self.padding		,max_length=self.max_length		,pad_to_multiple_of=self.pad_to_multiple_of		,return_tensors="""pt"""		,)
           SCREAMING_SNAKE_CASE	=		self.processor.pad(
               labels=lowerCamelCase__		,padding=self.padding		,max_length=self.max_length_labels		,pad_to_multiple_of=self.pad_to_multiple_of_labels		,return_tensors="""pt"""		,)

           # replace padding with -100 to ignore loss correctly
           SCREAMING_SNAKE_CASE	=		labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1 )		,-100 )

           SCREAMING_SNAKE_CASE	=		labels

           return batch

class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					nn.Module		,lowerCamelCase__		:					Dict[str, Union[torch.Tensor, Any]] )  ->	torch.Tensor:




           '''simple docstring'''


           model.train()
           SCREAMING_SNAKE_CASE	=		self._prepare_inputs(lowerCamelCase__ )

           if self.use_amp:
                 with autocast():
                       SCREAMING_SNAKE_CASE	=		self.compute_loss(lowerCamelCase__		,lowerCamelCase__ )
           else:
                 SCREAMING_SNAKE_CASE	=		self.compute_loss(lowerCamelCase__		,lowerCamelCase__ )

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

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

           return loss.detach()



def      __lowercase     (   )				->     Tuple:


      '''simple docstring'''


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

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

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

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

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

      def remove_special_characters(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		re.sub(_SCREAMING_SNAKE_CASE				,		""""""				,		batch["""sentence"""]			).lower() + """ """
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(_SCREAMING_SNAKE_CASE				,		remove_columns=["""sentence"""]			)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(_SCREAMING_SNAKE_CASE				,		remove_columns=["""sentence"""]			)

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

      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		batched=_SCREAMING_SNAKE_CASE				,		batch_size=-1				,		keep_in_memory=_SCREAMING_SNAKE_CASE				,		remove_columns=train_dataset.column_names				,		)
      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		batched=_SCREAMING_SNAKE_CASE				,		batch_size=-1				,		keep_in_memory=_SCREAMING_SNAKE_CASE				,		remove_columns=eval_dataset.column_names				,		)

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

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

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

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

      SCREAMING_SNAKE_CASE	=		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(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		torchaudio.load(batch["""path"""]			)
            SCREAMING_SNAKE_CASE	=		resampler(_SCREAMING_SNAKE_CASE			).squeeze().numpy()
            SCREAMING_SNAKE_CASE	=		1_60_00
            SCREAMING_SNAKE_CASE	=		batch["""text"""]
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=train_dataset.column_names				,		num_proc=data_args.preprocessing_num_workers				,		)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=eval_dataset.column_names				,		num_proc=data_args.preprocessing_num_workers				,		)

      def prepare_dataset(_SCREAMING_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}."""

            SCREAMING_SNAKE_CASE	=		processor(
                audio=batch["""speech"""]				,		text=batch["""target_text"""]				,		sampling_rate=batch["""sampling_rate"""][0]			)
            batch.update(_SCREAMING_SNAKE_CASE			)
            return batch

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

      # Metric
      SCREAMING_SNAKE_CASE	=		datasets.load_metric("""wer"""			)

      def compute_metrics(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		pred.predictions
            SCREAMING_SNAKE_CASE	=		np.argmax(_SCREAMING_SNAKE_CASE				,		axis=-1			)

            SCREAMING_SNAKE_CASE	=		processor.tokenizer.pad_token_id

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

            SCREAMING_SNAKE_CASE	=		wer_metric.compute(predictions=_SCREAMING_SNAKE_CASE				,		references=_SCREAMING_SNAKE_CASE			)

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      SCREAMING_SNAKE_CASE	=		DataCollatorCTCWithPadding(processor=_SCREAMING_SNAKE_CASE				,		padding=_SCREAMING_SNAKE_CASE			)

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

            SCREAMING_SNAKE_CASE	=		trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE			)
            trainer.save_model()

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

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

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

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

      return results


if __name__ == "__main__":
      main()


