
from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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


if is_tf_available():
    import tensorflow as tf

    from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel




@require_tf
class        UpperCAmelCase_			:


  '''simple docstring'''







  a__           =		MBartConfig
  a__           =		{}
  a__           =		"""gelu"""
  def __init__( self			: str			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: List[str]=13			,							UpperCamelCase__			: Union[str, Any]=7			,							UpperCamelCase__			: Optional[Any]=True			,							UpperCamelCase__			: List[str]=False			,							UpperCamelCase__			: Optional[int]=99			,							UpperCamelCase__			: Optional[Any]=32			,							UpperCamelCase__			: Optional[Any]=2			,							UpperCamelCase__			: str=4			,							UpperCamelCase__			: List[str]=37			,							UpperCamelCase__			: List[Any]=0.1			,							UpperCamelCase__			: Optional[int]=0.1			,							UpperCamelCase__			: Tuple=20			,							UpperCamelCase__			: Optional[int]=2			,							UpperCamelCase__			: Optional[int]=1			,							UpperCamelCase__			: List[Any]=0			,							)			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       batch_size
    __magic_name__				     =       seq_length
    __magic_name__				     =       is_training
    __magic_name__				     =       use_labels
    __magic_name__				     =       vocab_size
    __magic_name__				     =       hidden_size
    __magic_name__				     =       num_hidden_layers
    __magic_name__				     =       num_attention_heads
    __magic_name__				     =       intermediate_size
    __magic_name__				     =       hidden_dropout_prob
    __magic_name__				     =       attention_probs_dropout_prob
    __magic_name__				     =       max_position_embeddings
    __magic_name__				     =       eos_token_id
    __magic_name__				     =       pad_token_id
    __magic_name__				     =       bos_token_id
  def 							_lowercase							( self			: int    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       ids_tensor([self.batch_size, self.seq_length - 1]			,							self.vocab_size    )
    __magic_name__				     =       tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size    )			,							1    )
    __magic_name__				     =       tf.concat([input_ids, eos_tensor]			,							axis=1    )

    __magic_name__				     =       ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )

    __magic_name__				     =       self.config_cls(
        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_ids=[2]			,							bos_token_id=self.bos_token_id			,							pad_token_id=self.pad_token_id			,							decoder_start_token_id=self.pad_token_id			,							**self.config_updates			,							)
    __magic_name__				     =       prepare_mbart_inputs_dict(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )
    return config, inputs_dict





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







    """simple docstring"""






    __magic_name__				     =       TFMBartModel(config=UpperCamelCase__    ).get_decoder()
    __magic_name__				     =       inputs_dict["""input_ids"""]

    __magic_name__				     =       input_ids[:1, :]
    __magic_name__				     =       inputs_dict["""attention_mask"""][:1, :]
    __magic_name__				     =       inputs_dict["""head_mask"""]
    __magic_name__				     =       1

    # first forward pass
    __magic_name__				     =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							head_mask=UpperCamelCase__			,							use_cache=UpperCamelCase__    )

    __magic_name__     ,    __magic_name__				     =       outputs.to_tuple()
    __magic_name__				     =       past_key_values[1]







def a__    (       A_,     A_,     A_,     A_=None,     A_=None,     A_=None,     A_=None,     A_=None,     ):






  '''simple docstring'''





  if attention_mask is None:
    __magic_name__				     =       tf.cast(tf.math.not_equal(A_,     config.pad_token_id					),     tf.inta					)
  if decoder_attention_mask is None:
    __magic_name__				     =       tf.concat(
        [
            tf.ones(decoder_input_ids[:, :1].shape,     dtype=tf.inta					),
            tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],     config.pad_token_id					),     tf.inta					),
        ],     axis=-1,     )
  if head_mask is None:
    __magic_name__				     =       tf.ones((config.encoder_layers, config.encoder_attention_heads)					)
  if decoder_head_mask is None:
    __magic_name__				     =       tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
  if cross_attn_head_mask is None:
    __magic_name__				     =       tf.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": decoder_attention_mask,
      "head_mask": head_mask,
      "decoder_head_mask": decoder_head_mask,
      "cross_attn_head_mask": cross_attn_head_mask,
  }




