



"""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 			snake_case		(		lowerCAmelCase_	)						->				Tuple:
  if isinstance(_lowercase  ,						collections.abc.Iterable	):
    return x
  return (x, x)



@require_tf
class     UpperCAmelCase    :



   def    __UpperCAmelCase    (       self    :	Optional[int]							,       __lowerCamelCase    :	Optional[int]							,       __lowerCamelCase    :	Tuple				):



     """simple docstring"""
     pass



   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     pass



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



     """simple docstring"""
     pass



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



     """simple docstring"""
     _snake_case   	=      VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      TFVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      model(input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__				)

     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    :	List[str]							,       __lowerCamelCase    :	Optional[Any]							,       __lowerCamelCase    :	List[str]							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	Tuple=None							,       **__lowerCamelCase    :	Optional[Any]				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.get_vision_text_model(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__							,       text_model=SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      model(input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__				)

     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    :	Optional[int]							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	Dict							,       __lowerCamelCase    :	List[Any]							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	str=None							,       **__lowerCamelCase    :	int				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.get_vision_text_model(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      {'''vision_model''': vision_model, '''text_model''': text_model}
     _snake_case   	=      TFVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      model(input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__				)

     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    :	List[str]							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	Dict							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	Union[str, Any]=None							,       **__lowerCamelCase    :	Optional[int]				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.get_vision_text_model(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__							,       text_model=SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      model(input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      output[0].numpy()

     with tempfile.TemporaryDirectory() as tmpdirname:
       model.save_pretrained(SCREAMING_SNAKE_CASE__				)
       _snake_case   	=      TFVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__				)

       _snake_case   	=      model(input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__				)
       _snake_case   	=      after_output[0].numpy()
       _snake_case   	=      np.amax(np.abs(out_a - out_a				)				)
       self.assertLessEqual(SCREAMING_SNAKE_CASE__							,       1E-5				)



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



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.get_vision_text_model(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__							,       text_model=SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      model(
         input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__							,       output_attentions=SCREAMING_SNAKE_CASE__				)

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

     _snake_case   	=      output.text_model_output.attentions
     self.assertEqual(len(SCREAMING_SNAKE_CASE__				)							,       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    :	Optional[int]							,       __lowerCamelCase    :	np.ndarray							,       __lowerCamelCase    :	np.ndarray							,       __lowerCamelCase    :	float				):



     """simple docstring"""
     _snake_case   	=      np.abs((a - b)				).max()
     self.assertLessEqual(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__							,       f"""Difference between torch and flax is {diff} (>= {tol})."""				)



   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     _snake_case   	=      self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_model(**SCREAMING_SNAKE_CASE__				)



   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     _snake_case   	=      self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**SCREAMING_SNAKE_CASE__				)



   def    __UpperCAmelCase    (       self    :	Optional[Any]				):



     """simple docstring"""
     _snake_case   	=      self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**SCREAMING_SNAKE_CASE__				)



   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      self.prepare_config_and_inputs()
     self.check_save_load(**SCREAMING_SNAKE_CASE__				)



   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     _snake_case   	=      self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**SCREAMING_SNAKE_CASE__				)





   @slow
   def    __UpperCAmelCase    (       self    :	Optional[int]				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.get_pretrained_model_and_inputs()

     _snake_case   	=      model_a(**SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      outputs[0].numpy()

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

       _snake_case   	=      model_a(**SCREAMING_SNAKE_CASE__				)
       _snake_case   	=      after_outputs[0].numpy()
       _snake_case   	=      np.amax(np.abs(out_a - out_a				)				)
       self.assertLessEqual(SCREAMING_SNAKE_CASE__							,       1E-5				)



@require_tf
class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE,unittest.TestCase  ):



   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      TFVisionTextDualEncoderModel.from_vision_text_pretrained(
         '''hf-internal-testing/tiny-random-vit'''							,       '''hf-internal-testing/tiny-random-bert'''				)
     _snake_case   	=      1_3
     _snake_case   	=      floats_tensor(
         [
             batch_size,
             model.vision_model.config.num_channels,
             model.vision_model.config.image_size,
             model.vision_model.config.image_size,
         ]				)
     _snake_case   	=      ids_tensor([batch_size, 4]							,       model.text_model.config.vocab_size				)
     _snake_case   	=      random_attention_mask([batch_size, 4]				)
     _snake_case   	=      {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

     return model, inputs



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



     """simple docstring"""
     _snake_case   	=      TFViTModel(SCREAMING_SNAKE_CASE__							,       name='''vision_model'''				)
     _snake_case   	=      TFBertModel(SCREAMING_SNAKE_CASE__							,       name='''text_model'''				)
     return vision_model, text_model





   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      TFViTModelTester(self				)
     _snake_case   	=      TFBertModelTester(self				)
     _snake_case   	=      vit_model_tester.prepare_config_and_inputs()
     _snake_case   	=      bert_model_tester.prepare_config_and_inputs()

     _snake_case	,     _snake_case	,     _snake_case   	=      vision_config_and_inputs

     (
         (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _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     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE,unittest.TestCase  ):



   def    __UpperCAmelCase    (       self    :	int				):



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

     return model, inputs



   def    __UpperCAmelCase    (       self    :	List[Any]							,       __lowerCamelCase    :	str							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	Tuple							,       __lowerCamelCase    :	List[Any]							,       __lowerCamelCase    :	Any=None							,       **__lowerCamelCase    :	str				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.get_vision_text_model(SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__							,       text_model=SCREAMING_SNAKE_CASE__				)

     _snake_case   	=      model(
         input_ids=SCREAMING_SNAKE_CASE__							,       pixel_values=SCREAMING_SNAKE_CASE__							,       attention_mask=SCREAMING_SNAKE_CASE__							,       output_attentions=SCREAMING_SNAKE_CASE__				)

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

     _snake_case   	=      output.text_model_output.attentions
     self.assertEqual(len(SCREAMING_SNAKE_CASE__				)							,       text_config.num_hidden_layers				)

     self.assertEqual(
         text_attentions[0].shape[-3:]							,       (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])							,       )



   def    __UpperCAmelCase    (       self    :	str							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      TFDeiTModel(SCREAMING_SNAKE_CASE__							,       name='''vision_model'''				)
     _snake_case   	=      TFRobertaModel(SCREAMING_SNAKE_CASE__							,       name='''text_model'''				)
     return vision_model, text_model





   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     _snake_case   	=      TFDeiTModelTester(self				)
     _snake_case   	=      TFRobertaModelTester(self				)
     _snake_case   	=      vit_model_tester.prepare_config_and_inputs()
     _snake_case   	=      bert_model_tester.prepare_config_and_inputs()

     _snake_case	,     _snake_case	,     _snake_case   	=      vision_config_and_inputs

     (
         (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _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     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE,unittest.TestCase  ):



   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     _snake_case   	=      TFVisionTextDualEncoderModel.from_vision_text_pretrained(
         '''Rocketknight1/tiny-random-clip-tf'''							,       '''hf-internal-testing/tiny-random-bert'''				)
     _snake_case   	=      1_3
     _snake_case   	=      floats_tensor(
         [
             batch_size,
             model.vision_model.config.num_channels,
             model.vision_model.config.image_size,
             model.vision_model.config.image_size,
         ]				)
     _snake_case   	=      ids_tensor([batch_size, 4]							,       model.text_model.config.vocab_size				)
     _snake_case   	=      random_attention_mask([batch_size, 4]				)
     _snake_case   	=      {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

     return model, inputs



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



     """simple docstring"""
     _snake_case   	=      TFCLIPVisionModel(SCREAMING_SNAKE_CASE__							,       name='''vision_model'''				)
     _snake_case   	=      TFBertModel(SCREAMING_SNAKE_CASE__							,       name='''text_model'''				)
     return vision_model, text_model





   def    __UpperCAmelCase    (       self    :	str				):



     """simple docstring"""
     _snake_case   	=      TFCLIPVisionModelTester(self				)
     _snake_case   	=      TFBertModelTester(self				)
     _snake_case   	=      clip_model_tester.prepare_config_and_inputs()
     _snake_case   	=      bert_model_tester.prepare_config_and_inputs()

     _snake_case	,     _snake_case   	=      vision_config_and_inputs

     (
         (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _snake_case		
     )	,     (
         _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     UpperCAmelCase    (	unittest.TestCase  ):



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



     """simple docstring"""
     _snake_case   	=      TFVisionTextDualEncoderModel.from_pretrained(
         '''clip-italian/clip-italian'''							,       logit_scale_init_value=1.0							,       from_pt=SCREAMING_SNAKE_CASE__				)
     _snake_case   	=      VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian'''				)

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

     _snake_case   	=      model(**SCREAMING_SNAKE_CASE__				)

     # 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   	=      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()							,       SCREAMING_SNAKE_CASE__							,       atol=1E-3				)				)







def  __lowerCamelCase					( _lowercase			)       ->      list:
     UpperCamelCase						    =					len(_lowercase			)
     for _ in range(_lowercase			):
          for i in range(_ % 2						,     arr_size - 1						,     2			):
               if arr[i + 1] < arr[i]:
                    UpperCamelCase    ,		UpperCamelCase						    =					arr[i + 1], arr[i]

     return arr


if __name__ == "__main__":
 _snake_case      = list(range(10, 0, -1))
 print(F"Original: {arr}. Sorted: {odd_even_transposition(arr)}")


