'''simple docstring'''





from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
			import tensorflow as tf

			from ..tf_utils import stable_softmax


if is_torch_available():
			import torch


lowerCAmelCase_						:		List[Any]								=  logging.get_logger(__name__)




@add_end_docstrings(
    UpperCAmelCase__ ,			R'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    ''' ,			)
class 		SCREAMING_SNAKE_CASE  (       UpperCAmelCase__						):







				'''simple docstring'''





				def 			snake_case__					(    self       :    Union[str, Any]							,		lowercase__       :    Tuple       )				->np.ndarray:


										'''simple docstring'''




										if self.framework == "tf":
																_UpperCamelCase      :      Tuple       =    tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
										elif self.framework == "pt":
																_UpperCamelCase      :      int       =    torch.nonzero(input_ids == self.tokenizer.mask_token_id							,		as_tuple=_UpperCAmelCase       )
										else:
																raise ValueError("Unsupported framework"       )
										return masked_index





				def 			snake_case__					(    self       :    Any							,		lowercase__       :    int       )				->np.ndarray:


										'''simple docstring'''




										_UpperCamelCase      :      Union[str, Any]       =    self.get_masked_index(_UpperCAmelCase       )
										_UpperCamelCase      :      Dict       =    np.prod(masked_index.shape       )
										if numel < 1:
																raise PipelineException(
																    "fill-mask"							,		self.model.base_model_prefix							,		f'''No mask_token ({self.tokenizer.mask_token}) found on the input'''							,		)





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


										'''simple docstring'''




										if isinstance(_UpperCAmelCase							,		_UpperCAmelCase       ):
																for model_input in model_inputs:
																						self._ensure_exactly_one_mask_token(model_input["input_ids"][0]       )
										else:
																for input_ids in model_inputs["input_ids"]:
																						self._ensure_exactly_one_mask_token(_UpperCAmelCase       )





				def 			snake_case__					(    self       :    Tuple							,		lowercase__       :    List[str]							,		lowercase__       :    Any=None							,		**lowercase__       :    int       )				->Dict[str, GenericTensor]:


										'''simple docstring'''




										if return_tensors is None:
																_UpperCamelCase      :      List[str]       =    self.framework
										_UpperCamelCase      :      Optional[int]       =    self.tokenizer(_UpperCAmelCase							,		return_tensors=_UpperCAmelCase       )
										self.ensure_exactly_one_mask_token(_UpperCAmelCase       )
										return model_inputs





				def 			snake_case__					(    self       :    List[Any]							,		lowercase__       :    str       )				->List[str]:


										'''simple docstring'''




										_UpperCamelCase      :      List[Any]       =    self.model(**_UpperCAmelCase       )
										_UpperCamelCase      :      Dict       =    model_inputs["input_ids"]
										return model_outputs





				def 			snake_case__					(    self       :    Optional[int]							,		lowercase__       :    Optional[int]							,		lowercase__       :    Union[str, Any]=5							,		lowercase__       :    Any=None       )				->Any:


										'''simple docstring'''




										if target_ids is not None and target_ids.shape[0] < top_k:
																_UpperCamelCase      :      Optional[int]       =    target_ids.shape[0]
										_UpperCamelCase      :      Any       =    model_outputs["input_ids"][0]
										_UpperCamelCase      :      str       =    model_outputs["logits"]

										if self.framework == "tf":
																_UpperCamelCase      :      Tuple       =    tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()[:, 0]

																_UpperCamelCase      :      Dict       =    outputs.numpy()

																_UpperCamelCase      :      int       =    outputs[0, masked_index, :]
																_UpperCamelCase      :      Dict       =    stable_softmax(_UpperCAmelCase							,		axis=-1       )
																if target_ids is not None:
																						_UpperCamelCase      :      int       =    tf.gather_nd(tf.squeeze(_UpperCAmelCase							,		0       )							,		target_ids.reshape(-1							,		1       )       )
																						_UpperCamelCase      :      Any       =    tf.expand_dims(_UpperCAmelCase							,		0       )

																_UpperCamelCase      :      Tuple       =    tf.math.top_k(_UpperCAmelCase							,		k=_UpperCAmelCase       )
																_UpperCamelCase      ,							_UpperCamelCase      :      List[str]       =    topk.values.numpy(), topk.indices.numpy()
										else:
																_UpperCamelCase      :      List[Any]       =    torch.nonzero(input_ids == self.tokenizer.mask_token_id							,		as_tuple=_UpperCAmelCase       ).squeeze(-1       )
																# Fill mask pipeline supports only one ${mask_token} per sample

																_UpperCamelCase      :      Tuple       =    outputs[0, masked_index, :]
																_UpperCamelCase      :      int       =    logits.softmax(dim=-1       )
																if target_ids is not None:
																						_UpperCamelCase      :      List[str]       =    probs[..., target_ids]

																_UpperCamelCase      ,							_UpperCamelCase      :      List[str]       =    probs.topk(_UpperCAmelCase       )

										_UpperCamelCase      :      Optional[Any]       =    []
										_UpperCamelCase      :      Optional[Any]       =    values.shape[0] == 1
										for i, (_values, _predictions) in enumerate(zip(values.tolist()							,		predictions.tolist()       )       ):
																_UpperCamelCase      :      List[str]       =    []
																for v, p in zip(_values							,		_predictions       ):
																						# Copy is important since we're going to modify this array in place
																						_UpperCamelCase      :      Optional[Any]       =    input_ids.numpy().copy()
																						if target_ids is not None:
																												_UpperCamelCase      :      str       =    target_ids[p].tolist()

																						_UpperCamelCase      :      List[str]       =    p
																						# Filter padding out:
																						_UpperCamelCase      :      Union[str, Any]       =    tokens[np.where(tokens != self.tokenizer.pad_token_id       )]
																						# Originally we skip special tokens to give readable output.
																						# For multi masks though, the other [MASK] would be removed otherwise
																						# making the output look odd, so we add them back
																						_UpperCamelCase      :      Any       =    self.tokenizer.decode(_UpperCAmelCase							,		skip_special_tokens=_UpperCAmelCase       )
																						_UpperCamelCase      :      Tuple       =    {"score": v, "token": p, "token_str": self.tokenizer.decode([p]       ), "sequence": sequence}
																						row.append(_UpperCAmelCase       )
																result.append(_UpperCAmelCase       )
										if single_mask:
																return result[0]
										return result





				def 			snake_case__					(    self       :    Union[str, Any]							,		lowercase__       :    List[Any]							,		lowercase__       :    int=None       )				->Any:


										'''simple docstring'''




										if isinstance(_UpperCAmelCase							,		_UpperCAmelCase       ):
																_UpperCamelCase      :      List[str]       =    [targets]
										try:
																_UpperCamelCase      :      Dict       =    self.tokenizer.get_vocab()
										except Exception:
																_UpperCamelCase      :      Dict       =    {}
										_UpperCamelCase      :      List[Any]       =    []
										for target in targets:
																_UpperCamelCase      :      Any       =    vocab.get(_UpperCAmelCase							,		_UpperCAmelCase       )
																if id_ is None:
																						_UpperCamelCase      :      Optional[Any]       =    self.tokenizer(
																						    _UpperCAmelCase							,		add_special_tokens=_UpperCAmelCase							,		return_attention_mask=_UpperCAmelCase							,		return_token_type_ids=_UpperCAmelCase							,		max_length=1							,		truncation=_UpperCAmelCase							,		)["input_ids"]
																						if len(_UpperCAmelCase       ) == 0:
																												logger.warning(
																												    f'''The specified target token `{target}` does not exist in the model vocabulary. '''
																												    "We cannot replace it with anything meaningful, ignoring it"       )
																												continue
																						_UpperCamelCase      :      Optional[int]       =    input_ids[0]
																						# XXX: If users encounter this pass
																						# it becomes pretty slow, so let's make sure
																						# The warning enables them to fix the input to
																						# get faster performance.
																						logger.warning(
																						    f'''The specified target token `{target}` does not exist in the model vocabulary. '''
																						    f'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_       )}`.'''       )
																target_ids.append(id_       )
										_UpperCamelCase      :      int       =    list(set(_UpperCAmelCase       )       )
										if len(_UpperCAmelCase       ) == 0:
																raise ValueError("At least one target must be provided when passed."       )
										_UpperCamelCase      :      Any       =    np.array(_UpperCAmelCase       )
										return target_ids





				def 			snake_case__					(    self       :    str							,		lowercase__       :    str=None							,		lowercase__       :    str=None       )				->List[str]:


										'''simple docstring'''




										_UpperCamelCase      :      List[Any]       =    {}

										if targets is not None:
																_UpperCamelCase      :      Union[str, Any]       =    self.get_target_ids(_UpperCAmelCase							,		_UpperCAmelCase       )
																_UpperCamelCase      :      int       =    target_ids

										if top_k is not None:
																_UpperCamelCase      :      str       =    top_k

										if self.tokenizer.mask_token_id is None:
																raise PipelineException(
																    "fill-mask"							,		self.model.base_model_prefix							,		"The tokenizer does not define a `mask_token`."       )
										return {}, {}, postprocess_params







				def __call__(    self       :    Dict							,		lowercase__       :    Optional[Any]							,		*lowercase__       :    Tuple							,		**lowercase__       :    int       )				->Any:


										'''simple docstring'''




										_UpperCamelCase      :      str       =    super().__call__(_UpperCAmelCase							,		**_UpperCAmelCase       )
										if isinstance(_UpperCAmelCase							,		_UpperCAmelCase       ) and len(_UpperCAmelCase       ) == 1:
																return outputs[0]
										return outputs










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     _a							:






  """simple docstring"""





  A_						       = MBartConfig
  A_						       = {}
  A_						       = """gelu"""




  def __init__(  self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=7		,		_UpperCAmelCase=True		,		_UpperCAmelCase=False		,		_UpperCAmelCase=99		,		_UpperCAmelCase=32		,		_UpperCAmelCase=2		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=20		,		_UpperCAmelCase=2		,		_UpperCAmelCase=1		,		_UpperCAmelCase=0		,		)      ->			Union[str, Any]:
     UpperCamelCase_						=  parent
     UpperCamelCase_						=  batch_size
     UpperCamelCase_						=  seq_length
     UpperCamelCase_						=  is_training
     UpperCamelCase_						=  use_labels
     UpperCamelCase_						=  vocab_size
     UpperCamelCase_						=  hidden_size
     UpperCamelCase_						=  num_hidden_layers
     UpperCamelCase_						=  num_attention_heads
     UpperCamelCase_						=  intermediate_size
     UpperCamelCase_						=  hidden_dropout_prob
     UpperCamelCase_						=  attention_probs_dropout_prob
     UpperCamelCase_						=  max_position_embeddings
     UpperCamelCase_						=  eos_token_id
     UpperCamelCase_						=  pad_token_id
     UpperCamelCase_						=  bos_token_id




  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  ids_tensor([self.batch_size, self.seq_length - 1]		,		self.vocab_size			)
     UpperCamelCase_						=  tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size			)		,		1			)
     UpperCamelCase_						=  tf.concat([input_ids, eos_tensor]		,		axis=1			)

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

     UpperCamelCase_						=  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		,		)
     UpperCamelCase_						=  prepare_mbart_inputs_dict(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)
     return config, inputs_dict




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			List[str]:
     UpperCamelCase_						=  TFMBartModel(config=_UpperCAmelCase			).get_decoder()
     UpperCamelCase_						=  inputs_dict['input_ids']

     UpperCamelCase_						=  input_ids[:1, :]
     UpperCamelCase_						=  inputs_dict['attention_mask'][:1, :]
     UpperCamelCase_						=  inputs_dict['head_mask']
     UpperCamelCase_						=  1

     # first forward pass
     UpperCamelCase_						=  model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		head_mask=_UpperCAmelCase		,		use_cache=_UpperCAmelCase			)

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