@require_tf
class        UpperCAmelCase_			( _A  ,       _A  ,       unittest.TestCase     ):


  '''simple docstring'''







  a__           =		(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
  a__           =		(TFMBartForConditionalGeneration,) if is_tf_available() else ()
  a__           =		(
      {
          """conversational""": TFMBartForConditionalGeneration,
          """feature-extraction""": TFMBartModel,
          """summarization""": TFMBartForConditionalGeneration,
          """text2text-generation""": TFMBartForConditionalGeneration,
          """translation""": TFMBartForConditionalGeneration,
      }
      if is_tf_available()
      else {}
  )
  a__           =		True
  a__           =		False
  a__           =		False
  def 							_lowercase							( self			: int			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Tuple    )			->	Tuple:







    """simple docstring"""






    if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
      # Exception encountered when calling layer '...'
      return True

    return False
  def 							_lowercase							( self			: Optional[Any]    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       TFMBartModelTester(self    )
    __magic_name__				     =       ConfigTester(self			,							config_class=UpperCamelCase__    )
  def 							_lowercase							( self			: Dict    )			->	List[str]:







    """simple docstring"""






    self.config_tester.run_common_tests()





  def 							_lowercase							( self			: Tuple    )			->	Dict:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()
    self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase__    )







@require_sentencepiece
@require_tokenizers
@require_tf
class        UpperCAmelCase_			( unittest.TestCase     ):


  '''simple docstring'''







  a__           =		[
      """ UN Chief Says There Is No Military Solution in Syria""",
  ]
  a__           =		[
      """Şeful ONU declară că nu există o soluţie militară în Siria""",
  ]
  a__           =		"""facebook/mbart-large-en-ro"""
  @cached_property
  def 							_lowercase							( self			: List[str]    )			->	Dict:







    """simple docstring"""






    return AutoTokenizer.from_pretrained(self.model_name    )
  @cached_property
  def 							_lowercase							( self			: Union[str, Any]    )			->	int:







    """simple docstring"""






    __magic_name__				     =       TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name    )
    return model
  def 							_lowercase							( self			: Dict			,							**UpperCamelCase__			: Union[str, Any]    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__				     =       self.translate_src_text(**UpperCamelCase__    )
    self.assertListEqual(self.expected_text			,							UpperCamelCase__    )
  def 							_lowercase							( self			: Union[str, Any]			,							**UpperCamelCase__			: Optional[int]    )			->	str:







    """simple docstring"""






    __magic_name__				     =       self.tokenizer(self.src_text			,							**UpperCamelCase__			,							return_tensors="""tf"""    )
    __magic_name__				     =       self.model.generate(
        model_inputs.input_ids			,							attention_mask=model_inputs.attention_mask			,							num_beams=2    )
    __magic_name__				     =       self.tokenizer.batch_decode(UpperCamelCase__			,							skip_special_tokens=UpperCamelCase__    )
    return generated_words





  @slow
  def 							_lowercase							( self			: Optional[int]    )			->	Dict:







    """simple docstring"""






    self._assert_generated_batch_equal_expected()



import re
import string

import numpy as np

import datasets


__lowerCAmelCase			:     Optional[int]           =   '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

__lowerCAmelCase			:     Optional[int]           =   '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

__lowerCAmelCase			:     Optional[int]           =   '\n'




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,       _KWARGS_DESCRIPTION     )
class        UpperCAmelCase_			( datasets.Metric     ):


  '''simple docstring'''







  def 							_lowercase							( self			: str    )			->	Optional[int]:







    """simple docstring"""






    return datasets.MetricInfo(
        description=_DESCRIPTION			,							citation=_CITATION			,							inputs_description=_KWARGS_DESCRIPTION			,							features=datasets.Features(
            {
                """predictions""": datasets.Value("""string"""			,							id="""sequence"""    ),
                """references""": datasets.Value("""string"""			,							id="""sequence"""    ),
            }    )			,							reference_urls=[]			,							)





  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[Any]=None			,							UpperCamelCase__			: Optional[Any]=False			,							UpperCamelCase__			: int=False			,							UpperCamelCase__			: Tuple=False			,							)			->	Dict:







    """simple docstring"""






    if regexes_to_ignore is not None:
      for s in regexes_to_ignore:
        __magic_name__				     =       np.array([re.sub(UpperCamelCase__			,							""""""			,							UpperCamelCase__    ) for x in predictions]    )
        __magic_name__				     =       np.array([re.sub(UpperCamelCase__			,							""""""			,							UpperCamelCase__    ) for x in references]    )
    else:
      __magic_name__				     =       np.asarray(UpperCamelCase__    )
      __magic_name__				     =       np.asarray(UpperCamelCase__    )

    if ignore_case:
      __magic_name__				     =       np.char.lower(UpperCamelCase__    )
      __magic_name__				     =       np.char.lower(UpperCamelCase__    )

    if ignore_punctuation:
      __magic_name__				     =       string.punctuation.maketrans(""""""			,							""""""			,							string.punctuation    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )

    if ignore_numbers:
      __magic_name__				     =       string.digits.maketrans(""""""			,							""""""			,							string.digits    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )

    __magic_name__				     =       predictions == references

    return {"exact_match": np.mean(UpperCamelCase__    ) * 100}

