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

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

  def 		_UpperCAmelCase (		self			:   Any							):
   __a							=	ids_tensor([self.batch_size, self.seq_length]  ,				self.vocab_size							)

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

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

   __a							=	self.get_config()

   return config, input_ids, tf.convert_to_tensor(__lowerCAmelCase							)

  def 		_UpperCAmelCase (		self			:   Optional[int]							):
   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			:   str  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]							):
   __a							=	TFBlipTextModel(config=__lowerCAmelCase							)
   __a							=	model(__lowerCAmelCase  ,				attention_mask=__lowerCAmelCase  ,				training=__lowerCAmelCase							)
   __a							=	model(__lowerCAmelCase  ,				training=__lowerCAmelCase							)
   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			:   str							):
   __a							=	self.prepare_config_and_inputs()
   __a							,  __a							,  __a							=	config_and_inputs
   __a							=	{"input_ids": input_ids, "attention_mask": input_mask}
   return config, inputs_dict
@require_tf
class  A_			(							lowerCAmelCase__      ,							unittest.TestCase			):
  _SCREAMING_SNAKE_CASE     					=      (TFBlipTextModel,) if is_tf_available() else ()
  _SCREAMING_SNAKE_CASE     					=      False
  _SCREAMING_SNAKE_CASE     					=      False
  _SCREAMING_SNAKE_CASE     					=      False

  def 		_UpperCAmelCase (		self			:   Union[str, Any]							):
   __a							=	BlipTextModelTester(self							)
   __a							=	ConfigTester(self  ,				config_class=__lowerCAmelCase  ,				hidden_size=37							)

  def 		_UpperCAmelCase (		self			:   Any							):
   self.config_tester.run_common_tests()

  def 		_UpperCAmelCase (		self			:   Optional[int]							):
   __a							=	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*__lowerCAmelCase							)

  def 		_UpperCAmelCase (		self			:   Tuple							):
   pass

  def 		_UpperCAmelCase (		self			:   Optional[Any]							):
   pass

  @unittest.skip(reason="Blip does not use inputs_embeds"							)
  def 		_UpperCAmelCase (		self			:   Union[str, Any]							):
   pass

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

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

  @slow
  def 		_UpperCAmelCase (		self			:   List[str]							):


   for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __a							=	TFBlipTextModel.from_pretrained(__lowerCAmelCase							)
    self.assertIsNotNone(__lowerCAmelCase							)

  def 		_UpperCAmelCase (		self			:   Any  ,				__SCREAMING_SNAKE_CASE			:   int=True							):
   super().test_pt_tf_model_equivalence(allow_missing_keys=__lowerCAmelCase							)



'''simple docstring'''




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 convert_to_rgb, 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


if is_vision_available():
						import PIL


__lowercase        =    logging.get_logger(__name__)






class 							a__(   lowerCAmelCase__      ):


			'''simple docstring'''






			UpperCAmelCase_     :	List[Any]						=			['''pixel_values''']



			def __init__(  self			,       __lowerCAmelCase = True			,       __lowerCAmelCase = None			,       __lowerCAmelCase = PILImageResampling.BICUBIC			,       __lowerCAmelCase = True			,       __lowerCAmelCase = 1 / 255			,       __lowerCAmelCase = True			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = True			,       **__lowerCAmelCase			,       ):




					"""simple docstring"""


					super().__init__(**__lowerCAmelCase)
					lowerCAmelCase     =    size if size is not None else {"""height""": 384, """width""": 384}
					lowerCAmelCase     =    get_size_dict(__lowerCAmelCase			,       default_to_square=__lowerCAmelCase)

					lowerCAmelCase     =    do_resize
					lowerCAmelCase     =    size
					lowerCAmelCase     =    resample
					lowerCAmelCase     =    do_rescale
					lowerCAmelCase     =    rescale_factor
					lowerCAmelCase     =    do_normalize
					lowerCAmelCase     =    image_mean if image_mean is not None else OPENAI_CLIP_MEAN
					lowerCAmelCase     =    image_std if image_std is not None else OPENAI_CLIP_STD
					lowerCAmelCase     =    do_convert_rgb



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase = PILImageResampling.BICUBIC			,       __lowerCAmelCase = None			,       **__lowerCAmelCase			,       ):




					"""simple docstring"""


					lowerCAmelCase     =    get_size_dict(__lowerCAmelCase			,       default_to_square=__lowerCAmelCase)
					if "height" not in size or "width" not in size:
							raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
					lowerCAmelCase     =    (size["""height"""], size["""width"""])
					return resize(__lowerCAmelCase			,       size=__lowerCAmelCase			,       resample=__lowerCAmelCase			,       data_format=__lowerCAmelCase			,       **__lowerCAmelCase)



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase = None			,       **__lowerCAmelCase			,       ):




					"""simple docstring"""


					return rescale(__lowerCAmelCase			,       scale=__lowerCAmelCase			,       data_format=__lowerCAmelCase			,       **__lowerCAmelCase)



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase = None			,       **__lowerCAmelCase			,       ):




					"""simple docstring"""


					return normalize(__lowerCAmelCase			,       mean=__lowerCAmelCase			,       std=__lowerCAmelCase			,       data_format=__lowerCAmelCase			,       **__lowerCAmelCase)







			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = ChannelDimension.FIRST			,       **__lowerCAmelCase			,       ):




					"""simple docstring"""


					lowerCAmelCase     =    do_resize if do_resize is not None else self.do_resize
					lowerCAmelCase     =    resample if resample is not None else self.resample
					lowerCAmelCase     =    do_rescale if do_rescale is not None else self.do_rescale
					lowerCAmelCase     =    rescale_factor if rescale_factor is not None else self.rescale_factor
					lowerCAmelCase     =    do_normalize if do_normalize is not None else self.do_normalize
					lowerCAmelCase     =    image_mean if image_mean is not None else self.image_mean
					lowerCAmelCase     =    image_std if image_std is not None else self.image_std
					lowerCAmelCase     =    do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

					lowerCAmelCase     =    size if size is not None else self.size
					lowerCAmelCase     =    get_size_dict(__lowerCAmelCase			,       default_to_square=__lowerCAmelCase)

					lowerCAmelCase     =    make_list_of_images(__lowerCAmelCase)

					if not valid_images(__lowerCAmelCase):
							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 or resample is None:
							raise ValueError("""Size and resample must be specified if do_resize 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:
							lowerCAmelCase     =    [convert_to_rgb(__lowerCAmelCase) for image in images]

					# All transformations expect numpy arrays.
					lowerCAmelCase     =    [to_numpy_array(__lowerCAmelCase) for image in images]

					if do_resize:
							lowerCAmelCase     =    [self.resize(image=__lowerCAmelCase			,       size=__lowerCAmelCase			,       resample=__lowerCAmelCase) for image in images]

					if do_rescale:
							lowerCAmelCase     =    [self.rescale(image=__lowerCAmelCase			,       scale=__lowerCAmelCase) for image in images]

					if do_normalize:
							lowerCAmelCase     =    [self.normalize(image=__lowerCAmelCase			,       mean=__lowerCAmelCase			,       std=__lowerCAmelCase) for image in images]

					lowerCAmelCase     =    [to_channel_dimension_format(__lowerCAmelCase			,       __lowerCAmelCase) for image in images]

					lowerCAmelCase     =    BatchFeature(data={"""pixel_values""": images}			,       tensor_type=__lowerCAmelCase)

					return encoded_outputs




