





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:
      """simple docstring"""





      a__						:    int   		=	parent
      a__						:    List[str]   		=	batch_size
      a__						:    Dict   		=	seq_length
      a__						:    Tuple   		=	is_training
      a__						:    List[Any]   		=	use_input_mask
      a__						:    Optional[int]   		=	use_labels
      a__						:    Optional[int]   		=	vocab_size
      a__						:    str   		=	hidden_size
      a__						:    Any   		=	projection_dim
      a__						:    Dict   		=	num_hidden_layers
      a__						:    Dict   		=	num_attention_heads
      a__						:    int   		=	intermediate_size
      a__						:    str   		=	dropout
      a__						:    Any   		=	attention_dropout
      a__						:    str   		=	max_position_embeddings
      a__						:    List[Any]   		=	initializer_range
      a__						:    Dict   		=	scope
      a__						:    Dict   		=	bos_token_id





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    List[str]   		=	ids_tensor([self.batch_size, self.seq_length]       ,      self.vocab_size   )

      a__						:    List[str]   		=	None
      if self.use_input_mask:
         a__						:    List[str]   		=	random_attention_mask([self.batch_size, self.seq_length]   )

      if input_mask is not None:
         a__						:    Any   		=	input_mask.numpy()
         a__		,  a__						:    List[Any]   		=	input_mask.shape
         a__						:    int   		=	np.random.randint(1       ,      seq_length - 1       ,      size=(batch_size,)   )
         for batch_idx, start_index in enumerate(snake_case   ):
            a__						:    Optional[Any]   		=	1
            a__						:    int   		=	0

      a__						:    Dict   		=	self.get_config()

      return config, input_ids, tf.convert_to_tensor(snake_case   )





   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      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 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case   )					->	int:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	TFBlipTextModel(config=snake_case   )
      a__						:    int   		=	model(snake_case       ,      attention_mask=snake_case       ,      training=snake_case   )
      a__						:    Optional[int]   		=	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 						_snake_case			(			self   )					->	Tuple:
      """simple docstring"""





      a__						:    List[str]   		=	self.prepare_config_and_inputs()
      a__		,  a__		,  a__						:    List[Any]   		=	config_and_inputs
      a__						:    Any   		=	{"input_ids": input_ids, "attention_mask": input_mask}
      return config, inputs_dict







@require_tf
class 	__lowerCAmelCase      (       _UpperCamelCase		,unittest.TestCase	):
   _UpperCamelCase			:    str  		=					(TFBlipTextModel,) if is_tf_available() else ()
   _UpperCamelCase			:    List[str]  		=					False
   _UpperCamelCase			:    Optional[int]  		=					False
   _UpperCamelCase			:    List[str]  		=					False





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	BlipTextModelTester(self   )
      a__						:    List[Any]   		=	ConfigTester(self       ,      config_class=snake_case       ,      hidden_size=37   )





   def 						_snake_case			(			self   )					->	Tuple:
      """simple docstring"""





      self.config_tester.run_common_tests()





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    int   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case   )





   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      pass





   def 						_snake_case			(			self   )					->	int:
      """simple docstring"""





      pass





   @unittest.skip(reason="Blip does not use inputs_embeds"   )
   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      pass





   @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"   )
   def 						_snake_case			(			self   )					->	int:
      """simple docstring"""





      pass





   @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"   )
   def 						_snake_case			(			self   )					->	List[str]:
      """simple docstring"""





      pass





   @slow
   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         a__						:    List[str]   		=	TFBlipTextModel.from_pretrained(snake_case   )
         self.assertIsNotNone(snake_case   )





   def 						_snake_case			(			self       ,      snake_case=True   )					->	List[str]:
      """simple docstring"""





      super().test_pt_tf_model_equivalence(allow_missing_keys=snake_case   )








import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


