

import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
       import os

       # The slow tests are often failing with OOM error on GPU
       # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
       # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
       UpperCamelCase__	:   List[Any]								=     "platform"

       import jax
       import jax.numpy as jnp

       from transformers import MarianTokenizer
       from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right


def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		Any			, _SCREAMING_SNAKE_CASE       :		Optional[int]			, _SCREAMING_SNAKE_CASE       :		Tuple=None			, _SCREAMING_SNAKE_CASE       :		Tuple=None			, _SCREAMING_SNAKE_CASE       :		str=None			, _SCREAMING_SNAKE_CASE       :		str=None			, _SCREAMING_SNAKE_CASE       :		Tuple=None			, _SCREAMING_SNAKE_CASE       :		Union[str, Any]=None			, ):





    """simple docstring"""


    if attention_mask is None:
        SCREAMING_SNAKE_CASE_						=    np.where(input_ids != config.pad_token_id			, 1			, 0							)
    if decoder_attention_mask is None:
        SCREAMING_SNAKE_CASE_						=    np.where(decoder_input_ids != config.pad_token_id			, 1			, 0							)
    if head_mask is None:
        SCREAMING_SNAKE_CASE_						=    np.ones((config.encoder_layers, config.encoder_attention_heads)							)
    if decoder_head_mask is None:
        SCREAMING_SNAKE_CASE_						=    np.ones((config.decoder_layers, config.decoder_attention_heads)							)
    if cross_attn_head_mask is None:
        SCREAMING_SNAKE_CASE_						=    np.ones((config.decoder_layers, config.decoder_attention_heads)							)
    return {
        "input_ids": input_ids,
        "decoder_input_ids": decoder_input_ids,
        "attention_mask": attention_mask,
        "decoder_attention_mask": attention_mask,
    }



