'''simple docstring'''






import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
   from transformers import (
       FlaxBertModel,
       FlaxCLIPVisionModel,
       FlaxVisionTextDualEncoderModel,
       FlaxViTModel,
       VisionTextDualEncoderConfig,
       VisionTextDualEncoderProcessor,
   )
   from transformers.modeling_flax_pytorch_utils import (
       convert_pytorch_state_dict_to_flax,
       load_flax_weights_in_pytorch_model,
   )


if is_torch_available():
   import torch

   from transformers import VisionTextDualEncoderModel

if is_vision_available():
   from PIL import Image





def  _SCREAMING_SNAKE_CASE		(      __snake_case							:			Any				):
     if isinstance(__snake_case   ,		collections.abc.Iterable				):
          return x
     return (x, x)







@require_flax
class lowercase_       :







   """simple docstring"""

   def 	__UpperCAmelCase   (      self      :			Tuple, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			List[Any]     )  ->			Dict:
        pass
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			Union[str, Any]:
        pass
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			List[Any]:
        pass
   def 	__UpperCAmelCase   (      self      :			List[Any], UpperCamelCase__      :			np.ndarray, UpperCamelCase__      :			np.ndarray, UpperCamelCase__      :			float     )  ->			Union[str, Any]:
        _A    		=  np.abs((a - b)     ).max()
        self.assertLessEqual(UpperCamelCase__, UpperCamelCase__, f'Difference between torch and flax is {diff} (>= {tol}).'     )
   def 	__UpperCAmelCase   (      self      :			Tuple, UpperCamelCase__      :			List[str], UpperCamelCase__      :			Union[str, Any], UpperCamelCase__      :			int, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Dict=None, **UpperCamelCase__      :			Union[str, Any]     )  ->			List[str]:
        _A    		=  VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__, UpperCamelCase__     )

        _A    		=  FlaxVisionTextDualEncoderModel(UpperCamelCase__     )

        _A    		=  model(input_ids=UpperCamelCase__, pixel_values=UpperCamelCase__, attention_mask=UpperCamelCase__     )

        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      :			Dict, UpperCamelCase__      :			Any, UpperCamelCase__      :			Any, UpperCamelCase__      :			List[str], UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Optional[Any]=None, **UpperCamelCase__      :			Any     )  ->			Any:
        _A		,       _A    		=  self.get_vision_text_model(UpperCamelCase__, UpperCamelCase__     )
        _A    		=  {'vision_model': vision_model, 'text_model': text_model}
        _A    		=  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__     )

        _A    		=  model(input_ids=UpperCamelCase__, pixel_values=UpperCamelCase__, attention_mask=UpperCamelCase__     )

        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[Any], UpperCamelCase__      :			List[str], UpperCamelCase__      :			Optional[int], UpperCamelCase__      :			int, UpperCamelCase__      :			List[Any], UpperCamelCase__      :			List[str]=None, **UpperCamelCase__      :			Optional[int]     )  ->			Optional[Any]:
        _A		,       _A    		=  self.get_vision_text_model(UpperCamelCase__, UpperCamelCase__     )
        _A    		=  {'vision_model': vision_model, 'text_model': text_model}
        _A    		=  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__     )

        _A    		=  model(input_ids=UpperCamelCase__, pixel_values=UpperCamelCase__, attention_mask=UpperCamelCase__     )
        _A    		=  output[0]

        with tempfile.TemporaryDirectory() as tmpdirname:
             model.save_pretrained(UpperCamelCase__     )
             _A    		=  FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__     )

             _A    		=  model(input_ids=UpperCamelCase__, pixel_values=UpperCamelCase__, attention_mask=UpperCamelCase__     )
             _A    		=  after_output[0]
             _A    		=  np.amax(np.abs(out_a - out_a     )     )
             self.assertLessEqual(UpperCamelCase__, 1e-3     )
   def 	__UpperCAmelCase   (      self      :			Optional[Any], UpperCamelCase__      :			Tuple, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Dict, UpperCamelCase__      :			Union[str, Any], UpperCamelCase__      :			Optional[int]=None, **UpperCamelCase__      :			Optional[Any]     )  ->			Tuple:
        _A		,       _A    		=  self.get_vision_text_model(UpperCamelCase__, UpperCamelCase__     )
        _A    		=  {'vision_model': vision_model, 'text_model': text_model}
        _A    		=  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__     )

        _A    		=  model(
            input_ids=UpperCamelCase__, pixel_values=UpperCamelCase__, attention_mask=UpperCamelCase__, output_attentions=UpperCamelCase__     )

        _A    		=  output.vision_model_output.attentions
        self.assertEqual(len(UpperCamelCase__     ), vision_config.num_hidden_layers     )

        # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
        _A    		=  to_atuple(vision_model.config.image_size     )
        _A    		=  to_atuple(vision_model.config.patch_size     )
        _A    		=  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
        _A    		=  num_patches + 1
        self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)     )

        _A    		=  output.text_model_output.attentions
        self.assertEqual(len(UpperCamelCase__     ), 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], UpperCamelCase__      :			int, UpperCamelCase__      :			Any, UpperCamelCase__      :			int     )  ->			int:
        pt_model.to(UpperCamelCase__     )
        pt_model.eval()

        # prepare inputs
        _A    		=  inputs_dict
        _A    		=  {k: torch.tensor(v.tolist()     ) for k, v in flax_inputs.items()}

        with torch.no_grad():
             _A    		=  pt_model(**UpperCamelCase__     ).to_tuple()

        _A    		=  fx_model(**UpperCamelCase__     ).to_tuple()
        self.assertEqual(len(UpperCamelCase__     ), len(UpperCamelCase__     ), 'Output lengths differ between Flax and PyTorch'     )
        for fx_output, pt_output in zip(fx_outputs[:4], pt_outputs[:4]     ):
             self.assert_almost_equals(UpperCamelCase__, pt_output.numpy(), 4e-2     )

        # PT -> Flax
        with tempfile.TemporaryDirectory() as tmpdirname:
             pt_model.save_pretrained(UpperCamelCase__     )
             _A    		=  FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__, from_pt=UpperCamelCase__     )

        _A    		=  fx_model_loaded(**UpperCamelCase__     ).to_tuple()
        self.assertEqual(len(UpperCamelCase__     ), len(UpperCamelCase__     ), 'Output lengths differ between Flax and PyTorch'     )
        for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4], pt_outputs[:4]     ):
             self.assert_almost_equals(UpperCamelCase__, pt_output.numpy(), 4e-2     )

        # Flax -> PT
        with tempfile.TemporaryDirectory() as tmpdirname:
             fx_model.save_pretrained(UpperCamelCase__     )
             _A    		=  VisionTextDualEncoderModel.from_pretrained(UpperCamelCase__, from_flax=UpperCamelCase__     )

        pt_model_loaded.to(UpperCamelCase__     )
        pt_model_loaded.eval()

        with torch.no_grad():
             _A    		=  pt_model_loaded(**UpperCamelCase__     ).to_tuple()

        self.assertEqual(len(UpperCamelCase__     ), len(UpperCamelCase__     ), 'Output lengths differ between Flax and PyTorch'     )
        for fx_output, pt_output_loaded in zip(fx_outputs[:4], pt_outputs_loaded[:4]     ):
             self.assert_almost_equals(UpperCamelCase__, pt_output_loaded.numpy(), 4e-2     )
   def 	__UpperCAmelCase   (      self      :			List[str], UpperCamelCase__      :			List[str], UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Optional[int]     )  ->			List[str]:
        _A    		=  VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__, UpperCamelCase__     )

        _A    		=  VisionTextDualEncoderModel(UpperCamelCase__     )
        _A    		=  FlaxVisionTextDualEncoderModel(UpperCamelCase__     )

        _A    		=  convert_pytorch_state_dict_to_flax(pt_model.state_dict(), UpperCamelCase__     )
        _A    		=  fx_state

        self.check_pt_flax_equivalence(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Dict, UpperCamelCase__      :			Any, UpperCamelCase__      :			List[str], UpperCamelCase__      :			Union[str, Any]     )  ->			List[str]:
        _A    		=  VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__, UpperCamelCase__     )

        _A    		=  VisionTextDualEncoderModel(UpperCamelCase__     )
        _A    		=  FlaxVisionTextDualEncoderModel(UpperCamelCase__     )

        _A    		=  load_flax_weights_in_pytorch_model(UpperCamelCase__, fx_model.params     )

        self.check_pt_flax_equivalence(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			str:
        _A    		=  self.prepare_config_and_inputs()
        self.check_model_from_pretrained_configs(**UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			str     )  ->			Dict:
        _A    		=  self.prepare_config_and_inputs()
        self.check_vision_text_dual_encoder_from_pretrained(**UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			List[str]:
        _A    		=  self.prepare_config_and_inputs()
        self.check_save_load(**UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			int     )  ->			int:
        _A    		=  self.prepare_config_and_inputs()
        self.check_vision_text_output_attention(**UpperCamelCase__     )
   @is_pt_flax_cross_test
   def 	__UpperCAmelCase   (      self      :			int     )  ->			Union[str, Any]:
        _A    		=  self.prepare_config_and_inputs()
        _A    		=  config_inputs_dict.pop('vision_config'     )
        _A    		=  config_inputs_dict.pop('text_config'     )

        _A    		=  config_inputs_dict

        self.check_equivalence_pt_to_flax(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__     )
        self.check_equivalence_flax_to_pt(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__     )

   @slow
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			Dict:
        _A		,       _A    		=  self.get_pretrained_model_and_inputs()

        _A    		=  model_a(**UpperCamelCase__     )
        _A    		=  outputs[0]

        with tempfile.TemporaryDirectory() as tmp_dirname:
             model_a.save_pretrained(UpperCamelCase__     )
             _A    		=  FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__     )

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







@require_flax
class lowercase_       (		_UpperCamelCase    ,    unittest.TestCase			):







   """simple docstring"""

   def 	__UpperCAmelCase   (      self      :			int     )  ->			List[Any]:
        _A    		=  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
            'hf-internal-testing/tiny-random-vit', 'hf-internal-testing/tiny-bert', vision_from_pt=UpperCamelCase__, text_from_pt=UpperCamelCase__, )
        _A    		=  13
        _A    		=  floats_tensor(
            [
                batch_size,
                model.config.vision_config.num_channels,
                model.config.vision_config.image_size,
                model.config.vision_config.image_size,
            ]     )
        _A    		=  ids_tensor([batch_size, 4], model.config.text_config.vocab_size     )
        _A    		=  random_attention_mask([batch_size, 4]     )
        _A    		=  {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

        return model, inputs
   def 	__UpperCAmelCase   (      self      :			List[str], UpperCamelCase__      :			List[Any], UpperCamelCase__      :			Dict     )  ->			int:
        _A    		=  FlaxViTModel(UpperCamelCase__     )
        _A    		=  FlaxBertModel(UpperCamelCase__     )
        return vision_model, text_model

   def 	__UpperCAmelCase   (      self      :			Tuple     )  ->			List[Any]:
        _A    		=  FlaxViTModelTester(self     )
        _A    		=  FlaxBertModelTester(self     )
        _A    		=  vit_model_tester.prepare_config_and_inputs()
        _A    		=  bert_model_tester.prepare_config_and_inputs()

        _A		,       _A    		=  vision_config_and_inputs

        _A		,       _A		,       _A		,       _A    		=  text_config_and_inputs

        # make sure that cross attention layers are added
        return {
            "text_config": text_config,
            "vision_config": vision_config,
            "pixel_values": pixel_values,
            "attention_mask": attention_mask,
            "input_ids": input_ids,
            "token_type_ids": token_type_ids,
        }







@require_torch
class lowercase_       (		_UpperCamelCase    ,    unittest.TestCase			):







   """simple docstring"""

   def 	__UpperCAmelCase   (      self      :			Optional[Any]     )  ->			List[Any]:
        _A    		=  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
            'hf-internal-testing/tiny-random-clip', 'hf-internal-testing/tiny-bert', vision_from_pt=UpperCamelCase__, text_from_pt=UpperCamelCase__, )
        _A    		=  13
        _A    		=  floats_tensor(
            [
                batch_size,
                model.config.vision_config.num_channels,
                model.config.vision_config.image_size,
                model.config.vision_config.image_size,
            ]     )
        _A    		=  ids_tensor([batch_size, 4], model.config.text_config.vocab_size     )
        _A    		=  random_attention_mask([batch_size, 4]     )
        _A    		=  {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

        return model, inputs
   def 	__UpperCAmelCase   (      self      :			Union[str, Any], UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			List[Any]     )  ->			List[str]:
        _A    		=  FlaxCLIPVisionModel(UpperCamelCase__     )
        _A    		=  FlaxBertModel(UpperCamelCase__     )
        return vision_model, text_model

   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			Union[str, Any]:
        _A    		=  FlaxCLIPVisionModelTester(self     )
        _A    		=  FlaxBertModelTester(self     )
        _A    		=  clip_model_tester.prepare_config_and_inputs()
        _A    		=  bert_model_tester.prepare_config_and_inputs()

        _A		,       _A    		=  vision_config_and_inputs

        _A		,       _A		,       _A		,       _A    		=  text_config_and_inputs

        # make sure that cross attention layers are added
        return {
            "text_config": text_config,
            "vision_config": vision_config,
            "pixel_values": pixel_values,
            "attention_mask": attention_mask,
            "input_ids": input_ids,
            "token_type_ids": token_type_ids,
        }







@require_flax
@require_vision
class lowercase_       (		unittest.TestCase			):







   """simple docstring"""

   @slow
   def 	__UpperCAmelCase   (      self      :			int     )  ->			List[Any]:
        _A    		=  FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian', logit_scale_init_value=1.0     )
        _A    		=  VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'     )

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

        _A    		=  model(**UpperCamelCase__     )

        # 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]), )

        _A    		=  np.array([[1.2_284_727, 0.3_104_122]]     )

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










'''simple docstring'''




import re





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str		)		->  list:
   return [char.split() for char in re.split(r"""[^ a-z A-Z 0-9 \s]"""      ,    str_		)]





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str		)		->  str:
   snake_case 						=   split_input(str_		)
   return "".join(
       ["""""".join([char.capitalize() for char in sub_str]		) for sub_str in string_split]		)





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str      ,    __lowerCAmelCase       :							bool      ,    __lowerCAmelCase       :							str		)		->  str:
   try:
      snake_case 						=   split_input(__lowerCAmelCase		)
      if upper:
         snake_case 						=   """""".join(
             [
                 separator.join([char.upper() for char in sub_str]		)
                 for sub_str in string_split
             ]		)
      else:
         snake_case 						=   """""".join(
             [
                 separator.join([char.lower() for char in sub_str]		)
                 for sub_str in string_split
             ]		)
      return res_str
   except IndexError:
      return "not valid string"





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str		)		->  str:
   return to_simple_case(__lowerCAmelCase		)





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str		)		->  str:
   try:
      snake_case 						=   to_simple_case(__lowerCAmelCase		)
      return res_str[0].lower() + res_str[1:]
   except IndexError:
      return "not valid string"





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str      ,    __lowerCAmelCase       :							bool		)		->  str:
   return to_complex_case(__lowerCAmelCase      ,    __lowerCAmelCase      ,    """_"""		)





def 	__lowerCamelCase			(      __lowerCAmelCase       :							str      ,    __lowerCAmelCase       :							bool		)		->  str:
   return to_complex_case(__lowerCAmelCase      ,    __lowerCAmelCase      ,    """-"""		)


if __name__ == "__main__":
 __import__("doctest").testmod()

