

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 				SCREAMING_SNAKE_CASE__ :





    def __init__(				self						,       a						,       a=12						,       a=7						,       a=True						,       a=True						,       a=True						,       a=99						,       a=32						,       a=32						,       a=2						,       a=4						,       a=37						,       a=0.1						,       a=0.1						,       a=512						,       a=0.02						,       a=0						,       a=None						,       ):
         lowercase__   :       Any				=	parent
         lowercase__   :       List[Any]				=	batch_size
         lowercase__   :       List[str]				=	seq_length
         lowercase__   :       List[Any]				=	is_training
         lowercase__   :       str				=	use_input_mask
         lowercase__   :       str				=	use_labels
         lowercase__   :       List[str]				=	vocab_size
         lowercase__   :       Any				=	hidden_size
         lowercase__   :       Tuple				=	projection_dim
         lowercase__   :       List[Any]				=	num_hidden_layers
         lowercase__   :       Optional[Any]				=	num_attention_heads
         lowercase__   :       List[str]				=	intermediate_size
         lowercase__   :       int				=	dropout
         lowercase__   :       Any				=	attention_dropout
         lowercase__   :       List[Any]				=	max_position_embeddings
         lowercase__   :       Tuple				=	initializer_range
         lowercase__   :       int				=	scope
         lowercase__   :       List[str]				=	bos_token_id





    def 				snake_case_    (				self):
         lowercase__   :       Tuple				=	ids_tensor([self.batch_size, self.seq_length]						,       self.vocab_size)

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

         if input_mask is not None:
              lowercase__   :       Any				=	input_mask.numpy()
              lowercase__				,			lowercase__   :       Dict				=	input_mask.shape
              lowercase__   :       str				=	np.random.randint(1						,       seq_length - 1						,       size=(batch_size,))
              for batch_idx, start_index in enumerate(__SCREAMING_SNAKE_CASE):
                   lowercase__   :       Tuple				=	1
                   lowercase__   :       Dict				=	0

         lowercase__   :       Optional[Any]				=	self.get_config()

         return config, input_ids, tf.convert_to_tensor(__SCREAMING_SNAKE_CASE)





    def 				snake_case_    (				self):
         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						,       a						,       a						,       a):
         lowercase__   :       List[Any]				=	TFBlipTextModel(config=__SCREAMING_SNAKE_CASE)
         lowercase__   :       List[str]				=	model(__SCREAMING_SNAKE_CASE						,       attention_mask=__SCREAMING_SNAKE_CASE						,       training=__SCREAMING_SNAKE_CASE)
         lowercase__   :       Union[str, Any]				=	model(__SCREAMING_SNAKE_CASE						,       training=__SCREAMING_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):
         lowercase__   :       Dict				=	self.prepare_config_and_inputs()
         lowercase__				,			lowercase__				,			lowercase__   :       List[str]				=	config_and_inputs
         lowercase__   :       Optional[int]				=	{'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict



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





    def 				snake_case_    (				self):
         lowercase__   :       Union[str, Any]				=	BlipTextModelTester(self)
         lowercase__   :       Optional[Any]				=	ConfigTester(self						,       config_class=__SCREAMING_SNAKE_CASE						,       hidden_size=37)





    def 				snake_case_    (				self):
         self.config_tester.run_common_tests()





    def 				snake_case_    (				self):
         lowercase__   :       Any				=	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE)





    def 				snake_case_    (				self):
         pass





    def 				snake_case_    (				self):
         pass





    @unittest.skip(reason='Blip does not use inputs_embeds')
    def 				snake_case_    (				self):
         pass





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





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





    @slow
    def 				snake_case_    (				self):

         for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              lowercase__   :       Union[str, Any]				=	TFBlipTextModel.from_pretrained(__SCREAMING_SNAKE_CASE)
              self.assertIsNotNone(__SCREAMING_SNAKE_CASE)





    def 				snake_case_    (				self						,       a=True):
         super().test_pt_tf_model_equivalence(allow_missing_keys=__SCREAMING_SNAKE_CASE)




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


snake_case_        =			logging.get_logger(__name__)


if is_vision_available():
       import PIL


