






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					:						Optional[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__						(    lowerCamelCase	:			Optional[Any]			,lowerCamelCase	:			Dict			,lowerCamelCase	:			Dict=None			,lowerCamelCase	:			Dict=None			,lowerCamelCase	:			str=None			,lowerCamelCase	:			Tuple=None			,lowerCamelCase	:			List[str]=None			,lowerCamelCase	:			List[Any]=None			,):
   if attention_mask is None:
      lowerCamelCase									=np.where(input_ids != config.pad_token_id			,1			,0    )
   if decoder_attention_mask is None:
      lowerCamelCase									=np.where(decoder_input_ids != config.pad_token_id			,1			,0    )
   if head_mask is None:
      lowerCamelCase									=np.ones((config.encoder_layers, config.encoder_attention_heads)    )
   if decoder_head_mask is None:
      lowerCamelCase									=np.ones((config.decoder_layers, config.decoder_attention_heads)    )
   if cross_attn_head_mask is None:
      lowerCamelCase									=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 		lowerCAmelCase_				:





     def __init__(	self							, _UpperCAmelCase							, _UpperCAmelCase=13							, _UpperCAmelCase=7							, _UpperCAmelCase=True							, _UpperCAmelCase=False							, _UpperCAmelCase=99							, _UpperCAmelCase=16							, _UpperCAmelCase=2							, _UpperCAmelCase=4							, _UpperCAmelCase=4							, _UpperCAmelCase="gelu"							, _UpperCAmelCase=0.1							, _UpperCAmelCase=0.1							, _UpperCAmelCase=32							, _UpperCAmelCase=2							, _UpperCAmelCase=1							, _UpperCAmelCase=0							, _UpperCAmelCase=0.02							, )		->				List[Any]:
        lowerCamelCase									=parent
        lowerCamelCase									=batch_size
        lowerCamelCase									=seq_length
        lowerCamelCase									=is_training
        lowerCamelCase									=use_labels
        lowerCamelCase									=vocab_size
        lowerCamelCase									=hidden_size
        lowerCamelCase									=num_hidden_layers
        lowerCamelCase									=num_attention_heads
        lowerCamelCase									=intermediate_size
        lowerCamelCase									=hidden_act
        lowerCamelCase									=hidden_dropout_prob
        lowerCamelCase									=attention_probs_dropout_prob
        lowerCamelCase									=max_position_embeddings
        lowerCamelCase									=eos_token_id
        lowerCamelCase									=pad_token_id
        lowerCamelCase									=bos_token_id
        lowerCamelCase									=initializer_range





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

        lowerCamelCase									=shift_tokens_right(_UpperCAmelCase							, 1							, 2  )

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





     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        lowerCamelCase				,       lowerCamelCase									=self.prepare_config_and_inputs()
        return config, inputs_dict





     def 						lowerCamelCase							(	self							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )		->				str:
        lowerCamelCase									=20
        lowerCamelCase									=model_class_name(_UpperCAmelCase  )

        lowerCamelCase									=model.encode(inputs_dict["""input_ids"""]  )

        lowerCamelCase				,       lowerCamelCase									=(
            inputs_dict["""decoder_input_ids"""],
            inputs_dict["""decoder_attention_mask"""],
        )

        lowerCamelCase									=model.init_cache(decoder_input_ids.shape[0]							, _UpperCAmelCase							, _UpperCAmelCase  )
        lowerCamelCase									=jnp.ones((decoder_input_ids.shape[0], max_decoder_length)							, dtype="""i4"""  )

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

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

        lowerCamelCase									=model.decode(_UpperCAmelCase							, _UpperCAmelCase  )

        lowerCamelCase									=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							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )		->				Any:
        lowerCamelCase									=20
        lowerCamelCase									=model_class_name(_UpperCAmelCase  )

        lowerCamelCase									=model.encode(inputs_dict["""input_ids"""]  )

        lowerCamelCase				,       lowerCamelCase									=(
            inputs_dict["""decoder_input_ids"""],
            inputs_dict["""decoder_attention_mask"""],
        )

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

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

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

        lowerCamelCase									=model.decode(_UpperCAmelCase							, _UpperCAmelCase							, decoder_attention_mask=_UpperCAmelCase  )

        lowerCamelCase									=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 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase				,     UpperCamelCase ):
     __lowerCamelCase       :    str 	=     True
     __lowerCamelCase       :    Any 	=     (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
     __lowerCamelCase       :    Optional[int] 	=     (FlaxMarianMTModel,) if is_flax_available() else ()





     def 						lowerCamelCase							(	self  )		->				List[Any]:
        lowerCamelCase									=FlaxMarianModelTester(self  )





     def 						lowerCamelCase							(	self  )		->				int:
        lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
           self.model_tester.check_use_cache_forward(_UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )





     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        lowerCamelCase				,       lowerCamelCase									=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(_UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )





     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__  ):
              lowerCamelCase									=self._prepare_for_class(_UpperCAmelCase							, _UpperCAmelCase  )
              lowerCamelCase									=model_class(_UpperCAmelCase  )

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

              with self.subTest("""JIT Enabled"""  ):
                 lowerCamelCase									=encode_jitted(**_UpperCAmelCase  ).to_tuple()

              with self.subTest("""JIT Disabled"""  ):
                 with jax.disable_jit():
                    lowerCamelCase									=encode_jitted(**_UpperCAmelCase  ).to_tuple()

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





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__  ):
              lowerCamelCase									=model_class(_UpperCAmelCase  )
              lowerCamelCase									=model.encode(inputs_dict["""input_ids"""]							, inputs_dict["""attention_mask"""]  )

              lowerCamelCase									={
                  """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(_UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  ):
                 return model.decode(
                     decoder_input_ids=_UpperCAmelCase							, decoder_attention_mask=_UpperCAmelCase							, encoder_outputs=_UpperCAmelCase							, )

              with self.subTest("""JIT Enabled"""  ):
                 lowerCamelCase									=decode_jitted(**_UpperCAmelCase  ).to_tuple()

              with self.subTest("""JIT Disabled"""  ):
                 with jax.disable_jit():
                    lowerCamelCase									=decode_jitted(**_UpperCAmelCase  ).to_tuple()

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





     @slow
     def 						lowerCamelCase							(	self  )		->				List[str]:
        for model_class_name in self.all_model_classes:
           lowerCamelCase									=model_class_name.from_pretrained("""Helsinki-NLP/opus-mt-en-de"""  )
           # FlaxMarianForSequenceClassification expects eos token in input_ids
           lowerCamelCase									=np.ones((1, 1)  ) * model.config.eos_token_id
           lowerCamelCase									=model(_UpperCAmelCase  )
           self.assertIsNotNone(_UpperCAmelCase  )




@require_flax
@require_sentencepiece
@require_tokenizers
class 		lowerCAmelCase_				(  unittest.TestCase ):
     __lowerCamelCase       :    Tuple 	=     None
     __lowerCamelCase       :    List[str] 	=     None





     @classmethod
     def 						lowerCamelCase							(	cls  )		->				None:
        lowerCamelCase									=F'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
        return cls





     @cached_property
     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        return MarianTokenizer.from_pretrained(self.model_name  )





     @property
     def 						lowerCamelCase							(	self  )		->				int:
        return self.tokenizer.eos_token_id





     @cached_property
     def 						lowerCamelCase							(	self  )		->				Dict:
        lowerCamelCase									=FlaxMarianMTModel.from_pretrained(self.model_name  )
        self.assertEqual(model.config.decoder_start_token_id							, model.config.pad_token_id  )
        return model





     def 						lowerCamelCase							(	self							, **_UpperCAmelCase  )		->				Union[str, Any]:
        lowerCamelCase									=self.translate_src_text(**_UpperCAmelCase  )
        self.assertListEqual(self.expected_text							, _UpperCAmelCase  )





     def 						lowerCamelCase							(	self							, **_UpperCAmelCase  )		->				str:
        lowerCamelCase									=self.tokenizer(self.src_text							, padding=_UpperCAmelCase							, return_tensors="""np"""							, **_UpperCAmelCase  )
        lowerCamelCase									=self.model.generate(
            model_inputs.input_ids							, attention_mask=model_inputs.attention_mask							, num_beams=2							, max_length=128							, ).sequences
        lowerCamelCase									=self.tokenizer.batch_decode(_UpperCAmelCase							, skip_special_tokens=_UpperCAmelCase  )
        return generated_words




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





     @slow
     def 						lowerCamelCase							(	self  )		->				Tuple:
        self._assert_generated_batch_equal_expected()




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





     @slow
     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        self._assert_generated_batch_equal_expected()




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





     @slow
     def 						lowerCamelCase							(	self  )		->				int:
        self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class 		lowerCAmelCase_				(  UpperCamelCase ):
     __lowerCamelCase       :    Optional[Any] 	=     '''en'''
     __lowerCamelCase       :    str 	=     '''de'''
     __lowerCamelCase       :    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       :    Dict 	=     [
         '''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  )		->				Tuple:
        self._assert_generated_batch_equal_expected()




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





     @slow
     def 						lowerCamelCase							(	self  )		->				Optional[Any]:
        self._assert_generated_batch_equal_expected()




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





     @slow
     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class 		lowerCAmelCase_				(  UpperCamelCase ):
     __lowerCamelCase       :    str 	=     '''en'''
     __lowerCamelCase       :    Tuple 	=     '''ROMANCE'''
     __lowerCamelCase       :    Any 	=     [
         '''>>fr<< Don\'t spend so much time watching TV.''',
         '''>>pt<< Your message has been sent.''',
         '''>>es<< He\'s two years older than me.''',
     ]
     __lowerCamelCase       :    int 	=     [
         '''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  )		->				Any:
        self._assert_generated_batch_equal_expected()







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import BlipImageProcessor


class 		lowerCAmelCase_				(  unittest.TestCase ):





     def __init__(	self							, _UpperCAmelCase							, _UpperCAmelCase=7							, _UpperCAmelCase=3							, _UpperCAmelCase=18							, _UpperCAmelCase=30							, _UpperCAmelCase=400							, _UpperCAmelCase=True							, _UpperCAmelCase=None							, _UpperCAmelCase=True							, _UpperCAmelCase=False							, _UpperCAmelCase=[0.48145466, 0.4578275, 0.40821073]							, _UpperCAmelCase=[0.26862954, 0.26130258, 0.27577711]							, _UpperCAmelCase=True							, )		->				List[str]:
        lowerCamelCase									=size if size is not None else {"""height""": 20, """width""": 20}
        lowerCamelCase									=parent
        lowerCamelCase									=batch_size
        lowerCamelCase									=num_channels
        lowerCamelCase									=image_size
        lowerCamelCase									=min_resolution
        lowerCamelCase									=max_resolution
        lowerCamelCase									=do_resize
        lowerCamelCase									=size
        lowerCamelCase									=do_normalize
        lowerCamelCase									=image_mean
        lowerCamelCase									=image_std
        lowerCamelCase									=do_pad
        lowerCamelCase									=do_convert_rgb





     def 						lowerCamelCase							(	self  )		->				str:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_convert_rgb": self.do_convert_rgb,
            "do_pad": self.do_pad,
        }





     def 						lowerCamelCase							(	self							, _UpperCAmelCase=False							, _UpperCAmelCase=False							, _UpperCAmelCase=False  )		->				Optional[int]:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
           lowerCamelCase									=[]
           for i in range(self.batch_size  ):
              image_inputs.append(
                  np.random.randint(
                      255							, size=(self.num_channels, self.max_resolution, self.max_resolution)							, dtype=np.uinta  )  )
        else:
           lowerCamelCase									=[]
           for i in range(self.batch_size  ):
              lowerCamelCase				,       lowerCamelCase									=np.random.choice(np.arange(self.min_resolution							, self.max_resolution  )							, 2  )
              image_inputs.append(np.random.randint(255							, size=(self.num_channels, width, height)							, dtype=np.uinta  )  )

        if not numpify and not torchify:
           # PIL expects the channel dimension as last dimension
           lowerCamelCase									=[Image.fromarray(np.moveaxis(_UpperCAmelCase							, 0							, -1  )  ) for x in image_inputs]

        if torchify:
           lowerCamelCase									=[torch.from_numpy(_UpperCAmelCase  ) for x in image_inputs]

        return image_inputs




@require_torch
@require_vision
class 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    str 	=     BlipImageProcessor if is_vision_available() else None





     def 						lowerCamelCase							(	self  )		->				Dict:
        lowerCamelCase									=BlipImageProcessingTester(self  )





     @property
     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        return self.image_processor_tester.prepare_image_processor_dict()





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_resize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """size"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_normalize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_mean"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_std"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_convert_rgb"""  )  )





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        pass





     def 						lowerCamelCase							(	self  )		->				int:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PIL images
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, Image.Image  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random numpy tensors
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase							, numpify=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, np.ndarray  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )





     def 						lowerCamelCase							(	self  )		->				Optional[Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PyTorch tensors
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase							, torchify=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, torch.Tensor  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )




@require_torch
@require_vision
class 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    Any 	=     BlipImageProcessor if is_vision_available() else None





     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        lowerCamelCase									=BlipImageProcessingTester(self							, num_channels=4  )
        lowerCamelCase									=3





     @property
     def 						lowerCamelCase							(	self  )		->				Any:
        return self.image_processor_tester.prepare_image_processor_dict()





     def 						lowerCamelCase							(	self  )		->				List[str]:
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_resize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """size"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_normalize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_mean"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_std"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_convert_rgb"""  )  )





     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        pass





     def 						lowerCamelCase							(	self  )		->				List[Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PIL images
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, Image.Image  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )