


"""simple docstring"""






from __future__ import annotations

import unittest

from transformers import DebertaConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import (
					    TFDebertaForMaskedLM,
					    TFDebertaForQuestionAnswering,
					    TFDebertaForSequenceClassification,
					    TFDebertaForTokenClassification,
					    TFDebertaModel,
					)


class 			SCREAMING_SNAKE_CASE_  :




							'''simple docstring'''





							def __init__(						self	,					lowerCamelCase__	,					lowerCamelCase__=13	,					lowerCamelCase__=7	,					lowerCamelCase__=True	,					lowerCamelCase__=True	,					lowerCamelCase__=True	,					lowerCamelCase__=True	,					lowerCamelCase__=99	,					lowerCamelCase__=32	,					lowerCamelCase__=2	,					lowerCamelCase__=4	,					lowerCamelCase__=37	,					lowerCamelCase__="gelu"	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=512	,					lowerCamelCase__=16	,					lowerCamelCase__=2	,					lowerCamelCase__=0.02	,					lowerCamelCase__=3	,					lowerCamelCase__=4	,					lowerCamelCase__=None	,					)   ->	Any:







								'''simple docstring'''




								snake_case__  :						List[Any]		=      parent
								snake_case__  :						Dict		=      13
								snake_case__  :						Optional[Any]		=      7
								snake_case__  :						Union[str, Any]		=      True
								snake_case__  :						Optional[Any]		=      True
								snake_case__  :						Any		=      True
								snake_case__  :						str		=      True
								snake_case__  :						Optional[int]		=      99
								snake_case__  :						str		=      32
								snake_case__  :						Dict		=      2
								snake_case__  :						Tuple		=      4
								snake_case__  :						Any		=      37
								snake_case__  :						Dict		=      "gelu"
								snake_case__  :						Union[str, Any]		=      0.1
								snake_case__  :						Optional[Any]		=      0.1
								snake_case__  :						Dict		=      512
								snake_case__  :						str		=      16
								snake_case__  :						int		=      False
								snake_case__  :						Tuple		=      -1
								snake_case__  :						Optional[int]		=      True
								snake_case__  :						List[str]		=      2
								snake_case__  :						Optional[Any]		=      0.02
								snake_case__  :						List[Any]		=      3
								snake_case__  :						str		=      4
								snake_case__  :						Optional[int]		=      None




							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						int		=      ids_tensor([self.batch_size, self.seq_length]	,					self.vocab_size)

								snake_case__  :						List[str]		=      None
								if self.use_input_mask:
									snake_case__  :						Union[str, Any]		=      random_attention_mask([self.batch_size, self.seq_length])

								snake_case__  :						List[str]		=      None
								if self.use_token_type_ids:
									snake_case__  :						Dict		=      ids_tensor([self.batch_size, self.seq_length]	,					self.type_vocab_size)

								snake_case__  :						List[str]		=      None
								snake_case__  :						int		=      None
								snake_case__  :						int		=      None
								if self.use_labels:
									snake_case__  :						Dict		=      ids_tensor([self.batch_size]	,					self.type_sequence_label_size)
									snake_case__  :						Dict		=      ids_tensor([self.batch_size, self.seq_length]	,					self.num_labels)

								snake_case__  :						str		=      DebertaConfig(
								    vocab_size=self.vocab_size	,					hidden_size=self.hidden_size	,					num_hidden_layers=self.num_hidden_layers	,					num_attention_heads=self.num_attention_heads	,					intermediate_size=self.intermediate_size	,					hidden_act=self.hidden_act	,					hidden_dropout_prob=self.hidden_dropout_prob	,					attention_probs_dropout_prob=self.attention_probs_dropout_prob	,					max_position_embeddings=self.max_position_embeddings	,					type_vocab_size=self.type_vocab_size	,					relative_attention=self.relative_attention	,					max_relative_positions=self.max_relative_positions	,					position_biased_input=self.position_biased_input	,					initializer_range=self.initializer_range	,					return_dict=lowerCamelCase__	,					)

								return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




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







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      TFDebertaModel(config=lowerCamelCase__)
								snake_case__  :						Optional[int]		=      {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

								snake_case__  :						Any		=      [input_ids, input_mask]
								snake_case__  :						Optional[int]		=      model(lowerCamelCase__)

								snake_case__  :						Union[str, Any]		=      model(lowerCamelCase__)

								self.parent.assertEqual(result.last_hidden_state.shape	,					(self.batch_size, self.seq_length, self.hidden_size))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	int:







								'''simple docstring'''




								snake_case__  :						str		=      TFDebertaForMaskedLM(config=lowerCamelCase__)
								snake_case__  :						str		=      {
								    "input_ids": input_ids,
								    "attention_mask": input_mask,
								    "token_type_ids": token_type_ids,
								}
								snake_case__  :						List[Any]		=      model(lowerCamelCase__)
								self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.seq_length, self.vocab_size))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	int:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      self.num_labels
								snake_case__  :						Union[str, Any]		=      TFDebertaForSequenceClassification(config=lowerCamelCase__)
								snake_case__  :						List[str]		=      {
								    "input_ids": input_ids,
								    "attention_mask": input_mask,
								    "token_type_ids": token_type_ids,
								}

								snake_case__  :						Union[str, Any]		=      model(lowerCamelCase__)
								self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						List[Any]		=      self.num_labels
								snake_case__  :						str		=      TFDebertaForTokenClassification(config=lowerCamelCase__)
								snake_case__  :						Optional[int]		=      {
								    "input_ids": input_ids,
								    "attention_mask": input_mask,
								    "token_type_ids": token_type_ids,
								}
								snake_case__  :						int		=      model(lowerCamelCase__)
								self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.seq_length, self.num_labels))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Any:







								'''simple docstring'''




								snake_case__  :						str		=      TFDebertaForQuestionAnswering(config=lowerCamelCase__)
								snake_case__  :						List[str]		=      {
								    "input_ids": input_ids,
								    "attention_mask": input_mask,
								    "token_type_ids": token_type_ids,
								}

								snake_case__  :						int		=      model(lowerCamelCase__)
								self.parent.assertEqual(result.start_logits.shape	,					(self.batch_size, self.seq_length))
								self.parent.assertEqual(result.end_logits.shape	,					(self.batch_size, self.seq_length))







							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      self.prepare_config_and_inputs()
								(
								    (
								    snake_case__
								),					(
								    snake_case__
								),					(
								    snake_case__
								),					(
								    snake_case__
								),					(
								    snake_case__
								),					(
								    snake_case__
								),					(
								    snake_case__
								),					
								)  :						Any		=      config_and_inputs
								snake_case__  :						Dict		=      {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
								return config, inputs_dict


@require_tf
class 			SCREAMING_SNAKE_CASE_  (   __A	,      __A	,      unittest.TestCase):




							'''simple docstring'''





							__magic_name__					:     Any				  =  (
							    (
							        TFDebertaModel,
							        TFDebertaForMaskedLM,
							        TFDebertaForQuestionAnswering,
							        TFDebertaForSequenceClassification,
							        TFDebertaForTokenClassification,
							    )
							    if is_tf_available()
							    else ()
							)
							__magic_name__					:     List[Any]				  =  (
							    {
							        """feature-extraction""": TFDebertaModel,
							        """fill-mask""": TFDebertaForMaskedLM,
							        """question-answering""": TFDebertaForQuestionAnswering,
							        """text-classification""": TFDebertaForSequenceClassification,
							        """token-classification""": TFDebertaForTokenClassification,
							        """zero-shot""": TFDebertaForSequenceClassification,
							    }
							    if is_tf_available()
							    else {}
							)

							__magic_name__					:     Any				  =  False
							__magic_name__					:     List[Any]				  =  False




							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      TFDebertaModelTester(self)
								snake_case__  :						Any		=      ConfigTester(self	,					config_class=lowerCamelCase__	,					hidden_size=37)




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								self.config_tester.run_common_tests()




							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								snake_case__  :						List[Any]		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								snake_case__  :						int		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								snake_case__  :						str		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Tuple		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__)







							@slow
							def        UpperCAmelCase (						self)   ->	int:







								'''simple docstring'''




								snake_case__  :						int		=      TFDebertaModel.from_pretrained("kamalkraj/deberta-base")
								self.assertIsNotNone(lowerCamelCase__)


