






from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__UpperCamelCase      :      Any     						=						logging.get_logger(__name__)


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:int   =       ['pixel_values']







	def __init__(  self      :							List[str]       ,				_lowerCAmelCase      :							bool = True       ,				_lowerCAmelCase      :							Dict[str, int] = None       ,				_lowerCAmelCase      :							PILImageResampling = PILImageResampling.BICUBIC       ,				_lowerCAmelCase      :							bool = True       ,				_lowerCAmelCase      :							Dict[str, int] = None       ,				_lowerCAmelCase      :							bool = True       ,				_lowerCAmelCase      :							Union[int, float] = 1 / 255       ,				_lowerCAmelCase      :							bool = True       ,				_lowerCAmelCase      :							Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN       ,				_lowerCAmelCase      :							Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD       ,				**_lowerCAmelCase      :							str       ,				)		-> None:
		"""simple docstring"""







		super().__init__(**_lowerCAmelCase			)
		__lowercase             =  size if size is not None else {"""shortest_edge""": 224}
		__lowercase             =  get_size_dict(_lowerCAmelCase       ,				default_to_square=_lowerCAmelCase			)
		__lowercase             =  crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
		__lowercase             =  get_size_dict(_lowerCAmelCase       ,				param_name="""crop_size"""			)

		__lowercase             =  do_resize
		__lowercase             =  size
		__lowercase             =  resample
		__lowercase             =  do_center_crop
		__lowercase             =  crop_size
		__lowercase             =  do_rescale
		__lowercase             =  rescale_factor
		__lowercase             =  do_normalize
		__lowercase             =  image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
		__lowercase             =  image_std if image_std is not None else IMAGENET_DEFAULT_STD







	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							Dict[str, int]       ,				_lowerCAmelCase      :							PILImageResampling = PILImageResampling.BICUBIC       ,				_lowerCAmelCase      :							Optional[Union[str, ChannelDimension]] = None       ,				**_lowerCAmelCase      :							Union[str, Any]       ,				)		-> np.ndarray:
		"""simple docstring"""







		__lowercase             =  get_size_dict(_lowerCAmelCase       ,				default_to_square=_lowerCAmelCase			)
		# size_dict is a dict with either keys "height" and "width" or "shortest_edge"
		if "shortest_edge" in size:
			__lowercase             =  int((256 / 224) * size["""shortest_edge"""]			)
			__lowercase             =  get_resize_output_image_size(_lowerCAmelCase       ,				size=_lowerCAmelCase       ,				default_to_square=_lowerCAmelCase			)
			__lowercase             =  {"""height""": output_size[0], """width""": output_size[1]}
		if "height" not in size_dict or "width" not in size_dict:
			raise ValueError(
			    F'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'			)
		return resize(
		    _lowerCAmelCase       ,				size=(size_dict["""height"""], size_dict["""width"""])       ,				resample=_lowerCAmelCase       ,				data_format=_lowerCAmelCase       ,				**_lowerCAmelCase			)







	def  _a   (  self      :							str       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							Dict[str, int]       ,				_lowerCAmelCase      :							Optional[Union[str, ChannelDimension]] = None       ,				**_lowerCAmelCase      :							int       ,				)		-> np.ndarray:
		"""simple docstring"""







		__lowercase             =  get_size_dict(_lowerCAmelCase			)
		if "height" not in size or "width" not in size:
			raise ValueError(F'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'			)
		return center_crop(_lowerCAmelCase       ,				size=(size["""height"""], size["""width"""])       ,				data_format=_lowerCAmelCase       ,				**_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							Union[int, float]       ,				_lowerCAmelCase      :							Optional[Union[str, ChannelDimension]] = None       ,				**_lowerCAmelCase      :							List[Any]       ,				)		-> np.ndarray:
		"""simple docstring"""







		return rescale(_lowerCAmelCase       ,				scale=_lowerCAmelCase       ,				data_format=_lowerCAmelCase       ,				**_lowerCAmelCase			)







	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							Union[float, List[float]]       ,				_lowerCAmelCase      :							Union[float, List[float]]       ,				_lowerCAmelCase      :							Optional[Union[str, ChannelDimension]] = None       ,				**_lowerCAmelCase      :							Tuple       ,				)		-> np.ndarray:
		"""simple docstring"""







		return normalize(_lowerCAmelCase       ,				mean=_lowerCAmelCase       ,				std=_lowerCAmelCase       ,				data_format=_lowerCAmelCase       ,				**_lowerCAmelCase			)







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							ImageInput       ,				_lowerCAmelCase      :							Optional[bool] = None       ,				_lowerCAmelCase      :							Optional[Dict[str, int]] = None       ,				_lowerCAmelCase      :							PILImageResampling = None       ,				_lowerCAmelCase      :							Optional[bool] = None       ,				_lowerCAmelCase      :							Optional[Dict[str, int]] = None       ,				_lowerCAmelCase      :							Optional[bool] = None       ,				_lowerCAmelCase      :							Optional[float] = None       ,				_lowerCAmelCase      :							Optional[bool] = None       ,				_lowerCAmelCase      :							Optional[Union[float, Iterable[float]]] = None       ,				_lowerCAmelCase      :							Optional[Union[float, Iterable[float]]] = None       ,				_lowerCAmelCase      :							Optional[TensorType] = None       ,				_lowerCAmelCase      :							ChannelDimension = ChannelDimension.FIRST       ,				**_lowerCAmelCase      :							List[Any]       ,				)		-> BatchFeature:
		"""simple docstring"""







		__lowercase             =  do_resize if do_resize is not None else self.do_resize
		__lowercase             =  resample if resample is not None else self.resample
		__lowercase             =  do_center_crop if do_center_crop is not None else self.do_center_crop
		__lowercase             =  do_rescale if do_rescale is not None else self.do_rescale
		__lowercase             =  rescale_factor if rescale_factor is not None else self.rescale_factor
		__lowercase             =  do_normalize if do_normalize is not None else self.do_normalize
		__lowercase             =  image_mean if image_mean is not None else self.image_mean
		__lowercase             =  image_std if image_std is not None else self.image_std

		__lowercase             =  size if size is not None else self.size
		__lowercase             =  get_size_dict(_lowerCAmelCase       ,				default_to_square=_lowerCAmelCase			)
		__lowercase             =  crop_size if crop_size is not None else self.crop_size
		__lowercase             =  get_size_dict(_lowerCAmelCase       ,				param_name="""crop_size"""			)

		__lowercase             =  make_list_of_images(_lowerCAmelCase			)

		if not valid_images(_lowerCAmelCase			):
			raise ValueError(
			    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
			    """torch.Tensor, tf.Tensor or jax.ndarray."""			)

		if do_resize and size is None:
			raise ValueError("""Size must be specified if do_resize is True."""			)

		if do_center_crop and crop_size is None:
			raise ValueError("""Crop size must be specified if do_center_crop is True."""			)

		if do_rescale and rescale_factor is None:
			raise ValueError("""Rescale factor must be specified if do_rescale is True."""			)

		if do_normalize and (image_mean is None or image_std is None):
			raise ValueError("""Image mean and std must be specified if do_normalize is True."""			)

		# All transformations expect numpy arrays.
		__lowercase             =  [to_numpy_array(_lowerCAmelCase			) for image in images]

		if do_resize:
			__lowercase             =  [self.resize(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			) for image in images]

		if do_center_crop:
			__lowercase             =  [self.center_crop(_lowerCAmelCase       ,				_lowerCAmelCase			) for image in images]

		if do_rescale:
			__lowercase             =  [self.rescale(_lowerCAmelCase       ,				_lowerCAmelCase			) for image in images]

		if do_normalize:
			__lowercase             =  [self.normalize(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			) for image in images]

		__lowercase             =  [to_channel_dimension_format(_lowerCAmelCase       ,				_lowerCAmelCase			) for image in images]

		__lowercase             =  {"""pixel_values""": images}
		return BatchFeature(data=_lowerCAmelCase       ,				tensor_type=_lowerCAmelCase			)














