


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

@require_tf
class 				_SCREAMING_SNAKE_CASE				:
   """simple docstring"""



   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							Tuple:
    pass


   def 					UpperCAmelCase__(						self						)      ->							Dict:
    pass


   def 					UpperCAmelCase__(						self						)      ->							str:
    pass


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__=None ,     **lowerCamelCase__						)      ->							Any:
    lowercase__       :       Any				=						VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__ ,     lowerCamelCase__						)

    lowercase__       :       List[Any]				=						TFVisionTextDualEncoderModel(lowerCamelCase__						)

    lowercase__       :       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 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__=None ,     **lowerCamelCase__						)      ->							Any:
    lowercase__	,       lowercase__       :       str				=						self.get_vision_text_model(lowerCamelCase__ ,     lowerCamelCase__						)
    lowercase__       :       int				=						TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__ ,     text_model=lowerCamelCase__						)

    lowercase__       :       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 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__=None ,     **lowerCamelCase__						)      ->							int:
    lowercase__	,       lowercase__       :       List[str]				=						self.get_vision_text_model(lowerCamelCase__ ,     lowerCamelCase__						)
    lowercase__       :       Optional[Any]				=						{"""vision_model""": vision_model, """text_model""": text_model}
    lowercase__       :       List[str]				=						TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__						)

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

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

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

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


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__=None ,     **lowerCamelCase__						)      ->							Union[str, Any]:
    lowercase__	,       lowercase__       :       str				=						self.get_vision_text_model(lowerCamelCase__ ,     lowerCamelCase__						)
    lowercase__       :       List[str]				=						TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__ ,     text_model=lowerCamelCase__						)

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

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


   def 					UpperCAmelCase__(						self						)      ->							Optional[Any]:
    lowercase__       :       int				=						self.prepare_config_and_inputs()
    self.check_vision_text_dual_encoder_model(**lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							List[str]:
    lowercase__       :       Optional[int]				=						self.prepare_config_and_inputs()
    self.check_model_from_pretrained_configs(**lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							List[Any]:
    lowercase__       :       Dict				=						self.prepare_config_and_inputs()
    self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       Tuple				=						self.prepare_config_and_inputs()
    self.check_save_load(**lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							List[str]:
    lowercase__       :       Tuple				=						self.prepare_config_and_inputs()
    self.check_vision_text_output_attention(**lowerCamelCase__						)







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

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

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

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

@require_tf
class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase     ,   unittest.TestCase  ):
   """simple docstring"""



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

    return model, inputs


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							Union[str, Any]:
    lowercase__       :       Optional[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]:
    lowercase__       :       Any				=						TFViTModelTester(self						)
    lowercase__       :       int				=						TFBertModelTester(self						)
    lowercase__       :       int				=						vit_model_tester.prepare_config_and_inputs()
    lowercase__       :       Any				=						bert_model_tester.prepare_config_and_inputs()

    lowercase__	,       lowercase__	,       lowercase__       :       Tuple				=						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_tf
class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase     ,   unittest.TestCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							int:
    # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
    # just reinitialize it.
    lowercase__       :       str				=						TFVisionTextDualEncoderModel.from_vision_text_pretrained(
        """Rocketknight1/tiny-random-deit-tf""" ,     """hf-internal-testing/tiny-random-roberta"""						)
    lowercase__       :       Union[str, Any]				=						13
    lowercase__       :       str				=						floats_tensor(
        [
            batch_size,
            model.vision_model.config.num_channels,
            model.vision_model.config.image_size,
            model.vision_model.config.image_size,
        ]						)
    lowercase__       :       List[Any]				=						ids_tensor([batch_size, 4] ,     model.text_model.config.vocab_size						)
    lowercase__       :       Dict				=						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__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__=None ,     **lowerCamelCase__						)      ->							List[Any]:
    lowercase__	,       lowercase__       :       Any				=						self.get_vision_text_model(lowerCamelCase__ ,     lowerCamelCase__						)
    lowercase__       :       Dict				=						TFVisionTextDualEncoderModel(vision_model=lowerCamelCase__ ,     text_model=lowerCamelCase__						)

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

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

    lowercase__       :       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 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							Tuple:
    lowercase__       :       Dict				=						TFDeiTModel(lowerCamelCase__ ,     name="""vision_model"""						)
    lowercase__       :       str				=						TFRobertaModel(lowerCamelCase__ ,     name="""text_model"""						)
    return vision_model, text_model







   def 					UpperCAmelCase__(						self						)      ->							Tuple:
    lowercase__       :       List[str]				=						TFDeiTModelTester(self						)
    lowercase__       :       Union[str, Any]				=						TFRobertaModelTester(self						)
    lowercase__       :       Optional[Any]				=						vit_model_tester.prepare_config_and_inputs()
    lowercase__       :       int				=						bert_model_tester.prepare_config_and_inputs()

    lowercase__	,       lowercase__	,       lowercase__       :       Optional[int]				=						vision_config_and_inputs

    (
        (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       
    )       :       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 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase     ,   unittest.TestCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       Union[str, Any]				=						TFVisionTextDualEncoderModel.from_vision_text_pretrained(
        """Rocketknight1/tiny-random-clip-tf""" ,     """hf-internal-testing/tiny-random-bert"""						)
    lowercase__       :       Optional[int]				=						13
    lowercase__       :       List[str]				=						floats_tensor(
        [
            batch_size,
            model.vision_model.config.num_channels,
            model.vision_model.config.image_size,
            model.vision_model.config.image_size,
        ]						)
    lowercase__       :       Any				=						ids_tensor([batch_size, 4] ,     model.text_model.config.vocab_size						)
    lowercase__       :       Union[str, 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__						)      ->							Tuple:
    lowercase__       :       List[Any]				=						TFCLIPVisionModel(lowerCamelCase__ ,     name="""vision_model"""						)
    lowercase__       :       Optional[int]				=						TFBertModel(lowerCamelCase__ ,     name="""text_model"""						)
    return vision_model, text_model







   def 					UpperCAmelCase__(						self						)      ->							List[str]:
    lowercase__       :       Union[str, Any]				=						TFCLIPVisionModelTester(self						)
    lowercase__       :       Tuple				=						TFBertModelTester(self						)
    lowercase__       :       Any				=						clip_model_tester.prepare_config_and_inputs()
    lowercase__       :       Optional[int]				=						bert_model_tester.prepare_config_and_inputs()

    lowercase__	,       lowercase__       :       Optional[Any]				=						vision_config_and_inputs

    (
        (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       (
        lowercase__
    )	,       
    )       :       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 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   @slow
   def 					UpperCAmelCase__(						self						)      ->							int:
    lowercase__       :       int				=						TFVisionTextDualEncoderModel.from_pretrained(
        """clip-italian/clip-italian""" ,     logit_scale_init_value=1.0 ,     from_pt=lowerCamelCase__						)
    lowercase__       :       Any				=						VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""						)

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

    lowercase__       :       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]) ,     )

    lowercase__       :       str				=						np.array([[1.228_4727, 0.310_4122]]						)

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



