



"""simple docstring"""




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_    :
      __SCREAMING_SNAKE_CASE		:  Optional[int]						=					MBartConfig
      __SCREAMING_SNAKE_CASE		:  Any						=					{}
      __SCREAMING_SNAKE_CASE		:  Tuple						=					'gelu'



      def __init__(	self	:      Tuple	,      A	:      Any	,      A	:      int=1_3	,      A	:      List[str]=7	,      A	:      Dict=True	,      A	:      Dict=False	,      A	:      List[str]=9_9	,      A	:      Tuple=3_2	,      A	:      Union[str, Any]=2	,      A	:      str=4	,      A	:      Dict=3_7	,      A	:      Dict=0.1	,      A	:      Dict=0.1	,      A	:      str=2_0	,      A	:      Dict=2	,      A	:      Tuple=1	,      A	:      Optional[int]=0	,      ):
           _UpperCAmelCase     :      List[Any]														=       parent
           _UpperCAmelCase     :      Tuple														=       batch_size
           _UpperCAmelCase     :      Optional[int]														=       seq_length
           _UpperCAmelCase     :      Tuple														=       is_training
           _UpperCAmelCase     :      Optional[Any]														=       use_labels
           _UpperCAmelCase     :      List[Any]														=       vocab_size
           _UpperCAmelCase     :      Dict														=       hidden_size
           _UpperCAmelCase     :      List[str]														=       num_hidden_layers
           _UpperCAmelCase     :      Optional[int]														=       num_attention_heads
           _UpperCAmelCase     :      Optional[Any]														=       intermediate_size
           _UpperCAmelCase     :      Tuple														=       hidden_dropout_prob
           _UpperCAmelCase     :      int														=       attention_probs_dropout_prob
           _UpperCAmelCase     :      str														=       max_position_embeddings
           _UpperCAmelCase     :      Dict														=       eos_token_id
           _UpperCAmelCase     :      List[Any]														=       pad_token_id
           _UpperCAmelCase     :      Union[str, Any]														=       bos_token_id



      def 		snake_case_   (	self	:      Tuple		):
           _UpperCAmelCase     :      Dict														=       ids_tensor([self.batch_size, self.seq_length - 1]	,      self.vocab_size		)
           _UpperCAmelCase     :      Optional[Any]														=       tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size		)	,      1		)
           _UpperCAmelCase     :      Optional[Any]														=       tf.concat([input_ids, eos_tensor]	,      axis=1		)

           _UpperCAmelCase     :      Dict														=       ids_tensor([self.batch_size, self.seq_length]	,      self.vocab_size		)

           _UpperCAmelCase     :      Optional[int]														=       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     :      Union[str, Any]														=       prepare_mbart_inputs_dict(A	,      A	,      A		)
           return config, inputs_dict



      def 		snake_case_   (	self	:      List[str]	,      A	:      Tuple	,      A	:      str		):
           _UpperCAmelCase     :      Dict														=       TFMBartModel(config=A		).get_decoder()
           _UpperCAmelCase     :      Optional[int]														=       inputs_dict["input_ids"]

           _UpperCAmelCase     :      Optional[Any]														=       input_ids[:1, :]
           _UpperCAmelCase     :      Union[str, Any]														=       inputs_dict["attention_mask"][:1, :]
           _UpperCAmelCase     :      Optional[int]														=       inputs_dict["head_mask"]
           _UpperCAmelCase     :      Union[str, Any]														=       1

           # first forward pass
           _UpperCAmelCase     :      List[str]														=       model(A	,      attention_mask=A	,      head_mask=A	,      use_cache=A		)

           _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       outputs.to_tuple()
           _UpperCAmelCase     :      int														=       past_key_values[1]







