


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






@require_tf
class _lowerCamelCase:
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   int:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

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




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							str      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Dict      		=		TFVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Dict      		=		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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   str:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Optional[int]      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							Optional[int]      		=		TFVisionTextDualEncoderModel(vision_model=lowerCamelCase,      text_model=lowerCamelCase)

           _lowercase       :							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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Tuple:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Optional[int]      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							Any      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Optional[int]      		=		TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							Union[str, Any]      		=		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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   List[Any]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Tuple      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							List[str]      		=		TFVisionTextDualEncoderModel(vision_model=lowerCamelCase,      text_model=lowerCamelCase)

           _lowercase       :							Union[str, Any]      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
           _lowercase       :							Optional[int]      		=		output[0].numpy()

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

               _lowercase       :							str      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
               _lowercase       :							List[Any]      		=		after_output[0].numpy()
               _lowercase       :							str      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-5)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Dict:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Union[str, Any]      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							List[Any]      		=		TFVisionTextDualEncoderModel(vision_model=lowerCamelCase,      text_model=lowerCamelCase)

           _lowercase       :							int      		=		model(
               input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase,      output_attentions=lowerCamelCase)

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

           _lowercase       :							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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		np.abs((a - b)).max()
           self.assertLessEqual(lowerCamelCase,      lowerCamelCase,      F'''Difference between torch and flax is {diff} (>= {tol}).''')
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		self.prepare_config_and_inputs()
           self.check_vision_text_dual_encoder_model(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							int      		=		self.prepare_config_and_inputs()
           self.check_model_from_pretrained_configs(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							str      		=		self.prepare_config_and_inputs()
           self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		self.prepare_config_and_inputs()
           self.check_save_load(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							str      		=		self.prepare_config_and_inputs()
           self.check_vision_text_output_attention(**lowerCamelCase)




       @slow
       def 			UpperCamelCase     (					self)       ->   int:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Tuple      		=		self.get_pretrained_model_and_inputs()

           _lowercase       :							Optional[int]      		=		model_a(**lowerCamelCase)
           _lowercase       :							Optional[int]      		=		outputs[0].numpy()

           with tempfile.TemporaryDirectory() as tmp_dirname:
               model_a.save_pretrained(lowerCamelCase)
               _lowercase       :							Optional[Any]      		=		TFVisionTextDualEncoderModel.from_pretrained(lowerCamelCase)

               _lowercase       :							Optional[int]      		=		model_a(**lowerCamelCase)
               _lowercase       :							Optional[int]      		=		after_outputs[0].numpy()
               _lowercase       :							str      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-5)






@require_tf
class _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							int      		=		TFVisionTextDualEncoderModel.from_vision_text_pretrained(
               'hf-internal-testing/tiny-random-vit',      'hf-internal-testing/tiny-random-bert')
           _lowercase       :							Union[str, Any]      		=		13
           _lowercase       :							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,
               ])
           _lowercase       :							str      		=		ids_tensor([batch_size, 4],      model.text_model.config.vocab_size)
           _lowercase       :							Any      		=		random_attention_mask([batch_size, 4])
           _lowercase       :							List[Any]      		=		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							int      		=		TFViTModel(lowerCamelCase,      name='vision_model')
           _lowercase       :							Union[str, Any]      		=		TFBertModel(lowerCamelCase,      name='text_model')
           return vision_model, text_model




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




           """simple docstring"""

           _lowercase       :							int      		=		TFViTModelTester(self)
           _lowercase       :							List[Any]      		=		TFBertModelTester(self)
           _lowercase       :							Any      		=		vit_model_tester.prepare_config_and_inputs()
           _lowercase       :							str      		=		bert_model_tester.prepare_config_and_inputs()

           _lowercase		,				_lowercase		,				_lowercase       :							str      		=		vision_config_and_inputs

           (
               (
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				
           )       :							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 _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

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

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   List[str]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Dict      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		TFVisionTextDualEncoderModel(vision_model=lowerCamelCase,      text_model=lowerCamelCase)

           _lowercase       :							List[Any]      		=		model(
               input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase,      output_attentions=lowerCamelCase)

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

           _lowercase       :							Optional[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,      lowerCamelCase,      lowerCamelCase)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Tuple      		=		TFDeiTModel(lowerCamelCase,      name='vision_model')
           _lowercase       :							str      		=		TFRobertaModel(lowerCamelCase,      name='text_model')
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		TFDeiTModelTester(self)
           _lowercase       :							Tuple      		=		TFRobertaModelTester(self)
           _lowercase       :							Any      		=		vit_model_tester.prepare_config_and_inputs()
           _lowercase       :							List[Any]      		=		bert_model_tester.prepare_config_and_inputs()

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

           (
               (
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				
           )       :							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 _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

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

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




           """simple docstring"""

           _lowercase       :							str      		=		TFCLIPVisionModel(lowerCamelCase,      name='vision_model')
           _lowercase       :							List[str]      		=		TFBertModel(lowerCamelCase,      name='text_model')
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Any      		=		TFCLIPVisionModelTester(self)
           _lowercase       :							Tuple      		=		TFBertModelTester(self)
           _lowercase       :							Optional[Any]      		=		clip_model_tester.prepare_config_and_inputs()
           _lowercase       :							Any      		=		bert_model_tester.prepare_config_and_inputs()

           _lowercase		,				_lowercase       :							Any      		=		vision_config_and_inputs

           (
               (
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				(
               _lowercase
           )		,				
           )       :							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 _lowerCamelCase(						unittest.TestCase   ):
       @slow
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		TFVisionTextDualEncoderModel.from_pretrained(
               'clip-italian/clip-italian',      logit_scale_init_value=1.0,      from_pt=lowerCamelCase)
           _lowercase       :							str      		=		VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

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

           _lowercase       :							Union[str, Any]      		=		model(**lowerCamelCase)

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

           _lowercase       :							Any      		=		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(),      lowerCamelCase,      atol=1E-3))







'''simple docstring'''




def 				lowerCAmelCase_   (	_lowerCamelCase:   list[int]       ,      _lowerCamelCase:   str					):
		__SCREAMING_SNAKE_CASE       :		str           =		int(_lowerCamelCase					)

		# Initialize Result
		__SCREAMING_SNAKE_CASE       :		Tuple           =		[]

		# Traverse through all denomination
		for denomination in reversed(_lowerCamelCase					):
				# Find denominations
				while int(_lowerCamelCase					) >= int(_lowerCamelCase					):
						total_value -= int(_lowerCamelCase					)
						answer.append(_lowerCamelCase					)  # Append the "answers" array

		return answer


# Driver Code
if __name__ == "__main__":
						UpperCamelCase__       :	int    = []
						UpperCamelCase__       :	List[Any]    = '''0'''

						if (
						    input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower()
						    == "y"
						):
												UpperCamelCase__       :	Tuple    = int(input('''Enter the number of denominations you want to add: ''').strip())

												for i in range(0, n):
																		denominations.append(int(input(f"Denomination {i}: ").strip()))
												UpperCamelCase__       :	str    = input('''Enter the change you want to make in Indian Currency: ''').strip()
						else:
												# All denominations of Indian Currency if user does not enter
												UpperCamelCase__       :	List[Any]    = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00]
												UpperCamelCase__       :	str    = input('''Enter the change you want to make: ''').strip()

						if int(value) == 0 or int(value) < 0:
												print('''The total value cannot be zero or negative.''')

						else:
												print(f"Following is minimal change for {value}: ")
												UpperCamelCase__       :	int    = find_minimum_change(denominations, value)
												# Print result
												for i in range(len(answer)):
																		print(answer[i], end=''' ''')