"""simple docstring"""


import os
import unittest

from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast
from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase     ,   unittest.TestCase  ):
   """simple docstring"""



   _a   :       Optional[int]									=    LayoutLMTokenizer
   _a   :       Dict									=    LayoutLMTokenizerFast
   _a   :       Dict									=    True
   _a   :       Any									=    True


   def 					UpperCAmelCase__(						self						)      ->							List[str]:
    super().setUp()

    lowercase__       :       int				=						[
        """[UNK]""",
        """[CLS]""",
        """[SEP]""",
        """want""",
        """##want""",
        """##ed""",
        """wa""",
        """un""",
        """runn""",
        """##ing""",
        """,""",
        """low""",
        """lowest""",
    ]
    lowercase__       :       Dict				=						os.path.join(self.tmpdirname ,     VOCAB_FILES_NAMES["""vocab_file"""]						)
    with open(self.vocab_file ,     """w""" ,     encoding="""utf-8"""						) as vocab_writer:
     vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]						)						)


   def 					UpperCAmelCase__(						self ,     **lowerCamelCase__						)      ->							Optional[int]:
    return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,     **lowerCamelCase__						)


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__						)      ->							List[Any]:
    lowercase__       :       List[str]				=						"""UNwant\u00E9d,running"""
    lowercase__       :       Optional[int]				=						"""unwanted, running"""
    return input_text, output_text


   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       str				=						self.tokenizer_class(self.vocab_file						)

    lowercase__       :       Optional[Any]				=						tokenizer.tokenize("""UNwant\u00E9d,running"""						)
    self.assertListEqual(lowerCamelCase__ ,     ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""]						)
    self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__						) ,     [7, 4, 5, 10, 8, 9]						)







   def 					UpperCAmelCase__(						self						)      ->							Any:
    pass