SCREAMING_SNAKE_CASE__							:      Tuple         =    logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__							:      int         =    {
    """google/pix2struct-textcaps-base""": (
        """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"""
    ),
}







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    Optional[int]  		=					"""pix2struct_text_model"""
   _UpperCamelCase			:    Dict  		=					["""past_key_values"""]
   _UpperCamelCase			:    Union[str, Any]  		=					{
       """hidden_size""": """hidden_size""",
       """num_attention_heads""": """num_heads""",
       """num_hidden_layers""": """num_layers""",
   }





   def __init__(			self       ,      snake_case=50_244       ,      snake_case=768       ,      snake_case=64       ,      snake_case=2_048       ,      snake_case=12       ,      snake_case=12       ,      snake_case=32       ,      snake_case=128       ,      snake_case=0.1       ,      snake_case=1E-6       ,      snake_case=1.0       ,      snake_case="gelu_new"       ,      snake_case=0       ,      snake_case=False       ,      snake_case=0       ,      snake_case=1       ,      snake_case=False       ,      snake_case=True       ,      **snake_case       ,      )					->	Dict:
      """simple docstring"""





      a__						:    Tuple   		=	vocab_size
      a__						:    List[str]   		=	hidden_size
      a__						:    Optional[Any]   		=	d_kv
      a__						:    List[str]   		=	d_ff
      a__						:    Optional[int]   		=	num_layers
      a__						:    Tuple   		=	num_heads
      a__						:    List[Any]   		=	relative_attention_num_buckets
      a__						:    Optional[int]   		=	relative_attention_max_distance
      a__						:    Optional[int]   		=	dropout_rate
      a__						:    List[Any]   		=	layer_norm_epsilon
      a__						:    List[str]   		=	initializer_factor
      a__						:    Any   		=	use_cache

      a__						:    Any   		=	eos_token_id
      a__						:    List[Any]   		=	decoder_start_token_id

      # for backwards compatibility
      a__						:    Tuple   		=	dense_act_fn

      super().__init__(
          pad_token_id=snake_case       ,      eos_token_id=snake_case       ,      decoder_start_token_id=snake_case       ,      tie_word_embeddings=snake_case       ,      is_decoder=snake_case       ,      **snake_case       ,      )





   @classmethod
   def 						_snake_case			(			cls       ,      snake_case       ,      **snake_case   )					->	"PretrainedConfig":
      """simple docstring"""





      cls._set_token_in_kwargs(snake_case   )

      a__		,  a__						:    Optional[Any]   		=	cls.get_config_dict(snake_case       ,      **snake_case   )

      # get the text config dict if we are loading from Pix2StructConfig
      if config_dict.get("model_type"   ) == "pix2struct":
         a__						:    Optional[int]   		=	config_dict["text_config"]

      if "model_type" in config_dict and hasattr(cls       ,      "model_type"   ) and config_dict["model_type"] != cls.model_type:
         logger.warning(
             F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
             F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""   )

      return cls.from_dict(snake_case       ,      **snake_case   )







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    int  		=					"""pix2struct_vision_model"""





   def __init__(			self       ,      snake_case=768       ,      snake_case=768       ,      snake_case=2_048       ,      snake_case=64       ,      snake_case=12       ,      snake_case=12       ,      snake_case="gelu_new"       ,      snake_case=1E-6       ,      snake_case=0.0       ,      snake_case=0.0       ,      snake_case=1E-10       ,      snake_case=1.0       ,      snake_case=4_096       ,      snake_case=32       ,      snake_case=128       ,      **snake_case       ,      )					->	Optional[Any]:
      """simple docstring"""





      super().__init__(**snake_case   )

      a__						:    Optional[Any]   		=	hidden_size
      a__						:    Tuple   		=	patch_embed_hidden_size
      a__						:    Tuple   		=	d_ff
      a__						:    List[Any]   		=	dropout_rate
      a__						:    Optional[Any]   		=	num_hidden_layers
      a__						:    Optional[Any]   		=	num_attention_heads
      a__						:    List[str]   		=	initializer_range
      a__						:    List[str]   		=	initializer_factor
      a__						:    List[Any]   		=	attention_dropout
      a__						:    Optional[int]   		=	layer_norm_eps
      a__						:    int   		=	dense_act_fn
      a__						:    Optional[Any]   		=	seq_len
      a__						:    List[Any]   		=	relative_attention_num_buckets
      a__						:    int   		=	relative_attention_max_distance
      a__						:    int   		=	d_kv





   @classmethod
   def 						_snake_case			(			cls       ,      snake_case       ,      **snake_case   )					->	"PretrainedConfig":
      """simple docstring"""





      cls._set_token_in_kwargs(snake_case   )

      a__		,  a__						:    int   		=	cls.get_config_dict(snake_case       ,      **snake_case   )

      # get the vision config dict if we are loading from Pix2StructConfig
      if config_dict.get("model_type"   ) == "pix2struct":
         a__						:    int   		=	config_dict["vision_config"]

      if "model_type" in config_dict and hasattr(cls       ,      "model_type"   ) and config_dict["model_type"] != cls.model_type:
         logger.warning(
             F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
             F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""   )

      return cls.from_dict(snake_case       ,      **snake_case   )







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    List[Any]  		=					"""pix2struct"""
   _UpperCamelCase			:    Dict  		=					True





   def __init__(			self       ,      snake_case=None       ,      snake_case=None       ,      snake_case=1.0       ,      snake_case=0.02       ,      snake_case=False       ,      snake_case=False       ,      snake_case=True       ,      **snake_case       ,      )					->	Optional[int]:
      """simple docstring"""





      super().__init__(tie_word_embeddings=snake_case       ,      is_encoder_decoder=snake_case       ,      **snake_case   )

      if text_config is None:
         a__						:    Optional[Any]   		=	{}
         logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values."   )

      if vision_config is None:
         a__						:    List[Any]   		=	{}
         logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values."   )

      a__						:    List[str]   		=	PixaStructTextConfig(**snake_case   )
      a__						:    List[str]   		=	PixaStructVisionConfig(**snake_case   )

      a__						:    Tuple   		=	self.text_config.decoder_start_token_id
      a__						:    int   		=	self.text_config.pad_token_id
      a__						:    List[Any]   		=	self.text_config.eos_token_id

      a__						:    str   		=	initializer_factor
      a__						:    Dict   		=	initializer_range

      a__						:    Optional[int]   		=	self.initializer_range
      a__						:    Union[str, Any]   		=	self.initializer_range

      a__						:    Union[str, Any]   		=	is_vqa





   @classmethod
   def 						_snake_case			(			cls       ,      snake_case       ,      snake_case       ,      **snake_case   )					->	Dict:
      """simple docstring"""





      return cls(text_config=text_config.to_dict()       ,      vision_config=vision_config.to_dict()       ,      **snake_case   )





   def 						_snake_case			(			self   )					->	int:
      """simple docstring"""





      a__						:    Tuple   		=	copy.deepcopy(self.__dict__   )
      a__						:    List[str]   		=	self.text_config.to_dict()
      a__						:    Union[str, Any]   		=	self.vision_config.to_dict()
      a__						:    List[Any]   		=	self.__class__.model_type
      return output