def 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Any		,    SCREAMING_SNAKE_CASE__      :		int		,    SCREAMING_SNAKE_CASE__      :		List[str]		,    SCREAMING_SNAKE_CASE__      :		Any=None		,    SCREAMING_SNAKE_CASE__      :		str=None		,    SCREAMING_SNAKE_CASE__      :		str=None		,    SCREAMING_SNAKE_CASE__      :		Union[str, Any]=None		,    SCREAMING_SNAKE_CASE__      :		Any=None		,    )    ->  Optional[Any]:





     '''simple docstring'''

     if attention_mask is None:
          _UpperCAmelCase     :      List[str]														=       tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__		,    config.pad_token_id							)		,    tf.inta							)
     if decoder_attention_mask is None:
          _UpperCAmelCase     :      Optional[int]														=       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     :      Union[str, Any]														=       tf.ones((config.encoder_layers, config.encoder_attention_heads)							)
     if decoder_head_mask is None:
          _UpperCAmelCase     :      str														=       tf.ones((config.decoder_layers, config.decoder_attention_heads)							)
     if cross_attn_head_mask is None:
          _UpperCAmelCase     :      Optional[int]														=       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_    (							_UpperCamelCase			,     _UpperCamelCase			,     unittest.TestCase		):
      __SCREAMING_SNAKE_CASE		:  int						=					(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
      __SCREAMING_SNAKE_CASE		:  Union[str, Any]						=					(TFMBartForConditionalGeneration,) if is_tf_available() else ()
      __SCREAMING_SNAKE_CASE		:  Any						=					(
          {
              'conversational': TFMBartForConditionalGeneration,
              'feature-extraction': TFMBartModel,
              'summarization': TFMBartForConditionalGeneration,
              'text2text-generation': TFMBartForConditionalGeneration,
              'translation': TFMBartForConditionalGeneration,
          }
          if is_tf_available()
          else {}
      )
      __SCREAMING_SNAKE_CASE		:  Dict						=					True
      __SCREAMING_SNAKE_CASE		:  int						=					False
      __SCREAMING_SNAKE_CASE		:  Tuple						=					False



      def 		snake_case_   (	self	:      Any	,      A	:      List[Any]	,      A	:      str	,      A	:      Optional[int]	,      A	:      Any	,      A	:      str		):
           if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
                # Exception encountered when calling layer '...'
                return True

           return False



      def 		snake_case_   (	self	:      Tuple		):
           _UpperCAmelCase     :      Any														=       TFMBartModelTester(self		)
           _UpperCAmelCase     :      List[Any]														=       ConfigTester(self	,      config_class=A		)



      def 		snake_case_   (	self	:      Union[str, Any]		):
           self.config_tester.run_common_tests()



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      str														=       self.model_tester.prepare_config_and_inputs_for_common()
           self.model_tester.check_decoder_model_past_large_inputs(*A		)







@require_sentencepiece
@require_tokenizers
@require_tf
class       UpperCAmelCase_    (							unittest.TestCase		):
      __SCREAMING_SNAKE_CASE		:  Optional[int]						=					[
          ' UN Chief Says There Is No Military Solution in Syria',
      ]
      __SCREAMING_SNAKE_CASE		:  str						=					[
          'Şeful ONU declară că nu există o soluţie militară în Siria',
      ]
      __SCREAMING_SNAKE_CASE		:  List[str]						=					'facebook/mbart-large-en-ro'



      @cached_property
      def 		snake_case_   (	self	:      Optional[Any]		):
           return AutoTokenizer.from_pretrained(self.model_name		)



      @cached_property
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      Optional[Any]														=       TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name		)
           return model



      def 		snake_case_   (	self	:      Any	,      **A	:      str		):
           _UpperCAmelCase     :      Tuple														=       self.translate_src_text(**A		)
           self.assertListEqual(self.expected_text	,      A		)



      def 		snake_case_   (	self	:      Union[str, Any]	,      **A	:      List[Any]		):
           _UpperCAmelCase     :      List[Any]														=       self.tokenizer(self.src_text	,      **A	,      return_tensors="tf"		)
           _UpperCAmelCase     :      str														=       self.model.generate(
               model_inputs.input_ids	,      attention_mask=model_inputs.attention_mask	,      num_beams=2		)
           _UpperCAmelCase     :      List[Any]														=       self.tokenizer.batch_decode(A	,      skip_special_tokens=A		)
           return generated_words



      @slow
      def 		snake_case_   (	self	:      str		):
           self._assert_generated_batch_equal_expected()





"""simple docstring"""




import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image
else:






 class       UpperCAmelCase_    :



       @staticmethod
       def 		snake_case_   (	*A	:      Union[str, Any]	,      **A	:      Dict		):
            pass






@is_pipeline_test
@require_vision
class       UpperCAmelCase_    (							unittest.TestCase		):



      @require_torch
      def 		snake_case_   (	self	:      Union[str, Any]		):
           _UpperCAmelCase     :      Union[str, Any]														=       pipeline(
               model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification"	,      )
           _UpperCAmelCase     :      Union[str, Any]														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      Tuple														=       image_classifier(A	,      candidate_labels=["a", "b", "c"]		)

           # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
           # python and torch versions.
           self.assertIn(
               nested_simplify(A		)	,      [
                   [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}],
                   [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}],
               ]	,      )

           _UpperCAmelCase     :      str														=       image_classifier([image] * 5	,      candidate_labels=["A", "B", "C"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
               ]	,      )



      @require_tf
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      List[str]														=       pipeline(
               model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification"	,      framework="tf"		)
           _UpperCAmelCase     :      int														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      Union[str, Any]														=       image_classifier(A	,      candidate_labels=["a", "b", "c"]		)

           self.assertEqual(
               nested_simplify(A		)	,      [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}]	,      )

           _UpperCAmelCase     :      Optional[Any]														=       image_classifier([image] * 5	,      candidate_labels=["A", "B", "C"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
               ]	,      )



      @slow
      @require_torch
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      Optional[Any]														=       pipeline(
               task="zero-shot-image-classification"	,      model="openai/clip-vit-base-patch32"	,      )
           # This is an image of 2 cats with remotes and no planes
           _UpperCAmelCase     :      Dict														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      List[Any]														=       image_classifier(A	,      candidate_labels=["cat", "plane", "remote"]		)

           self.assertEqual(
               nested_simplify(A		)	,      [
                   {"score": 0.511, "label": "remote"},
                   {"score": 0.485, "label": "cat"},
                   {"score": 0.004, "label": "plane"},
               ]	,      )

           _UpperCAmelCase     :      Tuple														=       image_classifier([image] * 5	,      candidate_labels=["cat", "plane", "remote"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.511, "label": "remote"},
                       {"score": 0.485, "label": "cat"},
                       {"score": 0.004, "label": "plane"},
                   ],
               ]
               * 5	,      )



      @slow
      @require_tf
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      List[Any]														=       pipeline(
               task="zero-shot-image-classification"	,      model="openai/clip-vit-base-patch32"	,      framework="tf"		)
           # This is an image of 2 cats with remotes and no planes
           _UpperCAmelCase     :      Union[str, Any]														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      Union[str, Any]														=       image_classifier(A	,      candidate_labels=["cat", "plane", "remote"]		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   {"score": 0.511, "label": "remote"},
                   {"score": 0.485, "label": "cat"},
                   {"score": 0.004, "label": "plane"},
               ]	,      )

           _UpperCAmelCase     :      Union[str, Any]														=       image_classifier([image] * 5	,      candidate_labels=["cat", "plane", "remote"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.511, "label": "remote"},
                       {"score": 0.485, "label": "cat"},
                       {"score": 0.004, "label": "plane"},
                   ],
               ]
               * 5	,      )
