



'''simple docstring'''

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_     (    __UpperCAmelCase					)				->					str:





			"""simple docstring"""







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






@require_tf
class 						a_		:


							def    UpperCamelCase     (				self   :						Union[str, Any]      ,						a_   :						Optional[Any]      ,						a_   :						int			)			->					List[str]:
										pass


							def    UpperCamelCase     (				self   :						Any			)			->					List[Any]:
										pass


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


							def    UpperCamelCase     (				self   :						Union[str, Any]      ,						a_   :						Union[str, Any]      ,						a_   :						str      ,						a_   :						int      ,						a_   :						Optional[int]      ,						a_   :						Any=None      ,						**a_   :						List[str]			)			->					List[Any]:
										snake_case:    Union[str, Any]      							=VisionTextDualEncoderConfig.from_vision_text_configs(a_      ,						a_			)

										snake_case:    Dict      							=TFVisionTextDualEncoderModel(a_			)

										snake_case:    Optional[int]      							=model(input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_			)

										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   :						str      ,						a_   :						Tuple      ,						a_   :						List[str]      ,						a_   :						str      ,						a_   :						Any      ,						a_   :						List[str]=None      ,						**a_   :						str			)			->					str:
										snake_case							,  snake_case:    Dict      							=self.get_vision_text_model(a_      ,						a_			)
										snake_case:    Dict      							=TFVisionTextDualEncoderModel(vision_model=a_      ,						text_model=a_			)

										snake_case:    Union[str, Any]      							=model(input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_			)

										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   :						str      ,						a_   :						Optional[int]      ,						a_   :						List[Any]      ,						a_   :						int      ,						a_   :						Optional[int]      ,						a_   :						Union[str, Any]=None      ,						**a_   :						Dict			)			->					Union[str, Any]:
										snake_case							,  snake_case:    int      							=self.get_vision_text_model(a_      ,						a_			)
										snake_case:    List[str]      							={'vision_model': vision_model, 'text_model': text_model}
										snake_case:    Any      							=TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a_			)

										snake_case:    Dict      							=model(input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_			)

										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   :						Union[str, Any]      ,						a_   :						Tuple      ,						a_   :						Any      ,						a_   :						int      ,						a_   :						List[str]      ,						a_   :						Tuple=None      ,						**a_   :						str			)			->					Optional[Any]:
										snake_case							,  snake_case:    Optional[int]      							=self.get_vision_text_model(a_      ,						a_			)
										snake_case:    List[Any]      							=TFVisionTextDualEncoderModel(vision_model=a_      ,						text_model=a_			)

										snake_case:    Dict      							=model(input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_			)
										snake_case:    List[str]      							=output[0].numpy()

										with tempfile.TemporaryDirectory() as tmpdirname:
													model.save_pretrained(a_			)
													snake_case:    List[str]      							=TFVisionTextDualEncoderModel.from_pretrained(a_			)

													snake_case:    Optional[int]      							=model(input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_			)
													snake_case:    int      							=after_output[0].numpy()
													snake_case:    int      							=np.amax(np.abs(out_a - out_a			)			)
													self.assertLessEqual(a_      ,						1E-5			)


							def    UpperCamelCase     (				self   :						Optional[int]      ,						a_   :						str      ,						a_   :						int      ,						a_   :						Union[str, Any]      ,						a_   :						Union[str, Any]      ,						a_   :						Optional[int]=None      ,						**a_   :						Optional[int]			)			->					Optional[int]:
										snake_case							,  snake_case:    Optional[int]      							=self.get_vision_text_model(a_      ,						a_			)
										snake_case:    Tuple      							=TFVisionTextDualEncoderModel(vision_model=a_      ,						text_model=a_			)

										snake_case:    str      							=model(
										    input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_      ,						output_attentions=a_			)

										snake_case:    Union[str, Any]      							=output.vision_model_output.attentions
										self.assertEqual(len(a_			)      ,						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:    Optional[int]      							=to_atuple(vision_model.config.image_size			)
										snake_case:    int      							=to_atuple(vision_model.config.patch_size			)
										snake_case:    Optional[int]      							=(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
										snake_case:    Any      							=num_patches + 1
										self.assertEqual(vision_attentions[0].shape[-3:]      ,						(vision_config.num_attention_heads, seq_len, seq_len)			)

										snake_case:    str      							=output.text_model_output.attentions
										self.assertEqual(len(a_			)      ,						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   :						int      ,						a_   :						np.ndarray      ,						a_   :						np.ndarray      ,						a_   :						float			)			->					List[str]:
										snake_case:    Dict      							=np.abs((a - b)			).max()
										self.assertLessEqual(a_      ,						a_      ,						F'''Difference between torch and flax is {diff} (>= {tol}).'''			)


							def    UpperCamelCase     (				self   :						List[str]			)			->					Optional[Any]:
										snake_case:    Any      							=self.prepare_config_and_inputs()
										self.check_vision_text_dual_encoder_model(**a_			)


							def    UpperCamelCase     (				self   :						List[str]			)			->					Dict:
										snake_case:    int      							=self.prepare_config_and_inputs()
										self.check_model_from_pretrained_configs(**a_			)


							def    UpperCamelCase     (				self   :						Dict			)			->					int:
										snake_case:    Dict      							=self.prepare_config_and_inputs()
										self.check_vision_text_dual_encoder_from_pretrained(**a_			)


							def    UpperCamelCase     (				self   :						Union[str, Any]			)			->					List[str]:
										snake_case:    List[Any]      							=self.prepare_config_and_inputs()
										self.check_save_load(**a_			)


							def    UpperCamelCase     (				self   :						Union[str, Any]			)			->					Optional[int]:
										snake_case:    List[Any]      							=self.prepare_config_and_inputs()
										self.check_vision_text_output_attention(**a_			)




							@slow
							def    UpperCamelCase     (				self   :						Optional[int]			)			->					int:
										snake_case							,  snake_case:    str      							=self.get_pretrained_model_and_inputs()

										snake_case:    int      							=model_a(**a_			)
										snake_case:    Dict      							=outputs[0].numpy()

										with tempfile.TemporaryDirectory() as tmp_dirname:
													model_a.save_pretrained(a_			)
													snake_case:    int      							=TFVisionTextDualEncoderModel.from_pretrained(a_			)

													snake_case:    int      							=model_a(**a_			)
													snake_case:    Union[str, Any]      							=after_outputs[0].numpy()
													snake_case:    Dict      							=np.amax(np.abs(out_a - out_a			)			)
													self.assertLessEqual(a_      ,						1E-5			)






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


							def    UpperCamelCase     (				self   :						Optional[int]			)			->					Dict:
										snake_case:    str      							=TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    'hf-internal-testing/tiny-random-vit'      ,						'hf-internal-testing/tiny-random-bert'			)
										snake_case:    Any      							=1_3
										snake_case:    List[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:    Dict      							=ids_tensor([batch_size, 4]      ,						model.text_model.config.vocab_size			)
										snake_case:    Tuple      							=random_attention_mask([batch_size, 4]			)
										snake_case:    Tuple      							={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

										return model, inputs


							def    UpperCamelCase     (				self   :						List[Any]      ,						a_   :						Union[str, Any]      ,						a_   :						Optional[Any]			)			->					int:
										snake_case:    List[Any]      							=TFViTModel(a_      ,						name='vision_model'			)
										snake_case:    Union[str, Any]      							=TFBertModel(a_      ,						name='text_model'			)
										return vision_model, text_model




							def    UpperCamelCase     (				self   :						Dict			)			->					Any:
										snake_case:    Union[str, Any]      							=TFViTModelTester(self			)
										snake_case:    Tuple      							=TFBertModelTester(self			)
										snake_case:    Union[str, Any]      							=vit_model_tester.prepare_config_and_inputs()
										snake_case:    List[str]      							=bert_model_tester.prepare_config_and_inputs()

										snake_case							,  snake_case							,  snake_case:    List[Any]      							=vision_config_and_inputs

										(
										    (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  
										):    Optional[int]      							=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 						a_		(     snake_case    ,   unittest.TestCase    ):


							def    UpperCamelCase     (				self   :						str			)			->					Tuple:
										# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
										# just reinitialize it.
										snake_case:    Optional[Any]      							=TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    'Rocketknight1/tiny-random-deit-tf'      ,						'hf-internal-testing/tiny-random-roberta'			)
										snake_case:    str      							=1_3
										snake_case:    List[str]      							=floats_tensor(
										    [
										        batch_size,
										        model.vision_model.config.num_channels,
										        model.vision_model.config.image_size,
										        model.vision_model.config.image_size,
										    ]			)
										snake_case:    Dict      							=ids_tensor([batch_size, 4]      ,						model.text_model.config.vocab_size			)
										snake_case:    List[Any]      							=random_attention_mask([batch_size, 4]			)
										snake_case:    Optional[int]      							={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

										return model, inputs


							def    UpperCamelCase     (				self   :						List[Any]      ,						a_   :						List[str]      ,						a_   :						str      ,						a_   :						Dict      ,						a_   :						Any      ,						a_   :						Dict=None      ,						**a_   :						Tuple			)			->					str:
										snake_case							,  snake_case:    str      							=self.get_vision_text_model(a_      ,						a_			)
										snake_case:    Optional[Any]      							=TFVisionTextDualEncoderModel(vision_model=a_      ,						text_model=a_			)

										snake_case:    Union[str, Any]      							=model(
										    input_ids=a_      ,						pixel_values=a_      ,						attention_mask=a_      ,						output_attentions=a_			)

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

										snake_case:    int      							=output.text_model_output.attentions
										self.assertEqual(len(a_			)      ,						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   :						Tuple      ,						a_   :						str      ,						a_   :						Tuple			)			->					str:
										snake_case:    Dict      							=TFDeiTModel(a_      ,						name='vision_model'			)
										snake_case:    Optional[int]      							=TFRobertaModel(a_      ,						name='text_model'			)
										return vision_model, text_model




							def    UpperCamelCase     (				self   :						int			)			->					Dict:
										snake_case:    List[Any]      							=TFDeiTModelTester(self			)
										snake_case:    List[str]      							=TFRobertaModelTester(self			)
										snake_case:    Optional[Any]      							=vit_model_tester.prepare_config_and_inputs()
										snake_case:    Optional[Any]      							=bert_model_tester.prepare_config_and_inputs()

										snake_case							,  snake_case							,  snake_case:    List[str]      							=vision_config_and_inputs

										(
										    (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  
										):    Dict      							=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 						a_		(     snake_case    ,   unittest.TestCase    ):


							def    UpperCamelCase     (				self   :						List[Any]			)			->					Tuple:
										snake_case:    Optional[Any]      							=TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    'Rocketknight1/tiny-random-clip-tf'      ,						'hf-internal-testing/tiny-random-bert'			)
										snake_case:    Any      							=1_3
										snake_case:    Union[str, 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:    str      							=ids_tensor([batch_size, 4]      ,						model.text_model.config.vocab_size			)
										snake_case:    Optional[int]      							=random_attention_mask([batch_size, 4]			)
										snake_case:    Optional[int]      							={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

										return model, inputs


							def    UpperCamelCase     (				self   :						Dict      ,						a_   :						Dict      ,						a_   :						Union[str, Any]			)			->					Optional[Any]:
										snake_case:    Optional[int]      							=TFCLIPVisionModel(a_      ,						name='vision_model'			)
										snake_case:    Any      							=TFBertModel(a_      ,						name='text_model'			)
										return vision_model, text_model




							def    UpperCamelCase     (				self   :						Tuple			)			->					Union[str, Any]:
										snake_case:    int      							=TFCLIPVisionModelTester(self			)
										snake_case:    str      							=TFBertModelTester(self			)
										snake_case:    Dict      							=clip_model_tester.prepare_config_and_inputs()
										snake_case:    Dict      							=bert_model_tester.prepare_config_and_inputs()

										snake_case							,  snake_case:    str      							=vision_config_and_inputs

										(
										    (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  (
										    snake_case
										)							,  
										):    Optional[int]      							=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 						a_		(     unittest.TestCase    ):


							@slow
							def    UpperCamelCase     (				self   :						int			)			->					List[str]:
										snake_case:    Any      							=TFVisionTextDualEncoderModel.from_pretrained(
										    'clip-italian/clip-italian'      ,						logit_scale_init_value=1.0      ,						from_pt=a_			)
										snake_case:    Any      							=VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'			)

										snake_case:    Optional[int]      							=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
										snake_case:    int      							=processor(
										    text=['una foto di un gatto', 'una foto di un cane']      ,						images=a_      ,						padding=a_      ,						return_tensors='np'			)

										snake_case:    Union[str, Any]      							=model(**a_			)

										# 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:    str      							=np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]			)

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









'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


a							   =				{
    'configuration_owlvit': [
        'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'OwlViTConfig',
        'OwlViTOnnxConfig',
        'OwlViTTextConfig',
        'OwlViTVisionConfig',
    ],
    'processing_owlvit': ['OwlViTProcessor'],
}


try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a							   =				['OwlViTFeatureExtractor']
	a							   =				['OwlViTImageProcessor']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a							   =				[
	    'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
	    'OwlViTModel',
	    'OwlViTPreTrainedModel',
	    'OwlViTTextModel',
	    'OwlViTVisionModel',
	    'OwlViTForObjectDetection',
	]

if TYPE_CHECKING:
	from .configuration_owlvit import (
	    OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    OwlViTConfig,
	    OwlViTOnnxConfig,
	    OwlViTTextConfig,
	    OwlViTVisionConfig,
	)
	from .processing_owlvit import OwlViTProcessor

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .feature_extraction_owlvit import OwlViTFeatureExtractor
		from .image_processing_owlvit import OwlViTImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_owlvit import (
		    OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    OwlViTForObjectDetection,
		    OwlViTModel,
		    OwlViTPreTrainedModel,
		    OwlViTTextModel,
		    OwlViTVisionModel,
		)

else:
	import sys

	a							   =				_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)