class    __snake_case	:

  def __init__(       self    ,		_A    ,		_A=13    ,		_A=7    ,		_A=True    ,		_A=False    ,		_A=99    ,		_A=16    ,		_A=2    ,		_A=4    ,		_A=4    ,		_A="gelu"    ,		_A=0.1    ,		_A=0.1    ,		_A=32    ,		_A=2    ,		_A=1    ,		_A=0    ,		_A=0.0_2    ,		):
      SCREAMING_SNAKE_CASE_						=    parent
      SCREAMING_SNAKE_CASE_						=    batch_size
      SCREAMING_SNAKE_CASE_						=    seq_length
      SCREAMING_SNAKE_CASE_						=    is_training
      SCREAMING_SNAKE_CASE_						=    use_labels
      SCREAMING_SNAKE_CASE_						=    vocab_size
      SCREAMING_SNAKE_CASE_						=    hidden_size
      SCREAMING_SNAKE_CASE_						=    num_hidden_layers
      SCREAMING_SNAKE_CASE_						=    num_attention_heads
      SCREAMING_SNAKE_CASE_						=    intermediate_size
      SCREAMING_SNAKE_CASE_						=    hidden_act
      SCREAMING_SNAKE_CASE_						=    hidden_dropout_prob
      SCREAMING_SNAKE_CASE_						=    attention_probs_dropout_prob
      SCREAMING_SNAKE_CASE_						=    max_position_embeddings
      SCREAMING_SNAKE_CASE_						=    eos_token_id
      SCREAMING_SNAKE_CASE_						=    pad_token_id
      SCREAMING_SNAKE_CASE_						=    bos_token_id
      SCREAMING_SNAKE_CASE_						=    initializer_range

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    np.clip(ids_tensor([self.batch_size, self.seq_length - 1]    ,		self.vocab_size)    ,		3    ,		self.vocab_size)
      SCREAMING_SNAKE_CASE_						=    np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)    ,		dtype=np.intaa))    ,		-1)

      SCREAMING_SNAKE_CASE_						=    shift_tokens_right(_A    ,		1    ,		2)

      SCREAMING_SNAKE_CASE_						=    MarianConfig(
          vocab_size=self.vocab_size    ,		d_model=self.hidden_size    ,		encoder_layers=self.num_hidden_layers    ,		decoder_layers=self.num_hidden_layers    ,		encoder_attention_heads=self.num_attention_heads    ,		decoder_attention_heads=self.num_attention_heads    ,		encoder_ffn_dim=self.intermediate_size    ,		decoder_ffn_dim=self.intermediate_size    ,		dropout=self.hidden_dropout_prob    ,		attention_dropout=self.attention_probs_dropout_prob    ,		max_position_embeddings=self.max_position_embeddings    ,		eos_token_id=self.eos_token_id    ,		bos_token_id=self.bos_token_id    ,		pad_token_id=self.pad_token_id    ,		initializer_range=self.initializer_range    ,		use_cache=_A    ,		)
      SCREAMING_SNAKE_CASE_						=    prepare_marian_inputs_dict(_A    ,		_A    ,		_A)
      return config, inputs_dict

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self.prepare_config_and_inputs()
      return config, inputs_dict

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A    ,		_A):
      SCREAMING_SNAKE_CASE_						=    20
      SCREAMING_SNAKE_CASE_						=    model_class_name(_A)

      SCREAMING_SNAKE_CASE_						=    model.encode(inputs_dict['input_ids'])

      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    (
          inputs_dict['decoder_input_ids'],
          inputs_dict['decoder_attention_mask'],
      )

      SCREAMING_SNAKE_CASE_						=    model.init_cache(decoder_input_ids.shape[0]    ,		_A    ,		_A)
      SCREAMING_SNAKE_CASE_						=    jnp.ones((decoder_input_ids.shape[0], max_decoder_length)    ,		dtype='i4')

      SCREAMING_SNAKE_CASE_						=    jnp.broadcast_to(
          jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :]    ,		(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)    ,		)
      SCREAMING_SNAKE_CASE_						=    model.decode(
          decoder_input_ids[:, :-1]    ,		_A    ,		decoder_attention_mask=_A    ,		past_key_values=_A    ,		decoder_position_ids=_A    ,		)

      SCREAMING_SNAKE_CASE_						=    jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]    ,		dtype='i4')
      SCREAMING_SNAKE_CASE_						=    model.decode(
          decoder_input_ids[:, -1:]    ,		_A    ,		decoder_attention_mask=_A    ,		past_key_values=outputs_cache.past_key_values    ,		decoder_position_ids=_A    ,		)

      SCREAMING_SNAKE_CASE_						=    model.decode(_A    ,		_A)

      SCREAMING_SNAKE_CASE_						=    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
      self.parent.assertTrue(diff < 1E-3    ,		msg=f"""Max diff is {diff}""")


  def     lowerCAmelCase__  (       self    ,		_A    ,		_A    ,		_A):
      SCREAMING_SNAKE_CASE_						=    20
      SCREAMING_SNAKE_CASE_						=    model_class_name(_A)

      SCREAMING_SNAKE_CASE_						=    model.encode(inputs_dict['input_ids'])

      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    (
          inputs_dict['decoder_input_ids'],
          inputs_dict['decoder_attention_mask'],
      )

      SCREAMING_SNAKE_CASE_						=    jnp.concatenate(
          [
              decoder_attention_mask,
              jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])),
          ]    ,		axis=-1    ,		)

      SCREAMING_SNAKE_CASE_						=    model.init_cache(decoder_input_ids.shape[0]    ,		_A    ,		_A)
      SCREAMING_SNAKE_CASE_						=    jnp.broadcast_to(
          jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :]    ,		(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)    ,		)

      SCREAMING_SNAKE_CASE_						=    model.decode(
          decoder_input_ids[:, :-1]    ,		_A    ,		decoder_attention_mask=_A    ,		past_key_values=_A    ,		decoder_position_ids=_A    ,		)
      SCREAMING_SNAKE_CASE_						=    jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]    ,		dtype='i4')
      SCREAMING_SNAKE_CASE_						=    model.decode(
          decoder_input_ids[:, -1:]    ,		_A    ,		past_key_values=outputs_cache.past_key_values    ,		decoder_attention_mask=_A    ,		decoder_position_ids=_A    ,		)

      SCREAMING_SNAKE_CASE_						=    model.decode(_A    ,		_A    ,		decoder_attention_mask=_A)

      SCREAMING_SNAKE_CASE_						=    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
      self.parent.assertTrue(diff < 1E-3    ,		msg=f"""Max diff is {diff}""")






