


"""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     lowercase			(SCREAMING_SNAKE_CASE_		:				Any  )   ->						str:
						if isinstance(SCREAMING_SNAKE_CASE_ ,			collections.abc.Iterable  ):
												return x
						return (x, x)
@require_tf
class 					lowerCAmelCase	:




		'''simple docstring'''







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







		def 							__A						(	self				)     ->							Tuple:
								pass







		def 							__A						(	self				)     ->							Any:
								pass







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__=None						,       **lowerCAmelCase__				)     ->							Union[str, Any]:
								SCREAMING_SNAKE_CASE													=					VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase__						,       lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel(lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					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						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__=None						,       **lowerCAmelCase__				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					self.get_vision_text_model(lowerCAmelCase__						,       lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel(vision_model=lowerCAmelCase__						,       text_model=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					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						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__=None						,       **lowerCAmelCase__				)     ->							Optional[Any]:
								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					self.get_vision_text_model(lowerCAmelCase__						,       lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					{'vision_model': vision_model, 'text_model': text_model}
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					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						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__=None						,       **lowerCAmelCase__				)     ->							Tuple:
								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					self.get_vision_text_model(lowerCAmelCase__						,       lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel(vision_model=lowerCAmelCase__						,       text_model=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					model(input_ids=lowerCAmelCase__						,       pixel_values=lowerCAmelCase__						,       attention_mask=lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					output[0].numpy()

								with tempfile.TemporaryDirectory() as tmpdirname:
														model.save_pretrained(lowerCAmelCase__				)
														SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase__				)

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







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__=None						,       **lowerCAmelCase__				)     ->							str:
								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					self.get_vision_text_model(lowerCAmelCase__						,       lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel(vision_model=lowerCAmelCase__						,       text_model=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					model(
								    input_ids=lowerCAmelCase__						,       pixel_values=lowerCAmelCase__						,       attention_mask=lowerCAmelCase__						,       output_attentions=lowerCAmelCase__				)

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

								SCREAMING_SNAKE_CASE													=					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						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							Any:
								SCREAMING_SNAKE_CASE													=					np.abs((a - b)				).max()
								self.assertLessEqual(lowerCAmelCase__						,       lowerCAmelCase__						,       F'Difference between torch and flax is {diff} (>= {tol}).'				)







		def 							__A						(	self				)     ->							List[str]:
								SCREAMING_SNAKE_CASE													=					self.prepare_config_and_inputs()
								self.check_vision_text_dual_encoder_model(**lowerCAmelCase__				)







		def 							__A						(	self				)     ->							Any:
								SCREAMING_SNAKE_CASE													=					self.prepare_config_and_inputs()
								self.check_model_from_pretrained_configs(**lowerCAmelCase__				)







		def 							__A						(	self				)     ->							Union[str, Any]:
								SCREAMING_SNAKE_CASE													=					self.prepare_config_and_inputs()
								self.check_vision_text_dual_encoder_from_pretrained(**lowerCAmelCase__				)







		def 							__A						(	self				)     ->							Union[str, Any]:
								SCREAMING_SNAKE_CASE													=					self.prepare_config_and_inputs()
								self.check_save_load(**lowerCAmelCase__				)







		def 							__A						(	self				)     ->							int:
								SCREAMING_SNAKE_CASE													=					self.prepare_config_and_inputs()
								self.check_vision_text_output_attention(**lowerCAmelCase__				)







		@slow
		def 							__A						(	self				)     ->							Dict:
								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					self.get_pretrained_model_and_inputs()

								SCREAMING_SNAKE_CASE													=					model_a(**lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					outputs[0].numpy()

								with tempfile.TemporaryDirectory() as tmp_dirname:
														model_a.save_pretrained(lowerCAmelCase__				)
														SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase__				)

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





@require_tf
class 					lowerCAmelCase	(					lowerCamelCase_	,    unittest.TestCase    ):




		'''simple docstring'''







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

								return model, inputs







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							int:
								SCREAMING_SNAKE_CASE													=					TFViTModel(lowerCAmelCase__						,       name='vision_model'				)
								SCREAMING_SNAKE_CASE													=					TFBertModel(lowerCAmelCase__						,       name='text_model'				)
								return vision_model, text_model







		def 							__A						(	self				)     ->							Optional[Any]:
								SCREAMING_SNAKE_CASE													=					TFViTModelTester(self				)
								SCREAMING_SNAKE_CASE													=					TFBertModelTester(self				)
								SCREAMING_SNAKE_CASE													=					vit_model_tester.prepare_config_and_inputs()
								SCREAMING_SNAKE_CASE													=					bert_model_tester.prepare_config_and_inputs()

								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					vision_config_and_inputs

								(
								    (
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				
								)													=					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 					lowerCAmelCase	(					lowerCamelCase_	,    unittest.TestCase    ):




		'''simple docstring'''







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

								return model, inputs







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__=None						,       **lowerCAmelCase__				)     ->							Dict:
								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					self.get_vision_text_model(lowerCAmelCase__						,       lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel(vision_model=lowerCAmelCase__						,       text_model=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					model(
								    input_ids=lowerCAmelCase__						,       pixel_values=lowerCAmelCase__						,       attention_mask=lowerCAmelCase__						,       output_attentions=lowerCAmelCase__				)

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

								SCREAMING_SNAKE_CASE													=					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						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							Tuple:
								SCREAMING_SNAKE_CASE													=					TFDeiTModel(lowerCAmelCase__						,       name='vision_model'				)
								SCREAMING_SNAKE_CASE													=					TFRobertaModel(lowerCAmelCase__						,       name='text_model'				)
								return vision_model, text_model







		def 							__A						(	self				)     ->							Tuple:
								SCREAMING_SNAKE_CASE													=					TFDeiTModelTester(self				)
								SCREAMING_SNAKE_CASE													=					TFRobertaModelTester(self				)
								SCREAMING_SNAKE_CASE													=					vit_model_tester.prepare_config_and_inputs()
								SCREAMING_SNAKE_CASE													=					bert_model_tester.prepare_config_and_inputs()

								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					vision_config_and_inputs

								(
								    (
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				
								)													=					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 					lowerCAmelCase	(					lowerCamelCase_	,    unittest.TestCase    ):




		'''simple docstring'''







		def 							__A						(	self				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
								    'Rocketknight1/tiny-random-clip-tf'						,       'hf-internal-testing/tiny-random-bert'				)
								SCREAMING_SNAKE_CASE													=					13
								SCREAMING_SNAKE_CASE													=					floats_tensor(
								    [
								        batch_size,
								        model.vision_model.config.num_channels,
								        model.vision_model.config.image_size,
								        model.vision_model.config.image_size,
								    ]				)
								SCREAMING_SNAKE_CASE													=					ids_tensor([batch_size, 4]						,       model.text_model.config.vocab_size				)
								SCREAMING_SNAKE_CASE													=					random_attention_mask([batch_size, 4]				)
								SCREAMING_SNAKE_CASE													=					{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

								return model, inputs







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							int:
								SCREAMING_SNAKE_CASE													=					TFCLIPVisionModel(lowerCAmelCase__						,       name='vision_model'				)
								SCREAMING_SNAKE_CASE													=					TFBertModel(lowerCAmelCase__						,       name='text_model'				)
								return vision_model, text_model







		def 							__A						(	self				)     ->							List[str]:
								SCREAMING_SNAKE_CASE													=					TFCLIPVisionModelTester(self				)
								SCREAMING_SNAKE_CASE													=					TFBertModelTester(self				)
								SCREAMING_SNAKE_CASE													=					clip_model_tester.prepare_config_and_inputs()
								SCREAMING_SNAKE_CASE													=					bert_model_tester.prepare_config_and_inputs()

								SCREAMING_SNAKE_CASE							,				SCREAMING_SNAKE_CASE													=					vision_config_and_inputs

								(
								    (
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				(
								    SCREAMING_SNAKE_CASE
								)							,				
								)													=					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 					lowerCAmelCase	(					unittest.TestCase    ):




		'''simple docstring'''







		@slow
		def 							__A						(	self				)     ->							int:
								SCREAMING_SNAKE_CASE													=					TFVisionTextDualEncoderModel.from_pretrained(
								    'clip-italian/clip-italian'						,       logit_scale_init_value=1.0						,       from_pt=lowerCAmelCase__				)
								SCREAMING_SNAKE_CASE													=					VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'				)

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

								SCREAMING_SNAKE_CASE													=					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])						,       )

								SCREAMING_SNAKE_CASE													=					np.array([[1.2_28_47_27, 0.3_10_41_22]]				)

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






"""simple docstring"""




from __future__ import annotations

from collections.abc import Callable


def     lowercase			(SCREAMING_SNAKE_CASE_		:				Callable[[int | float], int | float] ,			SCREAMING_SNAKE_CASE_		:				int | float ,			SCREAMING_SNAKE_CASE_		:				int | float ,			SCREAMING_SNAKE_CASE_		:				int = 1_00 ,			)   ->						float:
						SCREAMING_SNAKE_CASE													=					x_start
						SCREAMING_SNAKE_CASE													=					fnc(SCREAMING_SNAKE_CASE_  )
						SCREAMING_SNAKE_CASE													=					0.0
						for _ in range(SCREAMING_SNAKE_CASE_  ):
												# Approximates small segments of curve as linear and solve
												# for trapezoidal area
												SCREAMING_SNAKE_CASE													=					(x_end - x_start) / steps + xa
												SCREAMING_SNAKE_CASE													=					fnc(SCREAMING_SNAKE_CASE_  )
												area += abs(fxa + fxa  ) * (xa - xa) / 2
												# Increment step
												SCREAMING_SNAKE_CASE													=					xa
												SCREAMING_SNAKE_CASE													=					fxa
						return area


if __name__ == "__main__":


	def     lowercase			(SCREAMING_SNAKE_CASE_		:				Optional[int]  )   ->						Dict:
							return x**3 + x**2

	print('''f(x) = x^3 + x^2''')
	print('''The area between the curve, x = -5, x = 5 and the x axis is:''')
	__UpperCamelCase						=      10
	while i <= 100000:
		print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''')
		i *= 10


