






"""simple docstring"""





from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
  import tensorflow as tf

  from transformers import TFBlipTextModel
  from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST
class    __lowerCamelCase    :

   def __init__(					self ,				snake_case_ ,				snake_case_=12 ,				snake_case_=7 ,				snake_case_=True ,				snake_case_=True ,				snake_case_=True ,				snake_case_=99 ,				snake_case_=32 ,				snake_case_=32 ,				snake_case_=2 ,				snake_case_=4 ,				snake_case_=37 ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=512 ,				snake_case_=0.02 ,				snake_case_=0 ,				snake_case_=None ,				)		->       Dict:
       UpperCamelCase__         =    parent
       UpperCamelCase__         =    batch_size
       UpperCamelCase__         =    seq_length
       UpperCamelCase__         =    is_training
       UpperCamelCase__         =    use_input_mask
       UpperCamelCase__         =    use_labels
       UpperCamelCase__         =    vocab_size
       UpperCamelCase__         =    hidden_size
       UpperCamelCase__         =    projection_dim
       UpperCamelCase__         =    num_hidden_layers
       UpperCamelCase__         =    num_attention_heads
       UpperCamelCase__         =    intermediate_size
       UpperCamelCase__         =    dropout
       UpperCamelCase__         =    attention_dropout
       UpperCamelCase__         =    max_position_embeddings
       UpperCamelCase__         =    initializer_range
       UpperCamelCase__         =    scope
       UpperCamelCase__         =    bos_token_id

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Any:
       UpperCamelCase__         =    ids_tensor([self.batch_size, self.seq_length] ,				self.vocab_size      )

       UpperCamelCase__         =    None
       if self.use_input_mask:
           UpperCamelCase__         =    random_attention_mask([self.batch_size, self.seq_length]      )

       if input_mask is not None:
           UpperCamelCase__         =    input_mask.numpy()
           UpperCamelCase__       ,						UpperCamelCase__         =    input_mask.shape
           UpperCamelCase__         =    np.random.randint(1 ,				seq_length - 1 ,				size=(batch_size,)      )
           for batch_idx, start_index in enumerate(snake_case_      ):
               UpperCamelCase__         =    1
               UpperCamelCase__         =    0

       UpperCamelCase__         =    self.get_config()

       return config, input_ids, tf.convert_to_tensor(snake_case_      )

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Any:
       return BlipTextConfig(
           vocab_size=self.vocab_size ,				hidden_size=self.hidden_size ,				projection_dim=self.projection_dim ,				num_hidden_layers=self.num_hidden_layers ,				num_attention_heads=self.num_attention_heads ,				intermediate_size=self.intermediate_size ,				dropout=self.dropout ,				attention_dropout=self.attention_dropout ,				max_position_embeddings=self.max_position_embeddings ,				initializer_range=self.initializer_range ,				bos_token_id=self.bos_token_id ,				)

   def 						SCREAMING_SNAKE_CASE__ (					self ,				snake_case_ ,				snake_case_ ,				snake_case_      )		->       Tuple:
       UpperCamelCase__         =    TFBlipTextModel(config=snake_case_      )
       UpperCamelCase__         =    model(snake_case_ ,				attention_mask=snake_case_ ,				training=snake_case_      )
       UpperCamelCase__         =    model(snake_case_ ,				training=snake_case_      )
       self.parent.assertEqual(result.last_hidden_state.shape ,				(self.batch_size, self.seq_length, self.hidden_size)      )
       self.parent.assertEqual(result.pooler_output.shape ,				(self.batch_size, self.hidden_size)      )







   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Dict:
       UpperCamelCase__         =    self.prepare_config_and_inputs()
       UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__         =    config_and_inputs
       UpperCamelCase__         =    {'input_ids': input_ids, 'attention_mask': input_mask}
       return config, inputs_dict







@require_tf
class    __lowerCamelCase    (  _a							,	unittest.TestCase  ):
   a      :				List[str] 						=(TFBlipTextModel,) if is_tf_available() else ()
   a      :				int 						=False
   a      :				Any 						=False
   a      :				Optional[Any] 						=False

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Union[str, Any]:
       UpperCamelCase__         =    BlipTextModelTester(self      )
       UpperCamelCase__         =    ConfigTester(self ,				config_class=snake_case_ ,				hidden_size=37      )

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Union[str, Any]:
       self.config_tester.run_common_tests()

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       List[Any]:
       UpperCamelCase__         =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case_      )

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Optional[int]:
       pass

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Union[str, Any]:
       pass

   @unittest.skip(reason='Blip does not use inputs_embeds'      )
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Union[str, Any]:
       pass

   @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'      )
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       int:
       pass

   @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'      )
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       int:
       pass

   @slow
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Any:
       for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__         =    TFBlipTextModel.from_pretrained(snake_case_      )
           self.assertIsNotNone(snake_case_      )







   def 						SCREAMING_SNAKE_CASE__ (					self ,				snake_case_=True      )		->       Tuple:
       super().test_pt_tf_model_equivalence(allow_missing_keys=snake_case_      )