@require_flax
class    __snake_case	(     lowerCAmelCase__  ,			unittest.TestCase  ,			lowerCAmelCase__							):
  __lowerCAmelCase  :						Any    			=	True
  __lowerCAmelCase  :						Dict    			=	(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
  __lowerCAmelCase  :						Optional[int]    			=	(FlaxMarianMTModel,) if is_flax_available() else ()

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    FlaxMarianModelTester(self)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self.model_tester.prepare_config_and_inputs()
      for model_class in self.all_model_classes:
          self.model_tester.check_use_cache_forward(_A    ,		_A    ,		_A)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self.model_tester.prepare_config_and_inputs()
      for model_class in self.all_model_classes:
          self.model_tester.check_use_cache_forward_with_attn_mask(_A    ,		_A    ,		_A)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          with self.subTest(model_class.__name__):
              SCREAMING_SNAKE_CASE_						=    self._prepare_for_class(_A    ,		_A)
              SCREAMING_SNAKE_CASE_						=    model_class(_A)

              @jax.jit
              def encode_jitted(_A    ,		_A=None    ,		**_A):
                  return model.encode(input_ids=_A    ,		attention_mask=_A)

              with self.subTest('JIT Enabled'):
                  SCREAMING_SNAKE_CASE_						=    encode_jitted(**_A).to_tuple()

              with self.subTest('JIT Disabled'):
                  with jax.disable_jit():
                      SCREAMING_SNAKE_CASE_						=    encode_jitted(**_A).to_tuple()

              self.assertEqual(len(_A)    ,		len(_A))
              for jitted_output, output in zip(_A    ,		_A):
                  self.assertEqual(jitted_output.shape    ,		output.shape)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          with self.subTest(model_class.__name__):
              SCREAMING_SNAKE_CASE_						=    model_class(_A)
              SCREAMING_SNAKE_CASE_						=    model.encode(inputs_dict['input_ids']    ,		inputs_dict['attention_mask'])

              SCREAMING_SNAKE_CASE_						=    {
                  'decoder_input_ids': inputs_dict['decoder_input_ids'],
                  'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
                  'encoder_outputs': encoder_outputs,
              }

              @jax.jit
              def decode_jitted(_A    ,		_A    ,		_A):
                  return model.decode(
                      decoder_input_ids=_A    ,		decoder_attention_mask=_A    ,		encoder_outputs=_A    ,		)

              with self.subTest('JIT Enabled'):
                  SCREAMING_SNAKE_CASE_						=    decode_jitted(**_A).to_tuple()

              with self.subTest('JIT Disabled'):
                  with jax.disable_jit():
                      SCREAMING_SNAKE_CASE_						=    decode_jitted(**_A).to_tuple()

              self.assertEqual(len(_A)    ,		len(_A))
              for jitted_output, output in zip(_A    ,		_A):
                  self.assertEqual(jitted_output.shape    ,		output.shape)


  @slow
  def     lowerCAmelCase__  (       self):
      for model_class_name in self.all_model_classes:
          SCREAMING_SNAKE_CASE_						=    model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de')
          # FlaxMarianForSequenceClassification expects eos token in input_ids
          SCREAMING_SNAKE_CASE_						=    np.ones((1, 1)) * model.config.eos_token_id
          SCREAMING_SNAKE_CASE_						=    model(_A)
          self.assertIsNotNone(_A)






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     unittest.TestCase							):
  __lowerCAmelCase  :						Tuple    			=	None
  __lowerCAmelCase  :						List[Any]    			=	None

  @classmethod
  def     lowerCAmelCase__  (       cls):
      SCREAMING_SNAKE_CASE_						=    f"""Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"""
      return cls

  @cached_property
  def     lowerCAmelCase__  (       self):
      return MarianTokenizer.from_pretrained(self.model_name)

  @property
  def     lowerCAmelCase__  (       self):
      return self.tokenizer.eos_token_id

  @cached_property
  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    FlaxMarianMTModel.from_pretrained(self.model_name)
      self.assertEqual(model.config.decoder_start_token_id    ,		model.config.pad_token_id)
      return model

  def     lowerCAmelCase__  (       self    ,		**_A):
      SCREAMING_SNAKE_CASE_						=    self.translate_src_text(**_A)
      self.assertListEqual(self.expected_text    ,		_A)


  def     lowerCAmelCase__  (       self    ,		**_A):
      SCREAMING_SNAKE_CASE_						=    self.tokenizer(self.src_text    ,		padding=_A    ,		return_tensors='np'    ,		**_A)
      SCREAMING_SNAKE_CASE_						=    self.model.generate(
          model_inputs.input_ids    ,		attention_mask=model_inputs.attention_mask    ,		num_beams=2    ,		max_length=128    ,		).sequences
      SCREAMING_SNAKE_CASE_						=    self.tokenizer.batch_decode(_A    ,		skip_special_tokens=_A)
      return generated_words






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Any    			=	'en'
  __lowerCAmelCase  :						str    			=	'fr'
  __lowerCAmelCase  :						Tuple    			=	[
      'I am a small frog.',
      'Now I can forget the 100 words of german that I know.',
  ]
  __lowerCAmelCase  :						Union[str, Any]    			=	[
      'Je suis une petite grenouille.',
      'Maintenant, je peux oublier les 100 mots d\'allemand que je connais.',
  ]

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						List[Any]    			=	'fr'
  __lowerCAmelCase  :						List[Any]    			=	'en'
  __lowerCAmelCase  :						str    			=	[
      'Donnez moi le micro.',
      'Tom et Mary étaient assis à une table.',  # Accents
  ]
  __lowerCAmelCase  :						Dict    			=	[
      'Give me the microphone.',
      'Tom and Mary were sitting at a table.',
  ]

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Any    			=	'mt'
  __lowerCAmelCase  :						int    			=	'en'
  __lowerCAmelCase  :						Optional[int]    			=	['Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.']
  __lowerCAmelCase  :						List[Any]    			=	['Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.']

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Any    			=	'en'
  __lowerCAmelCase  :						List[Any]    			=	'de'
  __lowerCAmelCase  :						Optional[int]    			=	[
      'I am a small frog.',
      'Now I can forget the 100 words of german that I know.',
      'Tom asked his teacher for advice.',
      'That\'s how I would do it.',
      'Tom really admired Mary\'s courage.',
      'Turn around and close your eyes.',
  ]
  __lowerCAmelCase  :						Optional[int]    			=	[
      'Ich bin ein kleiner Frosch.',
      'Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.',
      'Tom bat seinen Lehrer um Rat.',
      'So würde ich das machen.',
      'Tom bewunderte Marias Mut wirklich.',
      'Drehen Sie sich um und schließen Sie die Augen.',
  ]

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Dict    			=	'en'
  __lowerCAmelCase  :						Union[str, Any]    			=	'zh'
  __lowerCAmelCase  :						str    			=	['My name is Wolfgang and I live in Berlin']
  __lowerCAmelCase  :						Union[str, Any]    			=	['我叫沃尔夫冈 我住在柏林']

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Optional[int]    			=	'ru'
  __lowerCAmelCase  :						str    			=	'fr'
  __lowerCAmelCase  :						Tuple    			=	['Он показал мне рукопись своей новой пьесы.']
  __lowerCAmelCase  :						List[str]    			=	['Il m\'a montré le manuscrit de sa nouvelle pièce.']

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Tuple    			=	'en'
  __lowerCAmelCase  :						Dict    			=	'ROMANCE'
  __lowerCAmelCase  :						Dict    			=	[
      '>>fr<< Don\'t spend so much time watching TV.',
      '>>pt<< Your message has been sent.',
      '>>es<< He\'s two years older than me.',
  ]
  __lowerCAmelCase  :						List[Any]    			=	[
      'Ne passez pas autant de temps à regarder la télé.',
      'A sua mensagem foi enviada.',
      'Es dos años más viejo que yo.',
  ]

  @slow
  def     lowerCAmelCase__  (       self):
      self._assert_generated_batch_equal_expected()





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


