import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

from ...test_tokenization_common import TokenizerTesterMixin


__lowercase							 =					get_tests_dir('''fixtures/test_sentencepiece.model''')


if is_torch_available():
    from transformers.models.mbart.modeling_mbart import shift_tokens_right

__lowercase							 =					25_0004
__lowercase							 =					25_0020


@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_     (   UpperCAmelCase_						,	unittest.TestCase ):






    '''simple docstring'''






    a__	:						Optional[int]						=      MBartTokenizer
    a__	:						str						=      MBartTokenizerFast
    a__	:						Dict						=      True
    a__	:						int						=      True







    def 			UpperCamelCase__   (	self)       ->	str:
        super().setUp()

        # We have a SentencePiece fixture for testing
        __UpperCamelCase     :str			  =		MBartTokenizer(__lowercase , keep_accents=__lowercase)
        tokenizer.save_pretrained(self.tmpdirname)







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :Optional[Any]			  =		MBartTokenizer(__lowercase , keep_accents=__lowercase)

        __UpperCamelCase     :Any			  =		tokenizer.tokenize('''This is a test''')
        self.assertListEqual(__lowercase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])

        self.assertListEqual(
            tokenizer.convert_tokens_to_ids(__lowercase) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )

        __UpperCamelCase     :str			  =		tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
        self.assertListEqual(
            __lowercase , [
                SPIECE_UNDERLINE + '''I''',
                SPIECE_UNDERLINE + '''was''',
                SPIECE_UNDERLINE + '''b''',
                '''or''',
                '''n''',
                SPIECE_UNDERLINE + '''in''',
                SPIECE_UNDERLINE + '''''',
                '''9''',
                '''2''',
                '''0''',
                '''0''',
                '''0''',
                ''',''',
                SPIECE_UNDERLINE + '''and''',
                SPIECE_UNDERLINE + '''this''',
                SPIECE_UNDERLINE + '''is''',
                SPIECE_UNDERLINE + '''f''',
                '''al''',
                '''s''',
                '''é''',
                '''.''',
            ] , )
        __UpperCamelCase     :Optional[Any]			  =		tokenizer.convert_tokens_to_ids(__lowercase)
        self.assertListEqual(
            __lowercase , [
                value + tokenizer.fairseq_offset
                for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
                #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
            ] , )

        __UpperCamelCase     :str			  =		tokenizer.convert_ids_to_tokens(__lowercase)
        self.assertListEqual(
            __lowercase , [
                SPIECE_UNDERLINE + '''I''',
                SPIECE_UNDERLINE + '''was''',
                SPIECE_UNDERLINE + '''b''',
                '''or''',
                '''n''',
                SPIECE_UNDERLINE + '''in''',
                SPIECE_UNDERLINE + '''''',
                '''<unk>''',
                '''2''',
                '''0''',
                '''0''',
                '''0''',
                ''',''',
                SPIECE_UNDERLINE + '''and''',
                SPIECE_UNDERLINE + '''this''',
                SPIECE_UNDERLINE + '''is''',
                SPIECE_UNDERLINE + '''f''',
                '''al''',
                '''s''',
                '''<unk>''',
                '''.''',
            ] , )







    def 			UpperCamelCase__   (	self)       ->	Any:







        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
            return

        __UpperCamelCase     :Union[str, Any]			  =		(self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {})
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
                __UpperCamelCase     :Tuple			  =		self.rust_tokenizer_class.from_pretrained(__lowercase , **__lowercase)
                __UpperCamelCase     :Optional[Any]			  =		self.tokenizer_class.from_pretrained(__lowercase , **__lowercase)

                __UpperCamelCase     :Optional[int]			  =		tempfile.mkdtemp()

                __UpperCamelCase     :Dict			  =		tokenizer_r.save_pretrained(__lowercase)
                __UpperCamelCase     :Tuple			  =		tokenizer_p.save_pretrained(__lowercase)

                # Checks it save with the same files + the tokenizer.json file for the fast one
                self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files))
                __UpperCamelCase     :Optional[Any]			  =		tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f)
                self.assertSequenceEqual(__lowercase , __lowercase)

                # Checks everything loads correctly in the same way
                __UpperCamelCase     :Any			  =		tokenizer_r.from_pretrained(__lowercase)
                __UpperCamelCase     :str			  =		tokenizer_p.from_pretrained(__lowercase)

                # Check special tokens are set accordingly on Rust and Python
                for key in tokenizer_pp.special_tokens_map:
                    self.assertTrue(hasattr(__lowercase , __lowercase))
                    # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
                    # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

                shutil.rmtree(__lowercase)

                # Save tokenizer rust, legacy_format=True
                __UpperCamelCase     :int			  =		tempfile.mkdtemp()

                __UpperCamelCase     :Dict			  =		tokenizer_r.save_pretrained(__lowercase , legacy_format=__lowercase)
                __UpperCamelCase     :str			  =		tokenizer_p.save_pretrained(__lowercase)

                # Checks it save with the same files
                self.assertSequenceEqual(__lowercase , __lowercase)

                # Checks everything loads correctly in the same way
                __UpperCamelCase     :Optional[int]			  =		tokenizer_r.from_pretrained(__lowercase)
                __UpperCamelCase     :Tuple			  =		tokenizer_p.from_pretrained(__lowercase)

                # Check special tokens are set accordingly on Rust and Python
                for key in tokenizer_pp.special_tokens_map:
                    self.assertTrue(hasattr(__lowercase , __lowercase))

                shutil.rmtree(__lowercase)

                # Save tokenizer rust, legacy_format=False
                __UpperCamelCase     :List[Any]			  =		tempfile.mkdtemp()

                __UpperCamelCase     :List[Any]			  =		tokenizer_r.save_pretrained(__lowercase , legacy_format=__lowercase)
                __UpperCamelCase     :Union[str, Any]			  =		tokenizer_p.save_pretrained(__lowercase)

                # Checks it saved the tokenizer.json file
                self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files))

                # Checks everything loads correctly in the same way
                __UpperCamelCase     :Tuple			  =		tokenizer_r.from_pretrained(__lowercase)
                __UpperCamelCase     :Optional[int]			  =		tokenizer_p.from_pretrained(__lowercase)

                # Check special tokens are set accordingly on Rust and Python
                for key in tokenizer_pp.special_tokens_map:
                    self.assertTrue(hasattr(__lowercase , __lowercase))

                shutil.rmtree(__lowercase)


