






"""simple docstring"""


import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask


if is_torch_available():
       import torch

       from transformers import BlipTextModel
       from transformers.models.blip.modeling_blip import BLIP_PRETRAINED_MODEL_ARCHIVE_LIST


class    snake_case						:


   '''simple docstring'''

   def __init__(      self					:	Dict,			_lowerCamelCase					:	Optional[Any],			_lowerCamelCase					:	str=12,			_lowerCamelCase					:	Optional[int]=7,			_lowerCamelCase					:	Union[str, Any]=True,			_lowerCamelCase					:	Dict=True,			_lowerCamelCase					:	Any=True,			_lowerCamelCase					:	Optional[int]=99,			_lowerCamelCase					:	List[Any]=32,			_lowerCamelCase					:	Optional[Any]=32,			_lowerCamelCase					:	str=5,			_lowerCamelCase					:	Any=4,			_lowerCamelCase					:	Optional[int]=37,			_lowerCamelCase					:	Any=0.1,			_lowerCamelCase					:	Optional[Any]=0.1,			_lowerCamelCase					:	int=5_12,			_lowerCamelCase					:	List[str]=0.02,			_lowerCamelCase					:	str=0,			_lowerCamelCase					:	List[str]=None,			):

     '''simple docstring'''
     __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 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple    ):

     '''simple docstring'''
     __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     ,       __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, input_mask


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[str]    ):

     '''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 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[int],			_lowerCamelCase					:	List[Any],			_lowerCamelCase					:	Union[str, Any],			_lowerCamelCase					:	str    ):

     '''simple docstring'''
     __A		     =					BlipTextModel(config=_lowerCamelCase    )
     model.to(_lowerCamelCase    )
     model.eval()
     with torch.no_grad():
       __A		     =					model(_lowerCamelCase,			attention_mask=_lowerCamelCase    )
       __A		     =					model(_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 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple    ):

     '''simple docstring'''
     __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_torch
class    snake_case						(				_lowerCAmelCase  ,      unittest.TestCase		):


   '''simple docstring'''

   A_		:      str							=					(BlipTextModel,) if is_torch_available() else ()
   A_		:      Optional[int]							=					False
   A_		:      int							=					False
   A_		:      List[str]							=					False


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any]    ):

     '''simple docstring'''
     __A		     =					BlipTextModelTester(self    )
     __A		     =					ConfigTester(self,			config_class=_lowerCamelCase,			hidden_size=37    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any]    ):

     '''simple docstring'''
     self.config_tester.run_common_tests()


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Any    ):

     '''simple docstring'''
     __A		     =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_lowerCamelCase    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Union[str, Any]    ):

     '''simple docstring'''
     pass


   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     pass


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

     '''simple docstring'''
     pass


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

     '''simple docstring'''
     pass


   @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''    )
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[int]    ):

     '''simple docstring'''
     pass


   @slow
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any]    ):

     '''simple docstring'''
     for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __A		     =					BlipTextModel.from_pretrained(_lowerCamelCase    )
       self.assertIsNotNone(_lowerCamelCase    )






   def 							_SCREAMING_SNAKE_CASE							(      self					:	Dict    ):

     '''simple docstring'''
     super().test_pt_tf_model_equivalence(allow_missing_keys=_lowerCamelCase    )










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, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_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


__A						:		Dict          =						logging.get_logger(__name__)

class 		lowercase_       (	lowerCAmelCase__				):
					__UpperCamelCase     	= ["pixel_values"]




					def __init__(   self:		str,     _lowercase:		bool = True,     _lowercase:		Dict[str, int] = None,     _lowercase:		PILImageResampling = PIL.Image.NEAREST,     _lowercase:		bool = False,     _lowercase:		Dict[str, int] = None,     _lowercase:		Union[int, float] = 1 / 255,     _lowercase:		bool = False,     _lowercase:		bool = True,     _lowercase:		bool = True,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		bool = True,     **_lowercase:		Union[str, Any],     ):


									'''simple docstring'''


									super().__init__(**_lowercase)
									__lowerCAmelCase					=  size if size is not None else {"""height""": 346, """width""": 346}
									__lowerCAmelCase					=  get_size_dict(_lowercase)
									__lowerCAmelCase					=  crop_size if crop_size is not None else {"""height""": 289, """width""": 289}
									__lowerCAmelCase					=  get_size_dict(_lowercase,     param_name="""crop_size""")

									__lowerCAmelCase					=  do_resize
									__lowerCAmelCase					=  size
									__lowerCAmelCase					=  resample
									__lowerCAmelCase					=  do_center_crop
									__lowerCAmelCase					=  crop_size
									__lowerCAmelCase					=  do_rescale
									__lowerCAmelCase					=  rescale_factor
									__lowerCAmelCase					=  rescale_offset
									__lowerCAmelCase					=  do_normalize
									__lowerCAmelCase					=  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
									__lowerCAmelCase					=  image_std if image_std is not None else IMAGENET_STANDARD_STD
									__lowerCAmelCase					=  include_top




					def     _lowercase						(   self:		Optional[Any],     _lowercase:		np.ndarray,     _lowercase:		Dict[str, int],     _lowercase:		PILImageResampling = PIL.Image.NEAREST,     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Dict,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  get_size_dict(_lowercase)
									if "height" not in size or "width" not in size:
													raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''')
									return resize(
									    _lowercase,     size=(size["""height"""], size["""width"""]),     resample=_lowercase,     data_format=_lowercase,     **_lowercase)




					def     _lowercase						(   self:		List[str],     _lowercase:		np.ndarray,     _lowercase:		Dict[str, int],     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Tuple,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  get_size_dict(_lowercase)
									if "height" not in size or "width" not in size:
													raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''')
									return center_crop(_lowercase,     size=(size["""height"""], size["""width"""]),     data_format=_lowercase,     **_lowercase)




					def     _lowercase						(   self:		Union[str, Any],     _lowercase:		np.ndarray,     _lowercase:		Union[int, float],     _lowercase:		bool = True,     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Dict,     ):


									'''simple docstring'''


									if offset:
													__lowerCAmelCase					=  (image - 127.5) * scale
													if data_format is not None:
																	__lowerCAmelCase					=  to_channel_dimension_format(_lowercase,     _lowercase)
													__lowerCAmelCase					=  rescaled_image.astype(np.floataa)
									else:
													__lowerCAmelCase					=  rescale(_lowercase,     scale=_lowercase,     data_format=_lowercase,     **_lowercase)
									return rescaled_image




					def     _lowercase						(   self:		Dict,     _lowercase:		np.ndarray,     _lowercase:		Union[float, List[float]],     _lowercase:		Union[float, List[float]],     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Any,     ):


									'''simple docstring'''


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







					def     _lowercase						(   self:		Dict,     _lowercase:		ImageInput,     _lowercase:		bool = None,     _lowercase:		Dict[str, int] = None,     _lowercase:		str=None,     _lowercase:		bool = None,     _lowercase:		Dict[str, int] = None,     _lowercase:		bool = None,     _lowercase:		float = None,     _lowercase:		bool = None,     _lowercase:		bool = None,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		bool = None,     _lowercase:		Optional[Union[str, TensorType]] = None,     _lowercase:		ChannelDimension = ChannelDimension.FIRST,     **_lowercase:		Tuple,     ):


									'''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_center_crop if do_center_crop is not None else self.do_center_crop
									__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					=  rescale_offset if rescale_offset is not None else self.rescale_offset
									__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					=  include_top if include_top is not None else self.include_top

									__lowerCAmelCase					=  size if size is not None else self.size
									__lowerCAmelCase					=  get_size_dict(_lowercase)
									__lowerCAmelCase					=  crop_size if crop_size is not None else self.crop_size
									__lowerCAmelCase					=  get_size_dict(_lowercase,     param_name="""crop_size""")

									__lowerCAmelCase					=  make_list_of_images(_lowercase)

									if not valid_images(_lowercase):
													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_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.""")

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

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

									if do_center_crop:
													__lowerCAmelCase					=  [self.center_crop(image=_lowercase,     size=_lowercase) for image in images]

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

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

									if include_top:
													__lowerCAmelCase					=  [self.normalize(image=_lowercase,     mean=[0, 0, 0],     std=_lowercase) for image in images]

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

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





