
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				:   Union[str, Any]    ,   _A				:   List[Any]    ,   _A				:   Optional[Any]=1_2    ,   _A				:   Optional[Any]=7    ,   _A				:   List[Any]=True    ,   _A				:   int=True    ,   _A				:   List[str]=True    ,   _A				:   Any=9_9    ,   _A				:   List[str]=3_2    ,   _A				:   Optional[Any]=3_2    ,   _A				:   str=2    ,   _A				:   List[str]=4    ,   _A				:   Optional[int]=3_7    ,   _A				:   Union[str, Any]=0.1    ,   _A				:   Tuple=0.1    ,   _A				:   int=5_1_2    ,   _A				:   Any=0.02    ,   _A				:   Dict=0    ,   _A				:   Optional[Any]=None    ,   )						->						List[str]:
         snake_case								= parent
         snake_case								= batch_size
         snake_case								= seq_length
         snake_case								= is_training
         snake_case								= use_input_mask
         snake_case								= use_labels
         snake_case								= vocab_size
         snake_case								= hidden_size
         snake_case								= projection_dim
         snake_case								= num_hidden_layers
         snake_case								= num_attention_heads
         snake_case								= intermediate_size
         snake_case								= dropout
         snake_case								= attention_dropout
         snake_case								= max_position_embeddings
         snake_case								= initializer_range
         snake_case								= scope
         snake_case								= bos_token_id





     def 		UpperCAmelCase(self				:   Optional[Any]       )						->						Union[str, Any]:
         snake_case								= ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size       )

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

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

         snake_case								= self.get_config()

         return config, input_ids, tf.convert_to_tensor(_A       )





     def 		UpperCAmelCase(self				:   Optional[Any]       )						->						Union[str, 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 		UpperCAmelCase(self				:   List[str]    ,   _A				:   Union[str, Any]    ,   _A				:   Optional[Any]    ,   _A				:   Optional[int]       )						->						Optional[int]:
         snake_case								= TFBlipTextModel(config=_A       )
         snake_case								= model(_A    ,   attention_mask=_A    ,   training=_A       )
         snake_case								= model(_A    ,   training=_A       )
         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 		UpperCAmelCase(self				:   int       )						->						Any:
         snake_case								= self.prepare_config_and_inputs()
         snake_case					,							snake_case					,							snake_case								= config_and_inputs
         snake_case								= {"input_ids": input_ids, "attention_mask": input_mask}
         return config, inputs_dict







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





     def 		UpperCAmelCase(self				:   Tuple       )						->						List[Any]:
         snake_case								= BlipTextModelTester(self       )
         snake_case								= ConfigTester(self    ,   config_class=_A    ,   hidden_size=3_7       )





     def 		UpperCAmelCase(self				:   Tuple       )						->						Any:
         self.config_tester.run_common_tests()





     def 		UpperCAmelCase(self				:   Optional[int]       )						->						Tuple:
         snake_case								= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_A       )





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





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





     @unittest.skip(reason="Blip does not use inputs_embeds"       )
     def 		UpperCAmelCase(self				:   int       )						->						Optional[Any]:
         pass





     @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"       )
     def 		UpperCAmelCase(self				:   Optional[int]       )						->						List[Any]:
         pass





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





     @slow
     def 		UpperCAmelCase(self				:   Any       )						->						Dict:
         for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             snake_case								= TFBlipTextModel.from_pretrained(_A       )
             self.assertIsNotNone(_A       )





     def 		UpperCAmelCase(self				:   Optional[Any]    ,   _A				:   str=True       )						->						List[str]:
         super().test_pt_tf_model_equivalence(allow_missing_keys=_A       )