def      _snake_case     (__lowercase     ,   __lowercase     ,   __lowercase     ,   __lowercase=None     ,   __lowercase=None     ,   __lowercase=None     ,   __lowercase=None     ,   __lowercase=None     ,   ):
   if attention_mask is None:
      UpperCamelCase_						=  tf.cast(tf.math.not_equal(__lowercase     ,   config.pad_token_id)     ,   tf.inta)
   if decoder_attention_mask is None:
      UpperCamelCase_						=  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:
      UpperCamelCase_						=  tf.ones((config.encoder_layers, config.encoder_attention_heads))
   if decoder_head_mask is None:
      UpperCamelCase_						=  tf.ones((config.decoder_layers, config.decoder_attention_heads))
   if cross_attn_head_mask is None:
      UpperCamelCase_						=  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     _a							(	UpperCAmelCase__    ,							UpperCAmelCase__    ,							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  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Tuple:
     if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
        # Exception encountered when calling layer '...'
        return True

     return False




  def  _UpperCAmelCase  (  self			)      ->			Optional[int]:
     UpperCamelCase_						=  TFMBartModelTester(self			)
     UpperCamelCase_						=  ConfigTester(self		,		config_class=_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self			)      ->			Optional[int]:
     self.config_tester.run_common_tests()




  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  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     _a							(	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  _UpperCAmelCase  (  self			)      ->			Any:
     return AutoTokenizer.from_pretrained(self.model_name			)




  @cached_property
  def  _UpperCAmelCase  (  self			)      ->			List[str]:
     UpperCamelCase_						=  TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name			)
     return model




  def  _UpperCAmelCase  (  self		,		**_UpperCAmelCase			)      ->			int:
     UpperCamelCase_						=  self.translate_src_text(**_UpperCAmelCase			)
     self.assertListEqual(self.expected_text		,		_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		**_UpperCAmelCase			)      ->			List[str]:
     UpperCamelCase_						=  self.tokenizer(self.src_text		,		**_UpperCAmelCase		,		return_tensors='tf'			)
     UpperCamelCase_						=  self.model.generate(
         model_inputs.input_ids		,		attention_mask=model_inputs.attention_mask		,		num_beams=2			)
     UpperCamelCase_						=  self.tokenizer.batch_decode(_UpperCAmelCase		,		skip_special_tokens=_UpperCAmelCase			)
     return generated_words




  @slow
  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     self._assert_generated_batch_equal_expected()





