




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
				__a			:	List[str]							     =		"""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  a_		(							__snake_case     ,		__snake_case     ,		__snake_case=None     ,		__snake_case=None     ,		__snake_case=None     ,		__snake_case=None     ,		__snake_case=None     ,		__snake_case=None     ,		)	->			Optional[int]:

			'''simple docstring'''


			if attention_mask is None:
						UpperCamelCase_     				= np.where(input_ids != config.pad_token_id     ,		1     ,		0					)
			if decoder_attention_mask is None:
						UpperCamelCase_     				= np.where(decoder_input_ids != config.pad_token_id     ,		1     ,		0					)
			if head_mask is None:
						UpperCamelCase_     				= np.ones((config.encoder_layers, config.encoder_attention_heads)					)
			if decoder_head_mask is None:
						UpperCamelCase_     				= np.ones((config.decoder_layers, config.decoder_attention_heads)					)
			if cross_attn_head_mask is None:
						UpperCamelCase_     				= 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     A					:







							def __init__(    self   :	Optional[Any]   ,     __UpperCAmelCase   :	List[str]   ,     __UpperCAmelCase   :	List[Any]=13   ,     __UpperCAmelCase   :	Optional[Any]=7   ,     __UpperCAmelCase   :	Union[str, Any]=True   ,     __UpperCAmelCase   :	Optional[int]=False   ,     __UpperCAmelCase   :	Any=99   ,     __UpperCAmelCase   :	Optional[int]=16   ,     __UpperCAmelCase   :	List[Any]=2   ,     __UpperCAmelCase   :	Optional[Any]=4   ,     __UpperCAmelCase   :	Any=4   ,     __UpperCAmelCase   :	List[Any]="gelu"   ,     __UpperCAmelCase   :	List[Any]=0.1   ,     __UpperCAmelCase   :	Union[str, Any]=0.1   ,     __UpperCAmelCase   :	Any=32   ,     __UpperCAmelCase   :	Any=2   ,     __UpperCAmelCase   :	int=1   ,     __UpperCAmelCase   :	Any=0   ,     __UpperCAmelCase   :	int=0.02   ,     )		->					Optional[int]:

										"""simple docstring"""



										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_act
										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
										UpperCamelCase_     				= initializer_range







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

										"""simple docstring"""



										UpperCamelCase_     				= np.clip(ids_tensor([self.batch_size, self.seq_length - 1]   ,     self.vocab_size				)   ,     3   ,     self.vocab_size				)
										UpperCamelCase_     				= np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)   ,     dtype=np.intaa				))   ,     -1				)

										UpperCamelCase_     				= shift_tokens_right(__UpperCAmelCase   ,     1   ,     2				)

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







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

										"""simple docstring"""



										UpperCamelCase_				,   UpperCamelCase_     				= self.prepare_config_and_inputs()
										return config, inputs_dict







							def        lowercase__							(    self   :	List[Any]   ,     __UpperCAmelCase   :	Optional[Any]   ,     __UpperCAmelCase   :	str   ,     __UpperCAmelCase   :	Optional[int]				)		->					Optional[int]:

										"""simple docstring"""



										UpperCamelCase_     				= 20
										UpperCamelCase_     				= model_class_name(__UpperCAmelCase				)

										UpperCamelCase_     				= model.encode(inputs_dict['input_ids']				)

										UpperCamelCase_				,   UpperCamelCase_     				= (
										    inputs_dict['decoder_input_ids'],
										    inputs_dict['decoder_attention_mask'],
										)

										UpperCamelCase_     				= model.init_cache(decoder_input_ids.shape[0]   ,     __UpperCAmelCase   ,     __UpperCAmelCase				)
										UpperCamelCase_     				= jnp.ones((decoder_input_ids.shape[0], max_decoder_length)   ,     dtype='i4'				)

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

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

										UpperCamelCase_     				= model.decode(__UpperCAmelCase   ,     __UpperCAmelCase				)

										UpperCamelCase_     				= 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        lowercase__							(    self   :	Union[str, Any]   ,     __UpperCAmelCase   :	List[str]   ,     __UpperCAmelCase   :	Union[str, Any]   ,     __UpperCAmelCase   :	int				)		->					Union[str, Any]:

										"""simple docstring"""



										UpperCamelCase_     				= 20
										UpperCamelCase_     				= model_class_name(__UpperCAmelCase				)

										UpperCamelCase_     				= model.encode(inputs_dict['input_ids']				)

										UpperCamelCase_				,   UpperCamelCase_     				= (
										    inputs_dict['decoder_input_ids'],
										    inputs_dict['decoder_attention_mask'],
										)

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

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

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

										UpperCamelCase_     				= model.decode(__UpperCAmelCase   ,     __UpperCAmelCase   ,     decoder_attention_mask=__UpperCAmelCase				)

										UpperCamelCase_     				= 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     A					(				lowerCamelCase_  ,						unittest.TestCase  ,						lowerCamelCase_       ):
							_SCREAMING_SNAKE_CASE  :		str			  =       True
							_SCREAMING_SNAKE_CASE  :		Tuple			  =       (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
							_SCREAMING_SNAKE_CASE  :		Union[str, Any]			  =       (FlaxMarianMTModel,) if is_flax_available() else ()







							def        lowercase__							(    self   :	List[Any]				)		->					Tuple:

										"""simple docstring"""



										UpperCamelCase_     				= FlaxMarianModelTester(self				)







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

										"""simple docstring"""



										UpperCamelCase_				,   UpperCamelCase_     				= 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        lowercase__							(    self   :	Tuple				)		->					List[str]:

										"""simple docstring"""



										UpperCamelCase_				,   UpperCamelCase_     				= 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        lowercase__							(    self   :	Any				)		->					List[str]:

										"""simple docstring"""



										UpperCamelCase_				,   UpperCamelCase_     				= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													with self.subTest(model_class.__name__				):
																UpperCamelCase_     				= self._prepare_for_class(__UpperCAmelCase   ,     __UpperCAmelCase				)
																UpperCamelCase_     				= model_class(__UpperCAmelCase				)

																@jax.jit
																def encode_jitted(__UpperCAmelCase   :	List[str]   ,     __UpperCAmelCase   :	Optional[int]=None   ,     **__UpperCAmelCase   :	int				):
																			return model.encode(input_ids=__UpperCAmelCase   ,     attention_mask=__UpperCAmelCase				)

																with self.subTest('JIT Enabled'				):
																			UpperCamelCase_     				= encode_jitted(**__UpperCAmelCase				).to_tuple()

																with self.subTest('JIT Disabled'				):
																			with jax.disable_jit():
																						UpperCamelCase_     				= 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        lowercase__							(    self   :	Optional[Any]				)		->					List[str]:

										"""simple docstring"""



										UpperCamelCase_				,   UpperCamelCase_     				= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													with self.subTest(model_class.__name__				):
																UpperCamelCase_     				= model_class(__UpperCAmelCase				)
																UpperCamelCase_     				= model.encode(inputs_dict['input_ids']   ,     inputs_dict['attention_mask']				)

																UpperCamelCase_     				= {
																    '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   :	Optional[int]   ,     __UpperCAmelCase   :	Any   ,     __UpperCAmelCase   :	Optional[int]				):
																			return model.decode(
																			    decoder_input_ids=__UpperCAmelCase   ,     decoder_attention_mask=__UpperCAmelCase   ,     encoder_outputs=__UpperCAmelCase   ,     )

																with self.subTest('JIT Enabled'				):
																			UpperCamelCase_     				= decode_jitted(**__UpperCAmelCase				).to_tuple()

																with self.subTest('JIT Disabled'				):
																			with jax.disable_jit():
																						UpperCamelCase_     				= 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        lowercase__							(    self   :	Dict				)		->					Optional[int]:

										"""simple docstring"""



										for model_class_name in self.all_model_classes:
													UpperCamelCase_     				= model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de'				)
													# FlaxMarianForSequenceClassification expects eos token in input_ids
													UpperCamelCase_     				= np.ones((1, 1)				) * model.config.eos_token_id
													UpperCamelCase_     				= model(__UpperCAmelCase				)
													self.assertIsNotNone(__UpperCAmelCase				)







@require_flax
@require_sentencepiece
@require_tokenizers
class     A					(				unittest.TestCase       ):
							_SCREAMING_SNAKE_CASE  :		Tuple			  =       None
							_SCREAMING_SNAKE_CASE  :		Tuple			  =       None







							@classmethod
							def        lowercase__							(    cls   :	Tuple				)		->					None:

										"""simple docstring"""



										UpperCamelCase_     				= f'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
										return cls







							@cached_property
							def        lowercase__							(    self   :	List[str]				)		->					Optional[Any]:

										"""simple docstring"""



										return MarianTokenizer.from_pretrained(self.model_name				)







							@property
							def        lowercase__							(    self   :	Union[str, Any]				)		->					int:

										"""simple docstring"""



										return self.tokenizer.eos_token_id







							@cached_property
							def        lowercase__							(    self   :	Union[str, Any]				)		->					Optional[int]:

										"""simple docstring"""



										UpperCamelCase_     				= FlaxMarianMTModel.from_pretrained(self.model_name				)
										self.assertEqual(model.config.decoder_start_token_id   ,     model.config.pad_token_id				)
										return model







							def        lowercase__							(    self   :	Union[str, Any]   ,     **__UpperCAmelCase   :	Optional[Any]				)		->					str:

										"""simple docstring"""



										UpperCamelCase_     				= self.translate_src_text(**__UpperCAmelCase				)
										self.assertListEqual(self.expected_text   ,     __UpperCAmelCase				)







							def        lowercase__							(    self   :	List[Any]   ,     **__UpperCAmelCase   :	int				)		->					Optional[Any]:

										"""simple docstring"""



										UpperCamelCase_     				= self.tokenizer(self.src_text   ,     padding=__UpperCAmelCase   ,     return_tensors='np'   ,     **__UpperCAmelCase				)
										UpperCamelCase_     				= self.model.generate(
										    model_inputs.input_ids   ,     attention_mask=model_inputs.attention_mask   ,     num_beams=2   ,     max_length=128   ,     ).sequences
										UpperCamelCase_     				= self.tokenizer.batch_decode(__UpperCAmelCase   ,     skip_special_tokens=__UpperCAmelCase				)
										return generated_words







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







							@slow
							def        lowercase__							(    self   :	Any				)		->					Union[str, Any]:

										"""simple docstring"""



										self._assert_generated_batch_equal_expected()







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







							@slow
							def        lowercase__							(    self   :	Any				)		->					Tuple:

										"""simple docstring"""



										self._assert_generated_batch_equal_expected()







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







							@slow
							def        lowercase__							(    self   :	Any				)		->					Any:

										"""simple docstring"""



										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class     A					(				lowerCamelCase_       ):
							_SCREAMING_SNAKE_CASE  :		Optional[Any]			  =       '''en'''
							_SCREAMING_SNAKE_CASE  :		Optional[Any]			  =       '''de'''
							_SCREAMING_SNAKE_CASE  :		Union[str, Any]			  =       [
							    '''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.''',
							]
							_SCREAMING_SNAKE_CASE  :		Tuple			  =       [
							    '''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        lowercase__							(    self   :	str				)		->					Dict:

										"""simple docstring"""



										self._assert_generated_batch_equal_expected()







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







							@slow
							def        lowercase__							(    self   :	List[str]				)		->					List[Any]:

										"""simple docstring"""



										self._assert_generated_batch_equal_expected()







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







							@slow
							def        lowercase__							(    self   :	Optional[int]				)		->					Optional[Any]:

										"""simple docstring"""



										self._assert_generated_batch_equal_expected()







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

										"""simple docstring"""



										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 CLIPImageProcessor




class     A					(				unittest.TestCase       ):







							def __init__(    self   :	Any   ,     __UpperCAmelCase   :	Optional[int]   ,     __UpperCAmelCase   :	List[Any]=7   ,     __UpperCAmelCase   :	Union[str, Any]=3   ,     __UpperCAmelCase   :	Optional[Any]=18   ,     __UpperCAmelCase   :	List[str]=30   ,     __UpperCAmelCase   :	int=400   ,     __UpperCAmelCase   :	List[Any]=True   ,     __UpperCAmelCase   :	Tuple=None   ,     __UpperCAmelCase   :	Optional[Any]=True   ,     __UpperCAmelCase   :	Any=None   ,     __UpperCAmelCase   :	Optional[int]=True   ,     __UpperCAmelCase   :	List[str]=[0.48_145_466, 0.4_578_275, 0.40_821_073]   ,     __UpperCAmelCase   :	List[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711]   ,     __UpperCAmelCase   :	Dict=True   ,     )		->					Tuple:

										"""simple docstring"""



										UpperCamelCase_     				= size if size is not None else {'shortest_edge': 20}
										UpperCamelCase_     				= crop_size if crop_size is not None else {'height': 18, 'width': 18}
										UpperCamelCase_     				= parent
										UpperCamelCase_     				= batch_size
										UpperCamelCase_     				= num_channels
										UpperCamelCase_     				= image_size
										UpperCamelCase_     				= min_resolution
										UpperCamelCase_     				= max_resolution
										UpperCamelCase_     				= do_resize
										UpperCamelCase_     				= size
										UpperCamelCase_     				= do_center_crop
										UpperCamelCase_     				= crop_size
										UpperCamelCase_     				= do_normalize
										UpperCamelCase_     				= image_mean
										UpperCamelCase_     				= image_std
										UpperCamelCase_     				= do_convert_rgb







							def        lowercase__							(    self   :	Tuple				)		->					List[Any]:

										"""simple docstring"""



										return {
										    "do_resize": self.do_resize,
										    "size": self.size,
										    "do_center_crop": self.do_center_crop,
										    "crop_size": self.crop_size,
										    "do_normalize": self.do_normalize,
										    "image_mean": self.image_mean,
										    "image_std": self.image_std,
										    "do_convert_rgb": self.do_convert_rgb,
										}







							def        lowercase__							(    self   :	List[Any]   ,     __UpperCAmelCase   :	str=False   ,     __UpperCAmelCase   :	Tuple=False   ,     __UpperCAmelCase   :	Optional[int]=False				)		->					Any:

										"""simple docstring"""



										assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

										if equal_resolution:
													UpperCamelCase_     				= []
													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:
													UpperCamelCase_     				= []
													for i in range(self.batch_size				):
																UpperCamelCase_				,   UpperCamelCase_     				= 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
													UpperCamelCase_     				= [Image.fromarray(np.moveaxis(__UpperCAmelCase   ,     0   ,     -1				)				) for x in image_inputs]

										if torchify:
													UpperCamelCase_     				= [torch.from_numpy(__UpperCAmelCase				) for x in image_inputs]

										return image_inputs







@require_torch
@require_vision
class     A					(				lowerCamelCase_  ,						unittest.TestCase       ):
							_SCREAMING_SNAKE_CASE  :		Any			  =       CLIPImageProcessor if is_vision_available() else None







							def        lowercase__							(    self   :	Dict				)		->					List[str]:

										"""simple docstring"""



										UpperCamelCase_     				= CLIPImageProcessingTester(self				)







							@property
							def        lowercase__							(    self   :	Optional[int]				)		->					Optional[Any]:

										"""simple docstring"""



										return self.image_processor_tester.prepare_image_processor_dict()







							def        lowercase__							(    self   :	Tuple				)		->					Tuple:

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class(**self.image_processor_dict				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'do_resize'				)				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'size'				)				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'do_center_crop'				)				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'center_crop'				)				)
										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        lowercase__							(    self   :	Optional[int]				)		->					Tuple:

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class.from_dict(self.image_processor_dict				)
										self.assertEqual(image_processor.size   ,     {'shortest_edge': 20}				)
										self.assertEqual(image_processor.crop_size   ,     {'height': 18, 'width': 18}				)

										UpperCamelCase_     				= self.image_processing_class.from_dict(self.image_processor_dict   ,     size=42   ,     crop_size=84				)
										self.assertEqual(image_processor.size   ,     {'shortest_edge': 42}				)
										self.assertEqual(image_processor.crop_size   ,     {'height': 84, 'width': 84}				)







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

										"""simple docstring"""



										pass







							def        lowercase__							(    self   :	int				)		->					Optional[int]:

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class(**self.image_processor_dict				)
										# create random PIL images
										UpperCamelCase_     				= self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCAmelCase				)
										for image in image_inputs:
													self.assertIsInstance(__UpperCAmelCase   ,     Image.Image				)

										# Test not batched input
										UpperCamelCase_     				= image_processing(image_inputs[0]   ,     return_tensors='pt'				).pixel_values
										self.assertEqual(
										    encoded_images.shape   ,     (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )

										# Test batched
										UpperCamelCase_     				= image_processing(__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.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )







							def        lowercase__							(    self   :	Optional[Any]				)		->					Tuple:

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class(**self.image_processor_dict				)
										# create random numpy tensors
										UpperCamelCase_     				= 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
										UpperCamelCase_     				= image_processing(image_inputs[0]   ,     return_tensors='pt'				).pixel_values
										self.assertEqual(
										    encoded_images.shape   ,     (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )

										# Test batched
										UpperCamelCase_     				= image_processing(__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.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )







							def        lowercase__							(    self   :	Optional[Any]				)		->					Any:

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class(**self.image_processor_dict				)
										# create random PyTorch tensors
										UpperCamelCase_     				= 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
										UpperCamelCase_     				= image_processing(image_inputs[0]   ,     return_tensors='pt'				).pixel_values
										self.assertEqual(
										    encoded_images.shape   ,     (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )

										# Test batched
										UpperCamelCase_     				= image_processing(__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.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )







@require_torch
@require_vision
class     A					(				lowerCamelCase_  ,						unittest.TestCase       ):
							_SCREAMING_SNAKE_CASE  :		str			  =       CLIPImageProcessor if is_vision_available() else None







							def        lowercase__							(    self   :	str				)		->					Any:

										"""simple docstring"""



										UpperCamelCase_     				= CLIPImageProcessingTester(self   ,     num_channels=4				)
										UpperCamelCase_     				= 3







							@property
							def        lowercase__							(    self   :	Dict				)		->					str:

										"""simple docstring"""



										return self.image_processor_tester.prepare_image_processor_dict()







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

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class(**self.image_processor_dict				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'do_resize'				)				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'size'				)				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'do_center_crop'				)				)
										self.assertTrue(hasattr(__UpperCAmelCase   ,     'center_crop'				)				)
										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        lowercase__							(    self   :	int				)		->					Any:

										"""simple docstring"""



										pass







							def        lowercase__							(    self   :	Any				)		->					Optional[int]:

										"""simple docstring"""



										UpperCamelCase_     				= self.image_processing_class(**self.image_processor_dict				)
										# create random PIL images
										UpperCamelCase_     				= self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCAmelCase				)
										for image in image_inputs:
													self.assertIsInstance(__UpperCAmelCase   ,     Image.Image				)

										# Test not batched input
										UpperCamelCase_     				= image_processing(image_inputs[0]   ,     return_tensors='pt'				).pixel_values
										self.assertEqual(
										    encoded_images.shape   ,     (
										        1,
										        self.expected_encoded_image_num_channels,
										        self.image_processor_tester.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )

										# Test batched
										UpperCamelCase_     				= image_processing(__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.crop_size['height'],
										        self.image_processor_tester.crop_size['width'],
										    )   ,     )