UpperCamelCase__	:   Tuple								=     logging.getLogger(__name__)



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






def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		ModelArguments			, _SCREAMING_SNAKE_CASE       :		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							)]			, )
    SCREAMING_SNAKE_CASE_						=    logging.WARNING
    if model_args.verbose_logging:
        SCREAMING_SNAKE_CASE_						=    logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank							):
        SCREAMING_SNAKE_CASE_						=    logging.INFO
    logger.setLevel(_SCREAMING_SNAKE_CASE							)



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






@dataclass
class    __snake_case	:
  __lowerCAmelCase  :						bool    			=	False
  __lowerCAmelCase  :						Optional[str]    			=	None
  __lowerCAmelCase  :						Optional[str]    			=	"|"
  __lowerCAmelCase  :						Optional[Dict[str, str]]    			=	field(default_factory=lowerCAmelCase__							)
  __lowerCAmelCase  :						Optional[Set[str]]    			=	field(default_factory=lowerCAmelCase__							)
  __lowerCAmelCase  :						Optional[Callable[[str], str]]    			=	None

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

  def     lowerCAmelCase__  (       self    ,		_A):
      # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
      if len(self.translation_table) > 0:
          SCREAMING_SNAKE_CASE_						=    text.translate(self.translation_table)
      if len(self.words_to_remove) == 0:
          SCREAMING_SNAKE_CASE_						=    ' '.join(text.split())  # clean up whitespaces
      else:
          SCREAMING_SNAKE_CASE_						=    ' '.join(w for w in text.split() if w not in self.words_to_remove)  # and clean up whilespaces
      return text


  def     lowerCAmelCase__  (       self    ,		_A):
      SCREAMING_SNAKE_CASE_						=    WavaVecaFeatureExtractor.from_pretrained(
          model_args.model_name_or_path    ,		cache_dir=model_args.cache_dir)
      if self.vocab_file:
          SCREAMING_SNAKE_CASE_						=    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:
          SCREAMING_SNAKE_CASE_						=    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(_A    ,		_A)






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

  def __call__(       self    ,		_A):
      # split inputs and labels since they have to be of different lenghts and need
      # different padding methods
      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(
          _A    ,		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=_A    ,		padding=self.padding    ,		max_length=self.max_length_labels    ,		pad_to_multiple_of=self.pad_to_multiple_of_labels    ,		return_tensors='pt'    ,		)

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

      SCREAMING_SNAKE_CASE_						=    labels

      return batch