@require_torch
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_     (   unittest.TestCase ):






    '''simple docstring'''






    a__	:						Any						=      "facebook/mbart-large-en-ro"
    a__	:						Union[str, Any]						=      [
        " UN Chief Says There Is No Military Solution in Syria",
        " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.",
    ]
    a__	:						str						=      [
        "Şeful ONU declară că nu există o soluţie militară în Siria",
        "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei"
        " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor"
        " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.",
    ]
    a__	:						Optional[Any]						=      [8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2, EN_CODE]







    @classmethod
    def 			UpperCamelCase__   (	cls)       ->	Union[str, Any]:
        __UpperCamelCase     :MBartTokenizer			  =		MBartTokenizer.from_pretrained(
            cls.checkpoint_name , src_lang='''en_XX''' , tgt_lang='''ro_RO''')
        __UpperCamelCase     :Optional[int]			  =		1
        return cls







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ar_AR'''] , 250_001)
        self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''en_EN'''] , 250_004)
        self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ro_RO'''] , 250_020)







    def 			UpperCamelCase__   (	self)       ->	Dict:
        __UpperCamelCase     :List[str]			  =		self.tokenizer.batch_encode_plus(self.src_text).input_ids[0]
        self.assertListEqual(self.expected_src_tokens , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        self.assertIn(__lowercase , self.tokenizer.all_special_ids)
        __UpperCamelCase     :int			  =		[RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2]
        __UpperCamelCase     :Dict			  =		self.tokenizer.decode(__lowercase , skip_special_tokens=__lowercase)
        __UpperCamelCase     :str			  =		self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowercase)
        self.assertEqual(__lowercase , __lowercase)
        self.assertNotIn(self.tokenizer.eos_token , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :List[Any]			  =		["""this is gunna be a long sentence """ * 20]
        assert isinstance(src_text[0] , __lowercase)
        __UpperCamelCase     :Tuple			  =		10
        __UpperCamelCase     :Dict			  =		self.tokenizer(__lowercase , max_length=__lowercase , truncation=__lowercase).input_ids[0]
        self.assertEqual(ids[-2] , 2)
        self.assertEqual(ids[-1] , __lowercase)
        self.assertEqual(len(__lowercase) , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	Any:
        self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR''']) , [250_026, 250_001])







    def 			UpperCamelCase__   (	self)       ->	Optional[Any]:
        __UpperCamelCase     :Union[str, Any]			  =		tempfile.mkdtemp()
        __UpperCamelCase     :Dict			  =		self.tokenizer.fairseq_tokens_to_ids
        self.tokenizer.save_pretrained(__lowercase)
        __UpperCamelCase     :List[str]			  =		MBartTokenizer.from_pretrained(__lowercase)
        self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __lowercase)







    @require_torch
    def 			UpperCamelCase__   (	self)       ->	Any:
        __UpperCamelCase     :Optional[int]			  =		self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowercase , return_tensors='''pt''')
        __UpperCamelCase     :List[str]			  =		shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id)

        # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
        assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
        assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
        assert batch.decoder_input_ids[1][-1] == 2
        assert batch.labels[1][-2:].tolist() == [2, RO_CODE]







    @require_torch
    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :int			  =		self.tokenizer(
            self.src_text , text_target=self.tgt_text , padding=__lowercase , truncation=__lowercase , max_length=len(self.expected_src_tokens) , return_tensors='''pt''' , )

        __UpperCamelCase     :Any			  =		shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id)

        self.assertIsInstance(__lowercase , __lowercase)

        self.assertEqual((2, 14) , batch.input_ids.shape)
        self.assertEqual((2, 14) , batch.attention_mask.shape)
        __UpperCamelCase     :int			  =		batch.input_ids.tolist()[0]
        self.assertListEqual(self.expected_src_tokens , __lowercase)
        self.assertEqual(2 , batch.decoder_input_ids[0, -1])  # EOS
        # Test that special tokens are reset
        self.assertEqual(self.tokenizer.prefix_tokens , [])
        self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE])







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :Optional[Any]			  =		self.tokenizer(self.src_text , padding=__lowercase , truncation=__lowercase , max_length=3 , return_tensors='''pt''')
        __UpperCamelCase     :Optional[int]			  =		self.tokenizer(
            text_target=self.tgt_text , padding=__lowercase , truncation=__lowercase , max_length=10 , return_tensors='''pt''')
        __UpperCamelCase     :Dict			  =		targets["""input_ids"""]
        __UpperCamelCase     :int			  =		shift_tokens_right(__lowercase , self.tokenizer.pad_token_id)

        self.assertEqual(batch.input_ids.shape[1] , 3)
        self.assertEqual(batch.decoder_input_ids.shape[1] , 10)







    @require_torch
    def 			UpperCamelCase__   (	self)       ->	Dict:
        __UpperCamelCase     :Union[str, Any]			  =		self.tokenizer._build_translation_inputs(
            '''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''ar_AR''')

        self.assertEqual(
            nested_simplify(__lowercase) , {
                # A, test, EOS, en_XX
                '''input_ids''': [[62, 3_034, 2, 250_004]],
                '''attention_mask''': [[1, 1, 1, 1]],
                # ar_AR
                '''forced_bos_token_id''': 250_001,
            } , )







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