from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
						from transformers import (
						    TFBertModel,
						    TFCLIPVisionModel,
						    TFDeiTModel,
						    TFRobertaModel,
						    TFVisionTextDualEncoderModel,
						    TFViTModel,
						    VisionTextDualEncoderConfig,
						)

if is_vision_available():
						from PIL import Image

						from transformers import VisionTextDualEncoderProcessor





def 				snake_case  (     lowerCamelCase					):




	'''simple docstring'''







	if isinstance(lowerCamelCase				,  collections.abc.Iterable					):
		return x
	return (x, x)


@require_tf
class        __UpperCamelCase    :







	def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Dict			)		-> Optional[int]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Any			)		-> Optional[Any]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							int       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Dict=None       ,				**_lowerCAmelCase      :							int			)		-> str:
		"""simple docstring"""







		__lowercase             =  VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCAmelCase       ,				_lowerCAmelCase			)

		__lowercase             =  TFVisionTextDualEncoderModel(_lowerCAmelCase			)

		__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)

		self.assertEqual(output["""text_embeds"""].shape       ,				(input_ids.shape[0], config.projection_dim)			)
		self.assertEqual(output["""image_embeds"""].shape       ,				(pixel_values.shape[0], config.projection_dim)			)







	def  _a   (  self      :							str       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							int=None       ,				**_lowerCAmelCase      :							Dict			)		-> Tuple:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)

		self.assertEqual(output["""text_embeds"""].shape       ,				(input_ids.shape[0], model.config.projection_dim)			)
		self.assertEqual(output["""image_embeds"""].shape       ,				(pixel_values.shape[0], model.config.projection_dim)			)







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Any=None       ,				**_lowerCAmelCase      :							str			)		-> Tuple:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  {"""vision_model""": vision_model, """text_model""": text_model}
		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCAmelCase			)

		__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)

		self.assertEqual(output["""text_embeds"""].shape       ,				(input_ids.shape[0], model.config.projection_dim)			)
		self.assertEqual(output["""image_embeds"""].shape       ,				(pixel_values.shape[0], model.config.projection_dim)			)







	def  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							List[Any]=None       ,				**_lowerCAmelCase      :							Any			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)
		__lowercase             =  output[0].numpy()

		with tempfile.TemporaryDirectory() as tmpdirname:
			model.save_pretrained(_lowerCAmelCase			)
			__lowercase             =  TFVisionTextDualEncoderModel.from_pretrained(_lowerCAmelCase			)

			__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)
			__lowercase             =  after_output[0].numpy()
			__lowercase             =  np.amax(np.abs(out_a - out_a			)			)
			self.assertLessEqual(_lowerCAmelCase       ,				1e-5			)







	def  _a   (  self      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Optional[int]=None       ,				**_lowerCAmelCase      :							Optional[int]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(
		    input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				output_attentions=_lowerCAmelCase			)

		__lowercase             =  output.vision_model_output.attentions
		self.assertEqual(len(_lowerCAmelCase			)       ,				vision_config.num_hidden_layers			)

		# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
		__lowercase             =  to_atuple(vision_model.config.image_size			)
		__lowercase             =  to_atuple(vision_model.config.patch_size			)
		__lowercase             =  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
		__lowercase             =  num_patches + 1
		self.assertEqual(vision_attentions[0].shape[-3:]       ,				(vision_config.num_attention_heads, seq_len, seq_len)			)

		__lowercase             =  output.text_model_output.attentions
		self.assertEqual(len(_lowerCAmelCase			)       ,				text_config.num_hidden_layers			)

		self.assertEqual(
		    text_attentions[0].shape[-3:]       ,				(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])       ,				)







	def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							float			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  np.abs((a - b)			).max()
		self.assertLessEqual(_lowerCAmelCase       ,				_lowerCAmelCase       ,				F'Difference between torch and flax is {diff} (>= {tol}).'			)







	def  _a   (  self      :							List[Any]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_vision_text_dual_encoder_model(**_lowerCAmelCase			)







	def  _a   (  self      :							int			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_model_from_pretrained_configs(**_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_vision_text_dual_encoder_from_pretrained(**_lowerCAmelCase			)







	def  _a   (  self      :							List[str]			)		-> str:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_save_load(**_lowerCAmelCase			)







	def  _a   (  self      :							Dict			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_vision_text_output_attention(**_lowerCAmelCase			)







	@slow
	def  _a   (  self      :							Optional[int]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_pretrained_model_and_inputs()

		__lowercase             =  model_a(**_lowerCAmelCase			)
		__lowercase             =  outputs[0].numpy()

		with tempfile.TemporaryDirectory() as tmp_dirname:
			model_a.save_pretrained(_lowerCAmelCase			)
			__lowercase             =  TFVisionTextDualEncoderModel.from_pretrained(_lowerCAmelCase			)

			__lowercase             =  model_a(**_lowerCAmelCase			)
			__lowercase             =  after_outputs[0].numpy()
			__lowercase             =  np.amax(np.abs(out_a - out_a			)			)
			self.assertLessEqual(_lowerCAmelCase       ,				1e-5			)


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):







	def  _a   (  self      :							Optional[int]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
		    """hf-internal-testing/tiny-random-vit"""       ,				"""hf-internal-testing/tiny-random-bert"""			)
		__lowercase             =  13
		__lowercase             =  floats_tensor(
		    [
		        batch_size,
		        model.vision_model.config.num_channels,
		        model.vision_model.config.image_size,
		        model.vision_model.config.image_size,
		    ]			)
		__lowercase             =  ids_tensor([batch_size, 4]       ,				model.text_model.config.vocab_size			)
		__lowercase             =  random_attention_mask([batch_size, 4]			)
		__lowercase             =  {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

		return model, inputs







	def  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  TFViTModel(_lowerCAmelCase       ,				name="""vision_model"""			)
		__lowercase             =  TFBertModel(_lowerCAmelCase       ,				name="""text_model"""			)
		return vision_model, text_model







	def  _a   (  self      :							Dict			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  TFViTModelTester(self			)
		__lowercase             =  TFBertModelTester(self			)
		__lowercase             =  vit_model_tester.prepare_config_and_inputs()
		__lowercase             =  bert_model_tester.prepare_config_and_inputs()

		__lowercase       ,						__lowercase       ,						__lowercase             =  vision_config_and_inputs

		(
		    (
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						
		)             =  text_config_and_inputs

		return {
		    "text_config": text_config,
		    "vision_config": vision_config,
		    "pixel_values": pixel_values,
		    "attention_mask": input_mask,
		    "input_ids": input_ids,
		    "text_token_type_ids": token_type_ids,
		    "text_sequence_labels": sequence_labels,
		    "text_token_labels": token_labels,
		    "text_choice_labels": choice_labels,
		}


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):







	def  _a   (  self      :							Tuple			)		-> Any:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
		    """Rocketknight1/tiny-random-deit-tf"""       ,				"""hf-internal-testing/tiny-random-roberta"""			)
		__lowercase             =  13
		__lowercase             =  floats_tensor(
		    [
		        batch_size,
		        model.vision_model.config.num_channels,
		        model.vision_model.config.image_size,
		        model.vision_model.config.image_size,
		    ]			)
		__lowercase             =  ids_tensor([batch_size, 4]       ,				model.text_model.config.vocab_size			)
		__lowercase             =  random_attention_mask([batch_size, 4]			)
		__lowercase             =  {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

		return model, inputs







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							int=None       ,				**_lowerCAmelCase      :							Tuple			)		-> Dict:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(
		    input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				output_attentions=_lowerCAmelCase			)

		__lowercase             =  output.vision_model_output.attentions
		self.assertEqual(len(_lowerCAmelCase			)       ,				vision_config.num_hidden_layers			)

		# in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
		__lowercase             =  to_atuple(vision_model.config.image_size			)
		__lowercase             =  to_atuple(vision_model.config.patch_size			)
		__lowercase             =  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
		__lowercase             =  num_patches + 2
		self.assertEqual(vision_attentions[0].shape[-3:]       ,				(vision_config.num_attention_heads, seq_len, seq_len)			)

		__lowercase             =  output.text_model_output.attentions
		self.assertEqual(len(_lowerCAmelCase			)       ,				text_config.num_hidden_layers			)

		self.assertEqual(
		    text_attentions[0].shape[-3:]       ,				(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])       ,				)







	def  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Dict			)		-> int:
		"""simple docstring"""







		__lowercase             =  TFDeiTModel(_lowerCAmelCase       ,				name="""vision_model"""			)
		__lowercase             =  TFRobertaModel(_lowerCAmelCase       ,				name="""text_model"""			)
		return vision_model, text_model







	def  _a   (  self      :							Tuple			)		-> str:
		"""simple docstring"""







		__lowercase             =  TFDeiTModelTester(self			)
		__lowercase             =  TFRobertaModelTester(self			)
		__lowercase             =  vit_model_tester.prepare_config_and_inputs()
		__lowercase             =  bert_model_tester.prepare_config_and_inputs()

		__lowercase       ,						__lowercase       ,						__lowercase             =  vision_config_and_inputs

		(
		    (
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						
		)             =  text_config_and_inputs

		return {
		    "text_config": text_config,
		    "vision_config": vision_config,
		    "pixel_values": pixel_values,
		    "attention_mask": input_mask,
		    "input_ids": input_ids,
		    "text_token_type_ids": token_type_ids,
		    "text_sequence_labels": sequence_labels,
		    "text_token_labels": token_labels,
		    "text_choice_labels": choice_labels,
		}


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):







	def  _a   (  self      :							int			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
		    """Rocketknight1/tiny-random-clip-tf"""       ,				"""hf-internal-testing/tiny-random-bert"""			)
		__lowercase             =  13
		__lowercase             =  floats_tensor(
		    [
		        batch_size,
		        model.vision_model.config.num_channels,
		        model.vision_model.config.image_size,
		        model.vision_model.config.image_size,
		    ]			)
		__lowercase             =  ids_tensor([batch_size, 4]       ,				model.text_model.config.vocab_size			)
		__lowercase             =  random_attention_mask([batch_size, 4]			)
		__lowercase             =  {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

		return model, inputs







	def  _a   (  self      :							Optional[int]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Union[str, Any]			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  TFCLIPVisionModel(_lowerCAmelCase       ,				name="""vision_model"""			)
		__lowercase             =  TFBertModel(_lowerCAmelCase       ,				name="""text_model"""			)
		return vision_model, text_model







	def  _a   (  self      :							Union[str, Any]			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  TFCLIPVisionModelTester(self			)
		__lowercase             =  TFBertModelTester(self			)
		__lowercase             =  clip_model_tester.prepare_config_and_inputs()
		__lowercase             =  bert_model_tester.prepare_config_and_inputs()

		__lowercase       ,						__lowercase             =  vision_config_and_inputs

		(
		    (
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						
		)             =  text_config_and_inputs

		return {
		    "text_config": text_config,
		    "vision_config": vision_config,
		    "pixel_values": pixel_values,
		    "attention_mask": input_mask,
		    "input_ids": input_ids,
		    "text_token_type_ids": token_type_ids,
		    "text_sequence_labels": sequence_labels,
		    "text_token_labels": token_labels,
		    "text_choice_labels": choice_labels,
		}


@require_vision
@require_tf
class        __UpperCamelCase    (     unittest.TestCase   ):







	@slow
	def  _a   (  self      :							int			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_pretrained(
		    """clip-italian/clip-italian"""       ,				logit_scale_init_value=1.0       ,				from_pt=_lowerCAmelCase			)
		__lowercase             =  VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""			)

		__lowercase             =  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
		__lowercase             =  processor(
		    text=["""una foto di un gatto""", """una foto di un cane"""]       ,				images=_lowerCAmelCase       ,				padding=_lowerCAmelCase       ,				return_tensors="""np"""			)

		__lowercase             =  model(**_lowerCAmelCase			)

		# verify the logits
		self.assertEqual(outputs.logits_per_image.shape       ,				(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])			)
		self.assertEqual(
		    outputs.logits_per_text.shape       ,				(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])       ,				)

		__lowercase             =  np.array([[1.2_284_727, 0.3_104_122]]			)

		self.assertTrue(np.allclose(outputs.logits_per_image.numpy()       ,				_lowerCAmelCase       ,				atol=1e-3			)			)