class    __snake_case	(     lowerCAmelCase__							):

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A):
      model.train()
      SCREAMING_SNAKE_CASE_						=    self._prepare_inputs(_A)

      if self.use_amp:
          with autocast():
              SCREAMING_SNAKE_CASE_						=    self.compute_loss(_A    ,		_A)
      else:
          SCREAMING_SNAKE_CASE_						=    self.compute_loss(_A    ,		_A)

      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(_A).backward()
      elif self.use_apex:
          with amp.scale_loss(_A    ,		self.optimizer) as scaled_loss:
              scaled_loss.backward()
      elif self.deepspeed:
          self.deepspeed.backward(_A)
      else:
          loss.backward()

      return loss.detach()






def        _UpperCAmelCase							(	):





    """simple docstring"""


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

    SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    parser.parse_args_into_dataclasses()
    configure_logger(_SCREAMING_SNAKE_CASE			, _SCREAMING_SNAKE_CASE							)

    SCREAMING_SNAKE_CASE_						=    Orthography.from_name(data_args.orthography.lower()							)
    SCREAMING_SNAKE_CASE_						=    orthography.create_processor(_SCREAMING_SNAKE_CASE							)
    SCREAMING_SNAKE_CASE_						=    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							)			, )

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

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

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

    SCREAMING_SNAKE_CASE_						=    train_dataset.map(_SCREAMING_SNAKE_CASE			, remove_columns=[data_args.speech_file_column]							)
    SCREAMING_SNAKE_CASE_						=    val_dataset.map(_SCREAMING_SNAKE_CASE			, remove_columns=[data_args.speech_file_column]							)

    if data_args.max_duration_in_seconds is not None:

        def filter_by_max_duration(_SCREAMING_SNAKE_CASE       :		Tuple							):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

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

    logger.warning(f"""Updated {len(_SCREAMING_SNAKE_CASE							)} 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}\""""							)
    SCREAMING_SNAKE_CASE_						=    None

    def prepare_dataset(_SCREAMING_SNAKE_CASE       :		List[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}."""

        SCREAMING_SNAKE_CASE_						=    processor(
            audio=batch['speech']			, text=batch[data_args.target_text_column]			, sampling_rate=batch['sampling_rate'][0]							)
        batch.update(_SCREAMING_SNAKE_CASE							)
        return batch

    SCREAMING_SNAKE_CASE_						=    train_dataset.map(
        _SCREAMING_SNAKE_CASE			, batch_size=training_args.per_device_train_batch_size			, batched=_SCREAMING_SNAKE_CASE			, num_proc=data_args.preprocessing_num_workers			, )
    SCREAMING_SNAKE_CASE_						=    val_dataset.map(
        _SCREAMING_SNAKE_CASE			, batch_size=training_args.per_device_train_batch_size			, batched=_SCREAMING_SNAKE_CASE			, num_proc=data_args.preprocessing_num_workers			, )

    SCREAMING_SNAKE_CASE_						=    DataCollatorCTCWithPadding(processor=_SCREAMING_SNAKE_CASE			, padding=_SCREAMING_SNAKE_CASE							)

    def compute_metrics(_SCREAMING_SNAKE_CASE       :		Optional[int]							):
        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							)
        if logger.isEnabledFor(logging.DEBUG							):
            for reference, predicted in zip(_SCREAMING_SNAKE_CASE			, _SCREAMING_SNAKE_CASE							):
                logger.debug(f"""reference: \"{reference}\""""							)
                logger.debug(f"""predicted: \"{predicted}\""""							)
                if orthography.untransliterator is not None:
                    logger.debug(f"""reference (untransliterated): \"{orthography.untransliterator(_SCREAMING_SNAKE_CASE							)}\""""							)
                    logger.debug(f"""predicted (untransliterated): \"{orthography.untransliterator(_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()

    SCREAMING_SNAKE_CASE_						=    CTCTrainer(
        model=_SCREAMING_SNAKE_CASE			, data_collator=_SCREAMING_SNAKE_CASE			, args=_SCREAMING_SNAKE_CASE			, compute_metrics=_SCREAMING_SNAKE_CASE			, train_dataset=_SCREAMING_SNAKE_CASE			, eval_dataset=_SCREAMING_SNAKE_CASE			, tokenizer=processor.feature_extractor			, )

    trainer.train()


if __name__ == "__main__":
       main()