lowercase  :					List[str]						    =							logging.get_logger(__name__)

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



           '''simple docstring'''







           if self.framework == "tf":
                  lowercase							:     str       	=      tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
           elif self.framework == "pt":
                  lowercase							:     Optional[int]       	=      torch.nonzero(input_ids == self.tokenizer.mask_token_id		,as_tuple=snake_case      )
           else:
                  raise ValueError("""Unsupported framework"""      )
           return masked_index
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      self.get_masked_index(snake_case      )
           lowercase							:     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       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if isinstance(snake_case		,snake_case      ):
                  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(snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None		,**snake_case      ):



           '''simple docstring'''







           if return_tensors is None:
                  lowercase							:     int       	=      self.framework
           lowercase							:     Optional[Any]       	=      self.tokenizer(snake_case		,return_tensors=snake_case      )
           self.ensure_exactly_one_mask_token(snake_case      )
           return model_inputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Optional[int]       	=      self.model(**snake_case      )
           lowercase							:     Tuple       	=      model_inputs["""input_ids"""]
           return model_outputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=5		,snake_case=None      ):



           '''simple docstring'''







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

           if self.framework == "tf":
                  lowercase							:     List[str]       	=      tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()[:, 0]

                  lowercase							:     Tuple       	=      outputs.numpy()

                  lowercase							:     Tuple       	=      outputs[0, masked_index, :]
                  lowercase							:     Any       	=      stable_softmax(snake_case		,axis=-1      )
                  if target_ids is not None:
                         lowercase							:     Union[str, Any]       	=      tf.gather_nd(tf.squeeze(snake_case		,0      )		,target_ids.reshape(-1		,1      )      )
                         lowercase							:     int       	=      tf.expand_dims(snake_case		,0      )

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

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

                  lowercase	,			lowercase							:     Union[str, Any]       	=      probs.topk(snake_case      )

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

                         lowercase							:     Tuple       	=      p
                         # Filter padding out:
                         lowercase							:     List[str]       	=      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
                         lowercase							:     Tuple       	=      self.tokenizer.decode(snake_case		,skip_special_tokens=snake_case      )
                         lowercase							:     Optional[Any]       	=      {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]      ), """sequence""": sequence}
                         row.append(snake_case      )
                  result.append(snake_case      )
           if single_mask:
                  return result[0]
           return result
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None      ):



           '''simple docstring'''







           if isinstance(snake_case		,snake_case      ):
                  lowercase							:     List[Any]       	=      [targets]
           try:
                  lowercase							:     List[str]       	=      self.tokenizer.get_vocab()
           except Exception:
                  lowercase							:     Any       	=      {}
           lowercase							:     Dict       	=      []
           for target in targets:
                  lowercase							:     Dict       	=      vocab.get(snake_case		,snake_case      )
                  if id_ is None:
                         lowercase							:     Optional[int]       	=      self.tokenizer(
                             snake_case		,add_special_tokens=snake_case		,return_attention_mask=snake_case		,return_token_type_ids=snake_case		,max_length=1		,truncation=snake_case		,)["""input_ids"""]
                         if len(snake_case      ) == 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
                         lowercase							:     Union[str, Any]       	=      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_      )
           lowercase							:     Optional[Any]       	=      list(set(snake_case      )      )
           if len(snake_case      ) == 0:
                  raise ValueError("""At least one target must be provided when passed."""      )
           lowercase							:     Optional[Any]       	=      np.array(snake_case      )
           return target_ids
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case=None		,snake_case=None      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      {}

           if targets is not None:
                  lowercase							:     str       	=      self.get_target_ids(snake_case		,snake_case      )
                  lowercase							:     List[Any]       	=      target_ids

           if top_k is not None:
                  lowercase							:     List[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		,snake_case		,*snake_case		,**snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      super().__call__(snake_case		,**snake_case      )
           if isinstance(snake_case		,snake_case      ) and len(snake_case      ) == 1:
                  return outputs[0]
           return outputs
