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__       (			a__ )      ->int:




  '''simple docstring'''

  if isinstance(a__    ,     collections.abc.Iterable ):
    return x
  return (x, x)




@require_tf
class 					_UpperCAmelCase			:



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   Union[str, Any]							, lowercase_				:   Optional[Any]							, lowercase_				:   Any)						->	int:


   """simple docstring"""







   pass







 def 		__UpperCAmelCase				(		self				:   str)						->	Optional[int]:


   """simple docstring"""







   pass







 def 		__UpperCAmelCase				(		self				:   Any)						->	str:


   """simple docstring"""







   pass







 def 		__UpperCAmelCase				(		self				:   Optional[int]							, lowercase_				:   str							, lowercase_				:   Optional[int]							, lowercase_				:   int							, lowercase_				:   Any							, lowercase_				:   Dict=None							, **lowercase_				:   Optional[int])						->	Union[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    VisionTextDualEncoderConfig.from_vision_text_configs(lowercase_							, lowercase_)

   _UpperCamelCase           =    TFVisionTextDualEncoderModel(lowercase_)

   _UpperCamelCase           =    model(input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_)

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


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self.get_vision_text_model(lowercase_							, lowercase_)
   _UpperCamelCase           =    TFVisionTextDualEncoderModel(vision_model=lowercase_							, text_model=lowercase_)

   _UpperCamelCase           =    model(input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_)

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


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self.get_vision_text_model(lowercase_							, lowercase_)
   _UpperCamelCase           =    {"vision_model": vision_model, "text_model": text_model}
   _UpperCamelCase           =    TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase_)

   _UpperCamelCase           =    model(input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_)

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


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self.get_vision_text_model(lowercase_							, lowercase_)
   _UpperCamelCase           =    TFVisionTextDualEncoderModel(vision_model=lowercase_							, text_model=lowercase_)

   _UpperCamelCase           =    model(input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_)
   _UpperCamelCase           =    output[0].numpy()

   with tempfile.TemporaryDirectory() as tmpdirname:
     model.save_pretrained(lowercase_)
     _UpperCamelCase           =    TFVisionTextDualEncoderModel.from_pretrained(lowercase_)

     _UpperCamelCase           =    model(input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_)
     _UpperCamelCase           =    after_output[0].numpy()
     _UpperCamelCase           =    np.amax(np.abs(out_a - out_a))
     self.assertLessEqual(lowercase_							, 1e-5)







 def 		__UpperCAmelCase				(		self				:   List[Any]							, lowercase_				:   List[str]							, lowercase_				:   Tuple							, lowercase_				:   List[Any]							, lowercase_				:   int							, lowercase_				:   Any=None							, **lowercase_				:   int)						->	str:


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self.get_vision_text_model(lowercase_							, lowercase_)
   _UpperCamelCase           =    TFVisionTextDualEncoderModel(vision_model=lowercase_							, text_model=lowercase_)

   _UpperCamelCase           =    model(
       input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_							, output_attentions=lowercase_)

   _UpperCamelCase           =    output.vision_model_output.attentions
   self.assertEqual(len(lowercase_)							, vision_config.num_hidden_layers)

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

   _UpperCamelCase           =    output.text_model_output.attentions
   self.assertEqual(len(lowercase_)							, 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				:   Dict							, lowercase_				:   np.ndarray							, lowercase_				:   np.ndarray							, lowercase_				:   float)						->	Dict:


   """simple docstring"""







   _UpperCamelCase           =    np.abs((a - b)).max()
   self.assertLessEqual(lowercase_							, lowercase_							, f'Difference between torch and flax is {diff} (>= {tol}).')







 def 		__UpperCAmelCase				(		self				:   List[Any])						->	str:


   """simple docstring"""







   _UpperCamelCase           =    self.prepare_config_and_inputs()
   self.check_vision_text_dual_encoder_model(**lowercase_)







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


   """simple docstring"""







   _UpperCamelCase           =    self.prepare_config_and_inputs()
   self.check_model_from_pretrained_configs(**lowercase_)







 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	Union[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    self.prepare_config_and_inputs()
   self.check_vision_text_dual_encoder_from_pretrained(**lowercase_)







 def 		__UpperCAmelCase				(		self				:   Dict)						->	Tuple:


   """simple docstring"""







   _UpperCamelCase           =    self.prepare_config_and_inputs()
   self.check_save_load(**lowercase_)







 def 		__UpperCAmelCase				(		self				:   Dict)						->	List[str]:


   """simple docstring"""







   _UpperCamelCase           =    self.prepare_config_and_inputs()
   self.check_vision_text_output_attention(**lowercase_)







 @slow
 def 		__UpperCAmelCase				(		self				:   int)						->	Any:


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self.get_pretrained_model_and_inputs()

   _UpperCamelCase           =    model_a(**lowercase_)
   _UpperCamelCase           =    outputs[0].numpy()

   with tempfile.TemporaryDirectory() as tmp_dirname:
     model_a.save_pretrained(lowercase_)
     _UpperCamelCase           =    TFVisionTextDualEncoderModel.from_pretrained(lowercase_)

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




@require_tf
class 					_UpperCAmelCase			(     lowerCAmelCase,			unittest.TestCase  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   Any)						->	str:


   """simple docstring"""







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

   return model, inputs







 def 		__UpperCAmelCase				(		self				:   int							, lowercase_				:   Optional[Any]							, lowercase_				:   int)						->	List[str]:


   """simple docstring"""







   _UpperCamelCase           =    TFViTModel(lowercase_							, name="vision_model")
   _UpperCamelCase           =    TFBertModel(lowercase_							, name="text_model")
   return vision_model, text_model







 def 		__UpperCAmelCase				(		self				:   Optional[Any])						->	str:


   """simple docstring"""







   _UpperCamelCase           =    TFViTModelTester(self)
   _UpperCamelCase           =    TFBertModelTester(self)
   _UpperCamelCase           =    vit_model_tester.prepare_config_and_inputs()
   _UpperCamelCase           =    bert_model_tester.prepare_config_and_inputs()

   _UpperCamelCase      ,						_UpperCamelCase      ,						_UpperCamelCase           =    vision_config_and_inputs

   (
       (
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						
   )           =    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			(     lowerCAmelCase,			unittest.TestCase  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   Any)						->	str:


   """simple docstring"""







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

   return model, inputs







 def 		__UpperCAmelCase				(		self				:   Optional[Any]							, lowercase_				:   Union[str, Any]							, lowercase_				:   str							, lowercase_				:   Any							, lowercase_				:   Union[str, Any]							, lowercase_				:   Optional[int]=None							, **lowercase_				:   Dict)						->	List[Any]:


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self.get_vision_text_model(lowercase_							, lowercase_)
   _UpperCamelCase           =    TFVisionTextDualEncoderModel(vision_model=lowercase_							, text_model=lowercase_)

   _UpperCamelCase           =    model(
       input_ids=lowercase_							, pixel_values=lowercase_							, attention_mask=lowercase_							, output_attentions=lowercase_)

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

   _UpperCamelCase           =    output.text_model_output.attentions
   self.assertEqual(len(lowercase_)							, 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				:   List[str]							, lowercase_				:   Union[str, Any]							, lowercase_				:   Union[str, Any])						->	Tuple:


   """simple docstring"""







   _UpperCamelCase           =    TFDeiTModel(lowercase_							, name="vision_model")
   _UpperCamelCase           =    TFRobertaModel(lowercase_							, name="text_model")
   return vision_model, text_model







 def 		__UpperCAmelCase				(		self				:   List[str])						->	int:


   """simple docstring"""







   _UpperCamelCase           =    TFDeiTModelTester(self)
   _UpperCamelCase           =    TFRobertaModelTester(self)
   _UpperCamelCase           =    vit_model_tester.prepare_config_and_inputs()
   _UpperCamelCase           =    bert_model_tester.prepare_config_and_inputs()

   _UpperCamelCase      ,						_UpperCamelCase      ,						_UpperCamelCase           =    vision_config_and_inputs

   (
       (
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						
   )           =    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			(     lowerCAmelCase,			unittest.TestCase  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[str])						->	List[Any]:


   """simple docstring"""







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

   return model, inputs







 def 		__UpperCAmelCase				(		self				:   List[Any]							, lowercase_				:   List[Any]							, lowercase_				:   Any)						->	Optional[Any]:


   """simple docstring"""







   _UpperCamelCase           =    TFCLIPVisionModel(lowercase_							, name="vision_model")
   _UpperCamelCase           =    TFBertModel(lowercase_							, name="text_model")
   return vision_model, text_model







 def 		__UpperCAmelCase				(		self				:   str)						->	Optional[Any]:


   """simple docstring"""







   _UpperCamelCase           =    TFCLIPVisionModelTester(self)
   _UpperCamelCase           =    TFBertModelTester(self)
   _UpperCamelCase           =    clip_model_tester.prepare_config_and_inputs()
   _UpperCamelCase           =    bert_model_tester.prepare_config_and_inputs()

   _UpperCamelCase      ,						_UpperCamelCase           =    vision_config_and_inputs

   (
       (
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						(
       _UpperCamelCase
   )      ,						
   )           =    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  ):



 '''simple docstring'''




 @slow
 def 		__UpperCAmelCase				(		self				:   List[str])						->	int:


   """simple docstring"""







   _UpperCamelCase           =    TFVisionTextDualEncoderModel.from_pretrained(
       "clip-italian/clip-italian"							, logit_scale_init_value=1.0							, from_pt=lowercase_)
   _UpperCamelCase           =    VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian")

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

   _UpperCamelCase           =    model(**lowercase_)

   # 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           =    np.array([[1.2_28_47_27, 0.3_10_41_22]])

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





from __future__ import annotations


def 				lowerCAmelCase__       (			a__    ,     a__ )      ->bool:




  '''simple docstring'''

  _UpperCamelCase           =    get_failure_array(a__ )

  # 2) Step through text searching for pattern
  _UpperCamelCase      ,						_UpperCamelCase           =    0, 0  # index into text, pattern
  while i < len(a__ ):
    if pattern[j] == text[i]:
      if j == (len(a__ ) - 1):
        return True
      j += 1

    # if this is a prefix in our pattern
    # just go back far enough to continue
    elif j > 0:
      _UpperCamelCase           =    failure[j - 1]
      continue
    i += 1
  return False


def 				lowerCAmelCase__       (			a__ )      ->list[int]:




  '''simple docstring'''

  _UpperCamelCase           =    [0]
  _UpperCamelCase           =    0
  _UpperCamelCase           =    1
  while j < len(a__ ):
    if pattern[i] == pattern[j]:
      i += 1
    elif i > 0:
      _UpperCamelCase           =    failure[i - 1]
      continue
    j += 1
    failure.append(a__ )
  return failure


if __name__ == "__main__":
   # Test 1)
   lowerCamelCase__  =					'''abc1abc12'''
   lowerCamelCase__  =					'''alskfjaldsabc1abc1abc12k23adsfabcabc'''
   lowerCamelCase__  =					'''alskfjaldsk23adsfabcabc'''
   assert kmp(pattern, texta) and not kmp(pattern, texta)

   # Test 2)
   lowerCamelCase__  =					'''ABABX'''
   lowerCamelCase__  =					'''ABABZABABYABABX'''
   assert kmp(pattern, text)

   # Test 3)
   lowerCamelCase__  =					'''AAAB'''
   lowerCamelCase__  =					'''ABAAAAAB'''
   assert kmp(pattern, text)

   # Test 4)
   lowerCamelCase__  =					'''abcdabcy'''
   lowerCamelCase__  =					'''abcxabcdabxabcdabcdabcy'''
   assert kmp(pattern, text)

   # Test 5)
   lowerCamelCase__  =					'''aabaabaaa'''
   assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]