@require_tf
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





							@unittest.skip(reason="Model not available yet")
							def        UpperCAmelCase (						self)   ->	Union[str, Any]:







								'''simple docstring'''




								pass







							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Tuple		=      TFDebertaModel.from_pretrained("kamalkraj/deberta-base")
								snake_case__  :						Any		=      tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]])
								snake_case__  :						int		=      tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
								snake_case__  :						str		=      model(lowerCamelCase__	,					attention_mask=lowerCamelCase__)[0]

								snake_case__  :						List[Any]		=      tf.constant(
								    [
								        [
								            [-0.59_85_58_96, -0.80_55_25_66, -0.8_46_21_35],
								            [1.4_48_40_25, -0.93_48_37_94, -0.80_59_30_85],
								            [0.3_12_27_41, 0.00_31_60_59, -1.4_13_13_77],
								        ]
								    ])
								tf.debugging.assert_near(output[:, 1:4, 1:4]	,					lowerCamelCase__	,					atol=1E-4)











'''simple docstring'''
import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
  from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""):
  A				: Union[str, Any]					      =			True
  from torch.cuda.amp import autocast


A				: Union[str, Any]					      =			logging.getLogger(__name__)






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	str       =   field(
           metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	)
       snake_case_					:	Optional[str]       =   field(
           default=__A  , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}  , )
       snake_case_					:	Optional[bool]       =   field(
           default=__A  , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}	)
       snake_case_					:	Optional[bool]       =   field(
           default=__A  , metadata={"""help""": """Whether to log verbose messages or not."""}  , )

