

"""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    UpperCamelCase       (      _lowerCAmelCase  :    Optional[Any]			)					->      str:
	if isinstance(lowerCamelCase__,	collections.abc.Iterable			):
		return x
	return (x, x)






@require_tf
class      _UpperCAmelCase      :
			def 				__snake_case			(		self   ,		_A   ,		_A  )     ->     Tuple:






				'''simple docstring'''







				pass
			def 				__snake_case			(		self  )     ->     Dict:






				'''simple docstring'''







				pass
			def 				__snake_case			(		self  )     ->     str:






				'''simple docstring'''







				pass
			def 				__snake_case			(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A=None   ,		**_A  )     ->     Any:






				'''simple docstring'''







				_UpperCAmelCase     :				Any          =       VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__   ,		lowerCamelCase__  )

				_UpperCAmelCase     :				List[Any]          =       TFVisionTextDualEncoderModel(lowerCamelCase__  )

				_UpperCAmelCase     :				Optional[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 				__snake_case			(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A=None   ,		**_A  )     ->     Any:






				'''simple docstring'''







				_UpperCAmelCase     :				str          =       self.get_vision_text_model(lowerCamelCase__   ,		lowerCamelCase__  )
				_UpperCAmelCase     :				int          =       TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__   ,		text_model=lowerCamelCase__  )

				_UpperCAmelCase     :				List[str]          =       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 				__snake_case			(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A=None   ,		**_A  )     ->     int:






				'''simple docstring'''







				_UpperCAmelCase     :				List[str]          =       self.get_vision_text_model(lowerCamelCase__   ,		lowerCamelCase__  )
				_UpperCAmelCase     :				Optional[Any]          =       {"""vision_model""": vision_model, """text_model""": text_model}
				_UpperCAmelCase     :				List[str]          =       TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__  )

				_UpperCAmelCase     :				Tuple          =       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 				__snake_case			(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A=None   ,		**_A  )     ->     Dict:






				'''simple docstring'''







				_UpperCAmelCase     :				List[Any]          =       self.get_vision_text_model(lowerCamelCase__   ,		lowerCamelCase__  )
				_UpperCAmelCase     :				List[str]          =       TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__   ,		text_model=lowerCamelCase__  )

				_UpperCAmelCase     :				Tuple          =       model(input_ids=lowerCamelCase__   ,		pixel_values=lowerCamelCase__   ,		attention_mask=lowerCamelCase__  )
				_UpperCAmelCase     :				str          =       output[0].numpy()

				with tempfile.TemporaryDirectory() as tmpdirname:
					model.save_pretrained(lowerCamelCase__  )
					_UpperCAmelCase     :				Optional[int]          =       TFVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__  )

					_UpperCAmelCase     :				Optional[int]          =       model(input_ids=lowerCamelCase__   ,		pixel_values=lowerCamelCase__   ,		attention_mask=lowerCamelCase__  )
					_UpperCAmelCase     :				Optional[Any]          =       after_output[0].numpy()
					_UpperCAmelCase     :				int          =       np.amax(np.abs(out_a - out_a  )  )
					self.assertLessEqual(lowerCamelCase__   ,		1e-5  )
			def 				__snake_case			(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A=None   ,		**_A  )     ->     Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase     :				str          =       self.get_vision_text_model(lowerCamelCase__   ,		lowerCamelCase__  )
				_UpperCAmelCase     :				List[str]          =       TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__   ,		text_model=lowerCamelCase__  )

				_UpperCAmelCase     :				Optional[int]          =       model(
				    input_ids=lowerCamelCase__   ,		pixel_values=lowerCamelCase__   ,		attention_mask=lowerCamelCase__   ,		output_attentions=lowerCamelCase__  )

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

				_UpperCAmelCase     :				Dict          =       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 				__snake_case			(		self   ,		_A   ,		_A   ,		_A  )     ->     Dict:






				'''simple docstring'''







				_UpperCAmelCase     :				str          =       np.abs((a - b)  ).max()
				self.assertLessEqual(lowerCamelCase__   ,		lowerCamelCase__   ,		f'''Difference between torch and flax is {diff} (>= {tol}).'''  )
			def 				__snake_case			(		self  )     ->     Optional[Any]:






				'''simple docstring'''







				_UpperCAmelCase     :				int          =       self.prepare_config_and_inputs()
				self.check_vision_text_dual_encoder_model(**lowerCamelCase__  )
			def 				__snake_case			(		self  )     ->     List[str]:






				'''simple docstring'''







				_UpperCAmelCase     :				Optional[int]          =       self.prepare_config_and_inputs()
				self.check_model_from_pretrained_configs(**lowerCamelCase__  )
			def 				__snake_case			(		self  )     ->     List[Any]:






				'''simple docstring'''







				_UpperCAmelCase     :				Dict          =       self.prepare_config_and_inputs()
				self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase__  )
			def 				__snake_case			(		self  )     ->     Optional[int]:






				'''simple docstring'''







				_UpperCAmelCase     :				Tuple          =       self.prepare_config_and_inputs()
				self.check_save_load(**lowerCamelCase__  )
			def 				__snake_case			(		self  )     ->     List[str]:






				'''simple docstring'''







				_UpperCAmelCase     :				Tuple          =       self.prepare_config_and_inputs()
				self.check_vision_text_output_attention(**lowerCamelCase__  )
			@slow
			def 				__snake_case			(		self  )     ->     Optional[int]:






				'''simple docstring'''







				_UpperCAmelCase     :				str          =       self.get_pretrained_model_and_inputs()

				_UpperCAmelCase     :				Tuple          =       model_a(**lowerCamelCase__  )
				_UpperCAmelCase     :				Any          =       outputs[0].numpy()

				with tempfile.TemporaryDirectory() as tmp_dirname:
					model_a.save_pretrained(lowerCamelCase__  )
					_UpperCAmelCase     :				List[Any]          =       TFVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__  )

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






@require_tf
class      _UpperCAmelCase      (		__UpperCAmelCase     ,  unittest.TestCase):
			def 				__snake_case			(		self  )     ->     List[Any]:






				'''simple docstring'''







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

				return model, inputs
			def 				__snake_case			(		self   ,		_A   ,		_A  )     ->     Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase     :				Optional[int]          =       TFViTModel(lowerCamelCase__   ,		name="""vision_model"""  )
				_UpperCAmelCase     :				Union[str, Any]          =       TFBertModel(lowerCamelCase__   ,		name="""text_model"""  )
				return vision_model, text_model
			def 				__snake_case			(		self  )     ->     List[Any]:






				'''simple docstring'''







				_UpperCAmelCase     :				Any          =       TFViTModelTester(self  )
				_UpperCAmelCase     :				int          =       TFBertModelTester(self  )
				_UpperCAmelCase     :				int          =       vit_model_tester.prepare_config_and_inputs()
				_UpperCAmelCase     :				Any          =       bert_model_tester.prepare_config_and_inputs()

				_UpperCAmelCase     :				Tuple          =       vision_config_and_inputs

				(
				    _UpperCAmelCase       
				)     :				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      _UpperCAmelCase      (		__UpperCAmelCase     ,  unittest.TestCase):
			def 				__snake_case			(		self  )     ->     int:






				'''simple docstring'''







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

				return model, inputs
			def 				__snake_case			(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A=None   ,		**_A  )     ->     List[Any]:






				'''simple docstring'''







				_UpperCAmelCase     :				Any          =       self.get_vision_text_model(lowerCamelCase__   ,		lowerCamelCase__  )
				_UpperCAmelCase     :				Dict          =       TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__   ,		text_model=lowerCamelCase__  )

				_UpperCAmelCase     :				Dict          =       model(
				    input_ids=lowerCamelCase__   ,		pixel_values=lowerCamelCase__   ,		attention_mask=lowerCamelCase__   ,		output_attentions=lowerCamelCase__  )

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

				_UpperCAmelCase     :				List[str]          =       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 				__snake_case			(		self   ,		_A   ,		_A  )     ->     Tuple:






				'''simple docstring'''







				_UpperCAmelCase     :				Dict          =       TFDeiTModel(lowerCamelCase__   ,		name="""vision_model"""  )
				_UpperCAmelCase     :				str          =       TFRobertaModel(lowerCamelCase__   ,		name="""text_model"""  )
				return vision_model, text_model
			def 				__snake_case			(		self  )     ->     Tuple:






				'''simple docstring'''







				_UpperCAmelCase     :				List[str]          =       TFDeiTModelTester(self  )
				_UpperCAmelCase     :				Union[str, Any]          =       TFRobertaModelTester(self  )
				_UpperCAmelCase     :				Optional[Any]          =       vit_model_tester.prepare_config_and_inputs()
				_UpperCAmelCase     :				int          =       bert_model_tester.prepare_config_and_inputs()

				_UpperCAmelCase     :				Optional[int]          =       vision_config_and_inputs

				(
				    _UpperCAmelCase       
				)     :				Tuple          =       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      (		__UpperCAmelCase     ,  unittest.TestCase):
			def 				__snake_case			(		self  )     ->     Optional[int]:






				'''simple docstring'''







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

				return model, inputs
			def 				__snake_case			(		self   ,		_A   ,		_A  )     ->     Tuple:






				'''simple docstring'''







				_UpperCAmelCase     :				List[Any]          =       TFCLIPVisionModel(lowerCamelCase__   ,		name="""vision_model"""  )
				_UpperCAmelCase     :				Optional[int]          =       TFBertModel(lowerCamelCase__   ,		name="""text_model"""  )
				return vision_model, text_model
			def 				__snake_case			(		self  )     ->     List[str]:






				'''simple docstring'''







				_UpperCAmelCase     :				Union[str, Any]          =       TFCLIPVisionModelTester(self  )
				_UpperCAmelCase     :				Tuple          =       TFBertModelTester(self  )
				_UpperCAmelCase     :				Any          =       clip_model_tester.prepare_config_and_inputs()
				_UpperCAmelCase     :				Optional[int]          =       bert_model_tester.prepare_config_and_inputs()

				_UpperCAmelCase     :				Optional[Any]          =       vision_config_and_inputs

				(
				    _UpperCAmelCase       
				)     :				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      _UpperCAmelCase      (		unittest.TestCase):
			@slow
			def 				__snake_case			(		self  )     ->     int:






				'''simple docstring'''







				_UpperCAmelCase     :				int          =       TFVisionTextDualEncoderModel.from_pretrained(
				    """clip-italian/clip-italian"""   ,		logit_scale_init_value=1.0   ,		from_pt=lowerCamelCase__  )
				_UpperCAmelCase     :				Any          =       VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""  )

				_UpperCAmelCase     :				List[str]          =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
				_UpperCAmelCase     :				Union[str, Any]          =       processor(
				    text=["""una foto di un gatto""", """una foto di un cane"""]   ,		images=lowerCamelCase__   ,		padding=lowerCamelCase__   ,		return_tensors="""np"""  )

				_UpperCAmelCase     :				List[str]          =       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])   ,		)

				_UpperCAmelCase     :				str          =       np.array([[1.2284727, 0.3104122]]  )

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









"""simple docstring"""


from decimal import Decimal, getcontext
from math import ceil, factorial


def    _lowerCamelCase   (     lowerCamelCase__	:							int  ):

 if not isinstance(lowerCamelCase__       ,		lowerCamelCase__  ):
  raise TypeError("""Undefined for non-integers"""  )
 elif precision < 1:
  raise ValueError("""Undefined for non-natural numbers"""  )

 lowercase__       :       List[str]				=						precision
 lowercase__       :       Optional[int]				=						ceil(precision / 14  )
 lowercase__       :       Union[str, Any]				=						42_68_80 * Decimal(1_00_05  ).sqrt()
 lowercase__       :       Optional[Any]				=						1
 lowercase__       :       Optional[Any]				=						13_59_14_09
 lowercase__       :       List[Any]				=						Decimal(lowerCamelCase__  )
 for k in range(1       ,		lowerCamelCase__  ):
  lowercase__       :       Optional[int]				=						factorial(6 * k  ) // (factorial(3 * k  ) * factorial(lowerCamelCase__  ) ** 3)
  linear_term += 5_45_14_01_34
  exponential_term *= -26_25_37_41_26_40_76_80_00
  partial_sum += Decimal(multinomial_term * linear_term  ) / exponential_term
 return str(constant_term / partial_sum  )[:-1]


if __name__ == "__main__":
   __snake_case    					=					50
   print(F"The first {n} digits of pi is: {pi(n)}")