class 				SCREAMING_SNAKE_CASE__ (__snake_case					):
    __lowerCamelCase						:	Optional[Any]														=					["""pixel_values"""]





    def __init__(				self						,       a = True						,       a = None						,       a = PILImageResampling.BICUBIC						,       a = True						,       a = None						,       a = True						,       a = 1 / 255						,       a = True						,       a = None						,       a = None						,       a = True						,       **a						,       ):
         super().__init__(**a)
         lowercase__   :       List[str]				=	size if size is not None else {'shortest_edge': 224}
         lowercase__   :       str				=	get_size_dict(a						,       default_to_square=a)
         lowercase__   :       Optional[int]				=	crop_size if crop_size is not None else {'height': 224, 'width': 224}
         lowercase__   :       Union[str, Any]				=	get_size_dict(a						,       default_to_square=a						,       param_name='crop_size')

         lowercase__   :       List[str]				=	do_resize
         lowercase__   :       List[Any]				=	size
         lowercase__   :       Tuple				=	resample
         lowercase__   :       int				=	do_center_crop
         lowercase__   :       Union[str, Any]				=	crop_size
         lowercase__   :       int				=	do_rescale
         lowercase__   :       List[str]				=	rescale_factor
         lowercase__   :       Tuple				=	do_normalize
         lowercase__   :       str				=	image_mean if image_mean is not None else OPENAI_CLIP_MEAN
         lowercase__   :       Optional[Any]				=	image_std if image_std is not None else OPENAI_CLIP_STD
         lowercase__   :       List[Any]				=	do_convert_rgb





    def 				snake_case_    (				self						,       a						,       a						,       a = PILImageResampling.BICUBIC						,       a = None						,       **a						,       ):
         lowercase__   :       str				=	get_size_dict(a						,       default_to_square=a)
         if "shortest_edge" not in size:
              raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""")
         lowercase__   :       str				=	get_resize_output_image_size(a						,       size=size['shortest_edge']						,       default_to_square=a)
         return resize(a						,       size=a						,       resample=a						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a						,       a = None						,       **a						,       ):
         lowercase__   :       List[str]				=	get_size_dict(a)
         if "height" not in size or "width" not in size:
              raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""")
         return center_crop(a						,       size=(size['height'], size['width'])						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a						,       a = None						,       **a						,       ):
         return rescale(a						,       scale=a						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a						,       a						,       a = None						,       **a						,       ):
         return normalize(a						,       mean=a						,       std=a						,       data_format=a						,       **a)





    def 				snake_case_    (				self						,       a						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = None						,       a = ChannelDimension.FIRST						,       **a						,       ):
         lowercase__   :       int				=	do_resize if do_resize is not None else self.do_resize
         lowercase__   :       Tuple				=	size if size is not None else self.size
         lowercase__   :       Union[str, Any]				=	get_size_dict(a						,       param_name='size'						,       default_to_square=a)
         lowercase__   :       Optional[Any]				=	resample if resample is not None else self.resample
         lowercase__   :       int				=	do_center_crop if do_center_crop is not None else self.do_center_crop
         lowercase__   :       List[Any]				=	crop_size if crop_size is not None else self.crop_size
         lowercase__   :       Union[str, Any]				=	get_size_dict(a						,       param_name='crop_size'						,       default_to_square=a)
         lowercase__   :       Dict				=	do_rescale if do_rescale is not None else self.do_rescale
         lowercase__   :       int				=	rescale_factor if rescale_factor is not None else self.rescale_factor
         lowercase__   :       List[str]				=	do_normalize if do_normalize is not None else self.do_normalize
         lowercase__   :       Optional[Any]				=	image_mean if image_mean is not None else self.image_mean
         lowercase__   :       List[str]				=	image_std if image_std is not None else self.image_std
         lowercase__   :       Any				=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

         lowercase__   :       str				=	make_list_of_images(a)

         if not valid_images(a):
              raise ValueError(
                  'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                  'torch.Tensor, tf.Tensor or jax.ndarray.')

         if do_resize and size is None:
              raise ValueError('Size must be specified if do_resize is True.')

         if do_center_crop and crop_size is None:
              raise ValueError('Crop size must be specified if do_center_crop is True.')

         if do_rescale and rescale_factor is None:
              raise ValueError('Rescale factor must be specified if do_rescale is True.')

         if do_normalize and (image_mean is None or image_std is None):
              raise ValueError('Image mean and std must be specified if do_normalize is True.')

         # PIL RGBA images are converted to RGB
         if do_convert_rgb:
              lowercase__   :       str				=	[convert_to_rgb(a) for image in images]

         # All transformations expect numpy arrays.
         lowercase__   :       Dict				=	[to_numpy_array(a) for image in images]

         if do_resize:
              lowercase__   :       Tuple				=	[self.resize(image=a						,       size=a						,       resample=a) for image in images]

         if do_center_crop:
              lowercase__   :       List[str]				=	[self.center_crop(image=a						,       size=a) for image in images]

         if do_rescale:
              lowercase__   :       str				=	[self.rescale(image=a						,       scale=a) for image in images]

         if do_normalize:
              lowercase__   :       Tuple				=	[self.normalize(image=a						,       mean=a						,       std=a) for image in images]

         lowercase__   :       Optional[int]				=	[to_channel_dimension_format(a						,       a) for image in images]

         lowercase__   :       Dict				=	{'pixel_values': images}
         return BatchFeature(data=a						,       tensor_type=a)