def 							snake_case_    (  a__						:      ModelArguments       ,a__						:      TrainingArguments     ):



    """simple docstring"""




    logging.basicConfig(
        format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""       ,datefmt="""%m/%d/%Y %H:%M:%S"""       ,handlers=[logging.StreamHandler(sys.stdout     )]       ,)
    __lowercase     							=		logging.WARNING
    if model_args.verbose_logging:
        __lowercase     							=		logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank     ):
        __lowercase     							=		logging.INFO
    logger.setLevel(a__     )






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	str       =   field(
           default=__A  , metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}	)
       snake_case_					:	Optional[str]       =   field(
           default=__A  , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}	)
       snake_case_					:	Optional[str]       =   field(
           default="""train"""  , metadata={
               """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
           }  , )
       snake_case_					:	Optional[str]       =   field(
           default="""validation"""  , metadata={
               """help""": (
                   """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"""
               )
           }  , )
       snake_case_					:	Optional[str]       =   field(
           default="""text"""  , metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}  , )
       snake_case_					:	Optional[str]       =   field(
           default="""file"""  , metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}  , )
       snake_case_					:	Optional[bool]       =   field(
           default=__A  , metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}  , )
       snake_case_					:	Optional[float]       =   field(
           default=__A  , metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}  , )
       snake_case_					:	Optional[str]       =   field(
           default="""librispeech"""  , metadata={
               """help""": (
                   """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
                   """ 'buckwalter'."""
               )
           }  , )
       snake_case_					:	bool       =   field(
           default=__A  , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}	)
       snake_case_					:	Optional[int]       =   field(
           default=__A  , metadata={"""help""": """The number of processes to use for the preprocessing."""}  , )






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	bool       =   False
       snake_case_					:	Optional[str]       =   None
       snake_case_					:	Optional[str]       =   "|"
       snake_case_					:	Optional[Dict[str, str]]       =   field(default_factory=__A	)
       snake_case_					:	Optional[Set[str]]       =   field(default_factory=__A	)
       snake_case_					:	Optional[Callable[[str], str]]       =   None

       @classmethod
       def        snake_case__     (       cls   ,						lowerCamelCase__	)       ->   Any:

           """simple docstring"""



           if name == "librispeech":
               return cls()
           if name == "timit":
               return cls(
                   do_lower_case=lowerCamelCase__   ,						translation_table=str.maketrans({"""-""": """ """}	)   ,						)
           if name == "buckwalter":
               __lowercase     							=		{
                   """-""": """ """,  # sometimes used to represent pauses
                   """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
               }
               return cls(
                   vocab_file=pathlib.Path(lowerCamelCase__	).parent.joinpath("""vocab/buckwalter.json"""	)   ,						word_delimiter_token="""/"""   ,						translation_table=str.maketrans(lowerCamelCase__	)   ,						words_to_remove={"""sil"""}   ,						untransliterator=arabic.buckwalter.untransliterate   ,						)
           raise ValueError(F'Unsupported orthography: \'{name}\'.'	)

       def        snake_case__     (       self   ,						lowerCamelCase__	)       ->   str:

           """simple docstring"""



           if len(self.translation_table	) > 0:
               __lowercase     							=		text.translate(self.translation_table	)
           if len(self.words_to_remove	) == 0:
               __lowercase     							=		""" """.join(text.split()	)  # clean up whitespaces
           else:
               __lowercase     							=		""" """.join(w for w in text.split() if w not in self.words_to_remove	)  # and clean up whilespaces
           return text




       def        snake_case__     (       self   ,						lowerCamelCase__	)       ->   WavaVecaProcessor:

           """simple docstring"""



           __lowercase     							=		WavaVecaFeatureExtractor.from_pretrained(
               model_args.model_name_or_path   ,						cache_dir=model_args.cache_dir	)
           if self.vocab_file:
               __lowercase     							=		WavaVecaCTCTokenizer(
                   self.vocab_file   ,						cache_dir=model_args.cache_dir   ,						do_lower_case=self.do_lower_case   ,						word_delimiter_token=self.word_delimiter_token   ,						)
           else:
               __lowercase     							=		WavaVecaCTCTokenizer.from_pretrained(
                   model_args.model_name_or_path   ,						cache_dir=model_args.cache_dir   ,						do_lower_case=self.do_lower_case   ,						word_delimiter_token=self.word_delimiter_token   ,						)
           return WavaVecaProcessor(lowerCamelCase__   ,						lowerCamelCase__	)






@dataclass
class 			SCREAMING_SNAKE_CASE:
       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   ,						lowerCamelCase__	)       ->   Dict[str, torch.Tensor]:

           """simple docstring"""



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

           __lowercase     							=		self.processor.pad(
               lowerCamelCase__   ,						padding=self.padding   ,						max_length=self.max_length   ,						pad_to_multiple_of=self.pad_to_multiple_of   ,						return_tensors="""pt"""   ,						)
           __lowercase     							=		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
           __lowercase     							=		labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1	)   ,						-100	)

           __lowercase     							=		labels

           return batch






class 			SCREAMING_SNAKE_CASE(							__A	):

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   torch.Tensor:

           """simple docstring"""



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

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

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



    """simple docstring"""




    __lowercase     							=		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

    __lowercase							,__lowercase							,__lowercase     							=		parser.parse_args_into_dataclasses()
    configure_logger(a__       ,a__     )

    __lowercase     							=		Orthography.from_name(data_args.orthography.lower()     )
    __lowercase     							=		orthography.create_processor(a__     )
    __lowercase     							=		WavaVecaForCTC.from_pretrained(
        model_args.model_name_or_path       ,cache_dir=model_args.cache_dir       ,gradient_checkpointing=training_args.gradient_checkpointing       ,vocab_size=len(processor.tokenizer     )       ,)

    __lowercase     							=		datasets.load_dataset(
        data_args.dataset_name       ,data_args.dataset_config_name       ,split=data_args.train_split_name     )
    __lowercase     							=		datasets.load_dataset(
        data_args.dataset_name       ,data_args.dataset_config_name       ,split=data_args.validation_split_name     )

    __lowercase     							=		datasets.load_metric("""wer"""     )
    __lowercase     							=		processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
    __lowercase     							=		"""""".join(t for t in processor.tokenizer.get_vocab().keys() if len(a__     ) == 1     )
    __lowercase     							=		re.compile(  # remove characters not in vocabulary
        rf'[^\s{re.escape(a__     )}]'       ,flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0       ,)
    __lowercase     							=		[]

    def prepare_example(a__						:      Tuple     ):  # TODO(elgeish) make use of multiprocessing?
        __lowercase							,__lowercase     							=		librosa.load(example[data_args.speech_file_column]       ,sr=a__     )
        if data_args.max_duration_in_seconds is not None:
            __lowercase     							=		len(example["""speech"""]     ) / example["""sampling_rate"""]
        # Normalize and clean up text; order matters!
        __lowercase     							=		orthography.preprocess_for_training(example[data_args.target_text_column]     )
        __lowercase     							=		vocabulary_text_cleaner.sub(""""""       ,a__     )
        if updated_text != example[data_args.target_text_column]:
            text_updates.append((example[data_args.target_text_column], updated_text)     )
            __lowercase     							=		updated_text
        return example

    __lowercase     							=		train_dataset.map(a__       ,remove_columns=[data_args.speech_file_column]     )
    __lowercase     							=		val_dataset.map(a__       ,remove_columns=[data_args.speech_file_column]     )

    if data_args.max_duration_in_seconds is not None:

        def filter_by_max_duration(a__						:      Union[str, Any]     ):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

        __lowercase     							=		len(a__     )
        __lowercase     							=		len(a__     )
        __lowercase     							=		train_dataset.filter(a__       ,remove_columns=["""duration_in_seconds"""]     )
        __lowercase     							=		val_dataset.filter(a__       ,remove_columns=["""duration_in_seconds"""]     )
        if len(a__     ) > old_train_size:
            logger.warning(
                f'Filtered out {len(a__     ) - old_train_size} train example(s) longer than'
                f' {data_args.max_duration_in_seconds} second(s).'     )
        if len(a__     ) > old_val_size:
            logger.warning(
                f'Filtered out {len(a__     ) - old_val_size} validation example(s) longer than'
                f' {data_args.max_duration_in_seconds} second(s).'     )
    logger.info(f'Split sizes: {len(a__     )} train and {len(a__     )} validation.'     )

    logger.warning(f'Updated {len(a__     )} transcript(s) using \'{data_args.orthography}\' orthography rules.'     )
    if logger.isEnabledFor(logging.DEBUG     ):
        for original_text, updated_text in text_updates:
            logger.debug(f'Updated text: "{original_text}" -> "{updated_text}"'     )
    __lowercase     							=		None

    def prepare_dataset(a__						:      Optional[Any]     ):
        # 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     							=		processor(
            audio=batch["""speech"""]       ,text=batch[data_args.target_text_column]       ,sampling_rate=batch["""sampling_rate"""][0]     )
        batch.update(a__     )
        return batch

    __lowercase     							=		train_dataset.map(
        a__       ,batch_size=training_args.per_device_train_batch_size       ,batched=a__       ,num_proc=data_args.preprocessing_num_workers       ,)
    __lowercase     							=		val_dataset.map(
        a__       ,batch_size=training_args.per_device_train_batch_size       ,batched=a__       ,num_proc=data_args.preprocessing_num_workers       ,)

    __lowercase     							=		DataCollatorCTCWithPadding(processor=a__       ,padding=a__     )

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

        __lowercase     							=		processor.tokenizer.pad_token_id

        __lowercase     							=		processor.batch_decode(a__     )
        # we do not want to group tokens when computing the metrics
        __lowercase     							=		processor.batch_decode(pred.label_ids       ,group_tokens=a__     )
        if logger.isEnabledFor(logging.DEBUG     ):
            for reference, predicted in zip(a__       ,a__     ):
                logger.debug(f'reference: "{reference}"'     )
                logger.debug(f'predicted: "{predicted}"'     )
                if orthography.untransliterator is not None:
                    logger.debug(f'reference (untransliterated): "{orthography.untransliterator(a__     )}"'     )
                    logger.debug(f'predicted (untransliterated): "{orthography.untransliterator(a__     )}"'     )

        __lowercase     							=		wer_metric.compute(predictions=a__       ,references=a__     )

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    __lowercase     							=		CTCTrainer(
        model=a__       ,data_collator=a__       ,args=a__       ,compute_metrics=a__       ,train_dataset=a__       ,eval_dataset=a__       ,tokenizer=processor.feature_extractor       ,)

    trainer.train()


if __name__ == "__main__":
  main()




