





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       A__(		__lowerCAmelCase ):
				if isinstance(__lowerCAmelCase	,			collections.abc.Iterable ):
								return x
				return (x, x)


@require_tf
class 			lowercase				:



						"""simple docstring"""

						def 		__UpperCAmelCase       (    self			:		Tuple ,				lowerCamelCase_			:		List[str] ,				lowerCamelCase_			:		int					):





										'''simple docstring'''







										pass







						def 		__UpperCAmelCase       (    self			:		Any					):





										'''simple docstring'''







										pass







						def 		__UpperCAmelCase       (    self			:		Any					):





										'''simple docstring'''







										pass







						def 		__UpperCAmelCase       (    self			:		Optional[int] ,				lowerCamelCase_			:		Optional[Any] ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		int ,				lowerCamelCase_			:		Optional[int] ,				lowerCamelCase_			:		Union[str, Any]=None ,				**lowerCamelCase_			:		int					):





										'''simple docstring'''







										_snake_case :			str  						=   VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase_ ,				lowerCamelCase_					)

										_snake_case :			str  						=   TFVisionTextDualEncoderModel(lowerCamelCase_					)

										_snake_case :			Union[str, Any]  						=   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 		__UpperCAmelCase       (    self			:		int ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		int ,				lowerCamelCase_			:		List[str] ,				lowerCamelCase_			:		Any=None ,				**lowerCamelCase_			:		Optional[Any]					):





										'''simple docstring'''







										_snake_case						,			_snake_case :			Tuple  						=   self.get_vision_text_model(lowerCamelCase_ ,				lowerCamelCase_					)
										_snake_case :			Optional[Any]  						=   TFVisionTextDualEncoderModel(vision_model=lowerCamelCase_ ,				text_model=lowerCamelCase_					)

										_snake_case :			Optional[int]  						=   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 		__UpperCAmelCase       (    self			:		Any ,				lowerCamelCase_			:		Optional[int] ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		Optional[Any] ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		str=None ,				**lowerCamelCase_			:		Optional[int]					):





										'''simple docstring'''







										_snake_case						,			_snake_case :			Union[str, Any]  						=   self.get_vision_text_model(lowerCamelCase_ ,				lowerCamelCase_					)
										_snake_case :			Union[str, Any]  						=   {'vision_model': vision_model, 'text_model': text_model}
										_snake_case :			Optional[int]  						=   TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase_					)

										_snake_case :			Dict  						=   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 		__UpperCAmelCase       (    self			:		Any ,				lowerCamelCase_			:		str ,				lowerCamelCase_			:		Optional[int] ,				lowerCamelCase_			:		Dict ,				lowerCamelCase_			:		Union[str, Any] ,				lowerCamelCase_			:		int=None ,				**lowerCamelCase_			:		List[Any]					):





										'''simple docstring'''







										_snake_case						,			_snake_case :			int  						=   self.get_vision_text_model(lowerCamelCase_ ,				lowerCamelCase_					)
										_snake_case :			List[str]  						=   TFVisionTextDualEncoderModel(vision_model=lowerCamelCase_ ,				text_model=lowerCamelCase_					)

										_snake_case :			Optional[Any]  						=   model(input_ids=lowerCamelCase_ ,				pixel_values=lowerCamelCase_ ,				attention_mask=lowerCamelCase_					)
										_snake_case :			int  						=   output[0].numpy()

										with tempfile.TemporaryDirectory() as tmpdirname:
														model.save_pretrained(lowerCamelCase_					)
														_snake_case :			List[Any]  						=   TFVisionTextDualEncoderModel.from_pretrained(lowerCamelCase_					)

														_snake_case :			Optional[int]  						=   model(input_ids=lowerCamelCase_ ,				pixel_values=lowerCamelCase_ ,				attention_mask=lowerCamelCase_					)
														_snake_case :			Optional[int]  						=   after_output[0].numpy()
														_snake_case :			Optional[Any]  						=   np.amax(np.abs(out_a - out_a					)					)
														self.assertLessEqual(lowerCamelCase_ ,				1e-5					)







						def 		__UpperCAmelCase       (    self			:		Optional[Any] ,				lowerCamelCase_			:		List[str] ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		Optional[int] ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		int=None ,				**lowerCamelCase_			:		int					):





										'''simple docstring'''







										_snake_case						,			_snake_case :			Optional[int]  						=   self.get_vision_text_model(lowerCamelCase_ ,				lowerCamelCase_					)
										_snake_case :			Union[str, Any]  						=   TFVisionTextDualEncoderModel(vision_model=lowerCamelCase_ ,				text_model=lowerCamelCase_					)

										_snake_case :			int  						=   model(
										    input_ids=lowerCamelCase_ ,				pixel_values=lowerCamelCase_ ,				attention_mask=lowerCamelCase_ ,				output_attentions=lowerCamelCase_					)

										_snake_case :			Tuple  						=   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)
										_snake_case :			str  						=   to_atuple(vision_model.config.image_size					)
										_snake_case :			Optional[int]  						=   to_atuple(vision_model.config.patch_size					)
										_snake_case :			Tuple  						=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
										_snake_case :			int  						=   num_patches + 1
										self.assertEqual(vision_attentions[0].shape[-3:] ,				(vision_config.num_attention_heads, seq_len, seq_len)					)

										_snake_case :			Optional[int]  						=   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 		__UpperCAmelCase       (    self			:		str ,				lowerCamelCase_			:		np.ndarray ,				lowerCamelCase_			:		np.ndarray ,				lowerCamelCase_			:		float					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   np.abs((a - b)					).max()
										self.assertLessEqual(lowerCamelCase_ ,				lowerCamelCase_ ,				f'''Difference between torch and flax is {diff} (>= {tol}).'''					)







						def 		__UpperCAmelCase       (    self			:		Optional[Any]					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   self.prepare_config_and_inputs()
										self.check_vision_text_dual_encoder_model(**lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Tuple					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   self.prepare_config_and_inputs()
										self.check_model_from_pretrained_configs(**lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Any					):





										'''simple docstring'''







										_snake_case :			Any  						=   self.prepare_config_and_inputs()
										self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Any					):





										'''simple docstring'''







										_snake_case :			int  						=   self.prepare_config_and_inputs()
										self.check_save_load(**lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		List[Any]					):





										'''simple docstring'''







										_snake_case :			Union[str, Any]  						=   self.prepare_config_and_inputs()
										self.check_vision_text_output_attention(**lowerCamelCase_					)







						@slow
						def 		__UpperCAmelCase       (    self			:		List[Any]					):





										'''simple docstring'''







										_snake_case						,			_snake_case :			Union[str, Any]  						=   self.get_pretrained_model_and_inputs()

										_snake_case :			List[Any]  						=   model_a(**lowerCamelCase_					)
										_snake_case :			Tuple  						=   outputs[0].numpy()

										with tempfile.TemporaryDirectory() as tmp_dirname:
														model_a.save_pretrained(lowerCamelCase_					)
														_snake_case :			Any  						=   TFVisionTextDualEncoderModel.from_pretrained(lowerCamelCase_					)

														_snake_case :			Optional[Any]  						=   model_a(**lowerCamelCase_					)
														_snake_case :			List[Any]  						=   after_outputs[0].numpy()
														_snake_case :			Optional[Any]  						=   np.amax(np.abs(out_a - out_a					)					)
														self.assertLessEqual(lowerCamelCase_ ,				1e-5					)



@require_tf
class 			lowercase				(							a_		,			unittest.TestCase     ):



						"""simple docstring"""

						def 		__UpperCAmelCase       (    self			:		Optional[int]					):





										'''simple docstring'''







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

										return model, inputs







						def 		__UpperCAmelCase       (    self			:		int ,				lowerCamelCase_			:		Any ,				lowerCamelCase_			:		Dict					):





										'''simple docstring'''







										_snake_case :			int  						=   TFViTModel(lowerCamelCase_ ,				name='vision_model'					)
										_snake_case :			Any  						=   TFBertModel(lowerCamelCase_ ,				name='text_model'					)
										return vision_model, text_model







						def 		__UpperCAmelCase       (    self			:		Optional[int]					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   TFViTModelTester(self					)
										_snake_case :			Union[str, Any]  						=   TFBertModelTester(self					)
										_snake_case :			str  						=   vit_model_tester.prepare_config_and_inputs()
										_snake_case :			Optional[int]  						=   bert_model_tester.prepare_config_and_inputs()

										_snake_case						,			_snake_case						,			_snake_case :			Dict  						=   vision_config_and_inputs

										(
										    (
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			
										) :			str  						=   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 			lowercase				(							a_		,			unittest.TestCase     ):



						"""simple docstring"""

						def 		__UpperCAmelCase       (    self			:		Tuple					):





										'''simple docstring'''







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

										return model, inputs







						def 		__UpperCAmelCase       (    self			:		Tuple ,				lowerCamelCase_			:		Optional[int] ,				lowerCamelCase_			:		Any ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		Any=None ,				**lowerCamelCase_			:		List[str]					):





										'''simple docstring'''







										_snake_case						,			_snake_case :			Dict  						=   self.get_vision_text_model(lowerCamelCase_ ,				lowerCamelCase_					)
										_snake_case :			Tuple  						=   TFVisionTextDualEncoderModel(vision_model=lowerCamelCase_ ,				text_model=lowerCamelCase_					)

										_snake_case :			str  						=   model(
										    input_ids=lowerCamelCase_ ,				pixel_values=lowerCamelCase_ ,				attention_mask=lowerCamelCase_ ,				output_attentions=lowerCamelCase_					)

										_snake_case :			Any  						=   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)
										_snake_case :			int  						=   to_atuple(vision_model.config.image_size					)
										_snake_case :			int  						=   to_atuple(vision_model.config.patch_size					)
										_snake_case :			List[Any]  						=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
										_snake_case :			Tuple  						=   num_patches + 2
										self.assertEqual(vision_attentions[0].shape[-3:] ,				(vision_config.num_attention_heads, seq_len, seq_len)					)

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





										'''simple docstring'''







										_snake_case :			Any  						=   TFDeiTModel(lowerCamelCase_ ,				name='vision_model'					)
										_snake_case :			Optional[Any]  						=   TFRobertaModel(lowerCamelCase_ ,				name='text_model'					)
										return vision_model, text_model







						def 		__UpperCAmelCase       (    self			:		List[str]					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   TFDeiTModelTester(self					)
										_snake_case :			Tuple  						=   TFRobertaModelTester(self					)
										_snake_case :			str  						=   vit_model_tester.prepare_config_and_inputs()
										_snake_case :			Optional[int]  						=   bert_model_tester.prepare_config_and_inputs()

										_snake_case						,			_snake_case						,			_snake_case :			Optional[Any]  						=   vision_config_and_inputs

										(
										    (
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			
										) :			Union[str, Any]  						=   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 			lowercase				(							a_		,			unittest.TestCase     ):



						"""simple docstring"""

						def 		__UpperCAmelCase       (    self			:		str					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    'Rocketknight1/tiny-random-clip-tf' ,				'hf-internal-testing/tiny-random-bert'					)
										_snake_case :			List[str]  						=   13
										_snake_case :			Optional[Any]  						=   floats_tensor(
										    [
										        batch_size,
										        model.vision_model.config.num_channels,
										        model.vision_model.config.image_size,
										        model.vision_model.config.image_size,
										    ]					)
										_snake_case :			Tuple  						=   ids_tensor([batch_size, 4] ,				model.text_model.config.vocab_size					)
										_snake_case :			Tuple  						=   random_attention_mask([batch_size, 4]					)
										_snake_case :			Dict  						=   {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

										return model, inputs







						def 		__UpperCAmelCase       (    self			:		List[Any] ,				lowerCamelCase_			:		int ,				lowerCamelCase_			:		Union[str, Any]					):





										'''simple docstring'''







										_snake_case :			Optional[Any]  						=   TFCLIPVisionModel(lowerCamelCase_ ,				name='vision_model'					)
										_snake_case :			Optional[int]  						=   TFBertModel(lowerCamelCase_ ,				name='text_model'					)
										return vision_model, text_model







						def 		__UpperCAmelCase       (    self			:		Union[str, Any]					):





										'''simple docstring'''







										_snake_case :			List[str]  						=   TFCLIPVisionModelTester(self					)
										_snake_case :			Optional[Any]  						=   TFBertModelTester(self					)
										_snake_case :			Optional[Any]  						=   clip_model_tester.prepare_config_and_inputs()
										_snake_case :			Any  						=   bert_model_tester.prepare_config_and_inputs()

										_snake_case						,			_snake_case :			Dict  						=   vision_config_and_inputs

										(
										    (
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			(
										    _snake_case
										)						,			
										) :			Optional[Any]  						=   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 			lowercase				(							unittest.TestCase     ):



						"""simple docstring"""

						@slow
						def 		__UpperCAmelCase       (    self			:		Tuple					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   TFVisionTextDualEncoderModel.from_pretrained(
										    'clip-italian/clip-italian' ,				logit_scale_init_value=1.0 ,				from_pt=lowerCamelCase_					)
										_snake_case :			int  						=   VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'					)

										_snake_case :			Dict  						=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
										_snake_case :			str  						=   processor(
										    text=['una foto di un gatto', 'una foto di un cane'] ,				images=lowerCamelCase_ ,				padding=lowerCamelCase_ ,				return_tensors='np'					)

										_snake_case :			int  						=   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]) ,				)

										_snake_case :			Optional[int]  						=   np.array([[1.228_4727, 0.310_4122]]					)

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













import warnings

from ...utils import logging
from .image_processing_segformer import SegformerImageProcessor


lowercase_		:				str				=						logging.get_logger(__name__)


class 			lowercase				(							a_     ):



						"""simple docstring"""

						def __init__(    self			:		int ,				*lowerCamelCase_			:		str ,				**lowerCamelCase_			:		Tuple					):





										'''simple docstring'''







										warnings.warn(
										    'The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
										    ' Please use SegformerImageProcessor instead.' ,				lowerCamelCase_ ,				)
										super().__init__(*lowerCamelCase_ ,				**lowerCamelCase_					)