"""simple docstring"""





import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow


if is_tf_available():
  import tensorflow as tf

if is_tensorflow_text_available():
  from transformers.models.bert import TFBertTokenizer


A__					: List[Any]=	["""bert-base-uncased""", """bert-base-cased"""]
A__					: Optional[int]=	"""hf-internal-testing/tiny-bert-tf-only"""

if is_tf_available():
  class    __lowerCamelCase    (  tf.keras.Model  ):

     def __init__(					self ,				snake_case_      )		->       Optional[int]:
         super().__init__()
         UpperCamelCase__         =    tokenizer
         UpperCamelCase__         =    AutoConfig.from_pretrained(snake_case_      )
         UpperCamelCase__         =    TFAutoModel.from_config(snake_case_      )







     def 						SCREAMING_SNAKE_CASE__ (					self ,				snake_case_      )		->       int:
         UpperCamelCase__         =    self.tokenizer(snake_case_      )
         UpperCamelCase__         =    self.bert(**snake_case_      )
         return out["pooler_output"]
@require_tf
@require_tensorflow_text
class    __lowerCamelCase    (  unittest.TestCase  ):

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       str:
       super().setUp()

       UpperCamelCase__         =    [
           BertTokenizer.from_pretrained(snake_case_      ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
       ]  # repeat for when fast_bert_tokenizer=false
       UpperCamelCase__         =    [TFBertTokenizer.from_pretrained(snake_case_      ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
           TFBertTokenizer.from_pretrained(snake_case_ ,				use_fast_bert_tokenizer=snake_case_      )
           for checkpoint in TOKENIZER_CHECKPOINTS
       ]
       assert len(self.tokenizers      ) == len(self.tf_tokenizers      )

       UpperCamelCase__         =    [
           'This is a straightforward English test sentence.',
           'This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.',
           'Now we\'re going to add some Chinese: 一 二 三 一二三',
           'And some much more rare Chinese: 齉 堃 齉堃',
           'Je vais aussi écrire en français pour tester les accents',
           'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ',
       ]
       UpperCamelCase__         =    list(zip(self.test_sentences ,				self.test_sentences[::-1]      )      )

   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Any:
       for tokenizer, tf_tokenizer in zip(self.tokenizers ,				self.tf_tokenizers      ):
           for test_inputs in (self.test_sentences, self.paired_sentences):
               UpperCamelCase__         =    tokenizer(snake_case_ ,				return_tensors='tf' ,				padding='longest'      )
               UpperCamelCase__         =    tf_tokenizer(snake_case_      )

               for key in python_outputs.keys():
                   self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape      )      )
                   self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] ,				tf.intaa      ) == tf_outputs[key]      )      )

   @slow
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       str:
       for tf_tokenizer in self.tf_tokenizers:
           UpperCamelCase__         =    tf_tokenizer(self.paired_sentences      )
           UpperCamelCase__         =    tf_tokenizer(
               text=[sentence[0] for sentence in self.paired_sentences] ,				text_pair=[sentence[1] for sentence in self.paired_sentences] ,				)
           for key in merged_outputs.keys():
               self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] ,				tf.intaa      ) == separated_outputs[key]      )      )

   @slow
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Dict:
       for tf_tokenizer in self.tf_tokenizers:
           UpperCamelCase__         =    tf.function(snake_case_      )
           for test_inputs in (self.test_sentences, self.paired_sentences):
               UpperCamelCase__         =    tf.constant(snake_case_      )
               UpperCamelCase__         =    compiled_tokenizer(snake_case_      )
               UpperCamelCase__         =    tf_tokenizer(snake_case_      )

               for key in eager_outputs.keys():
                   self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]      )      )







   @slow
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       List[str]:
       for tf_tokenizer in self.tf_tokenizers:
           UpperCamelCase__         =    ModelToSave(tokenizer=snake_case_      )
           UpperCamelCase__         =    tf.convert_to_tensor(self.test_sentences      )
           UpperCamelCase__         =    model(snake_case_      )  # Build model with some sample inputs
           with TemporaryDirectory() as tempdir:
               UpperCamelCase__         =    Path(snake_case_      ) / 'saved.model'
               model.save(snake_case_      )
               UpperCamelCase__         =    tf.keras.models.load_model(snake_case_      )
           UpperCamelCase__         =    loaded_model(snake_case_      )
           # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
           self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output      )      ) ,				1E-5      )