import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Dict									=		["image_processor", "tokenizer"]
     UpperCAmelCase__    :							Dict									=		"LayoutLMv2ImageProcessor"
     UpperCAmelCase__    :							Optional[Any]									=		("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")





     def __init__(self				:   str    ,   _A				:   Any=None    ,   _A				:   Tuple=None    ,   **_A				:   Optional[Any]       )						->						Optional[int]:
         if "feature_extractor" in kwargs:
             warnings.warn(
                 "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                 " instead."    ,   _A    ,   )
             snake_case								= kwargs.pop("feature_extractor"       )

         snake_case								= image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
             raise ValueError("You need to specify an `image_processor`."       )
         if tokenizer is None:
             raise ValueError("You need to specify a `tokenizer`."       )

         super().__init__(_A    ,   _A       )





     def __call__(self				:   int    ,   _A				:   List[str]    ,   _A				:   Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None    ,   _A				:   Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None    ,   _A				:   Union[List[List[int]], List[List[List[int]]]] = None    ,   _A				:   Optional[Union[List[int], List[List[int]]]] = None    ,   _A				:   bool = True    ,   _A				:   Union[bool, str, PaddingStrategy] = False    ,   _A				:   Union[bool, str, TruncationStrategy] = None    ,   _A				:   Optional[int] = None    ,   _A				:   int = 0    ,   _A				:   Optional[int] = None    ,   _A				:   Optional[bool] = None    ,   _A				:   Optional[bool] = None    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = True    ,   _A				:   Optional[Union[str, TensorType]] = None    ,   **_A				:   Dict    ,   )						->						BatchEncoding:
         # verify input
         if self.image_processor.apply_ocr and (boxes is not None):
             raise ValueError(
                 "You cannot provide bounding boxes "
                 "if you initialized the image processor with apply_ocr set to True."       )

         if self.image_processor.apply_ocr and (word_labels is not None):
             raise ValueError(
                 "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."       )

         if return_overflowing_tokens is True and return_offsets_mapping is False:
             raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."       )

         # first, apply the image processor
         snake_case								= self.image_processor(images=_A    ,   return_tensors=_A       )

         # second, apply the tokenizer
         if text is not None and self.image_processor.apply_ocr and text_pair is None:
             if isinstance(_A    ,   _A       ):
                 snake_case								= [text]  # add batch dimension (as the image processor always adds a batch dimension)
             snake_case								= features["words"]

         snake_case								= self.tokenizer(
             text=text if text is not None else features["words"]    ,   text_pair=text_pair if text_pair is not None else None    ,   boxes=boxes if boxes is not None else features["boxes"]    ,   word_labels=_A    ,   add_special_tokens=_A    ,   padding=_A    ,   truncation=_A    ,   max_length=_A    ,   stride=_A    ,   pad_to_multiple_of=_A    ,   return_token_type_ids=_A    ,   return_attention_mask=_A    ,   return_overflowing_tokens=_A    ,   return_special_tokens_mask=_A    ,   return_offsets_mapping=_A    ,   return_length=_A    ,   verbose=_A    ,   return_tensors=_A    ,   **_A    ,   )

         # add pixel values
         snake_case								= features.pop("pixel_values"       )
         if return_overflowing_tokens is True:
             snake_case								= self.get_overflowing_images(_A    ,   encoded_inputs["overflow_to_sample_mapping"]       )
         snake_case								= images

         return encoded_inputs





     def 		UpperCAmelCase(self				:   Dict    ,   _A				:   Dict    ,   _A				:   List[str]       )						->						Optional[int]:
         # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
         snake_case								= []
         for sample_idx in overflow_to_sample_mapping:
             images_with_overflow.append(images[sample_idx]       )

         if len(_A       ) != len(_A       ):
             raise ValueError(
                 "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
                 f' {len(_A       )} and {len(_A       )}'       )

         return images_with_overflow





     def 		UpperCAmelCase(self				:   Tuple    ,   *_A				:   int    ,   **_A				:   Dict       )						->						str:
         return self.tokenizer.batch_decode(*_A    ,   **_A       )





     def 		UpperCAmelCase(self				:   str    ,   *_A				:   List[Any]    ,   **_A				:   List[Any]       )						->						Optional[Any]:
         return self.tokenizer.decode(*_A    ,   **_A       )





     @property
     def 		UpperCAmelCase(self				:   Tuple       )						->						Optional[int]:
         return ["input_ids", "bbox", "attention_mask", "image"]





     @property
     def 		UpperCAmelCase(self				:   List[Any]       )						->						int:
         warnings.warn(
             "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."    ,   _A    ,   )
         return self.image_processor_class





     @property
     def 		UpperCAmelCase(self				:   Dict       )						->						Union[str, Any]:
         warnings.warn(
             "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."    ,   _A    ,   )
         return self.image_processor

