'''simple docstring'''

import unittest
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import BridgeTowerImageProcessor
class   SCREAMING_SNAKE_CASE			(						unittest.TestCase):







		"""simple docstring"""






		def __init__(   self		,						__A		,						__A = True		,						__A = None		,						__A = 32		,						__A = True		,						__A = 1 / 255		,						__A = True		,						__A = True		,						__A = [0.48_145_466, 0.4_578_275, 0.40_821_073]		,						__A = [0.26_862_954, 0.26_130_258, 0.27_577_711]		,						__A = True		,						__A=7		,						__A=30		,						__A=400		,						__A=3		,						) ->     Any:
								_lowerCAmelCase										=parent
								_lowerCAmelCase										=do_resize
								_lowerCAmelCase										=size if size is not None else {"shortest_edge": 288}
								_lowerCAmelCase										=size_divisor
								_lowerCAmelCase										=do_rescale
								_lowerCAmelCase										=rescale_factor
								_lowerCAmelCase										=do_normalize
								_lowerCAmelCase										=do_center_crop
								_lowerCAmelCase										=image_mean
								_lowerCAmelCase										=image_std
								_lowerCAmelCase										=do_pad
								_lowerCAmelCase										=batch_size
								_lowerCAmelCase										=num_channels
								_lowerCAmelCase										=min_resolution
								_lowerCAmelCase										=max_resolution






		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								return {
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								    "do_normalize": self.do_normalize,
								    "do_resize": self.do_resize,
								    "size": self.size,
								    "size_divisor": self.size_divisor,
								}






		def 		UpperCamelCase__       (   self		,						__A		,						__A=False				) ->     Optional[int]:
								if not batched:
														_lowerCAmelCase										=self.size["shortest_edge"]
														_lowerCAmelCase										=image_inputs[0]
														if isinstance(__A		,						Image.Image				):
																				_lowerCAmelCase										=image.size
														else:
																				_lowerCAmelCase										=image.shape[1], image.shape[2]
														_lowerCAmelCase										=size / min(__A		,						__A				)
														if h < w:
																				_lowerCAmelCase										=size, scale * w
														else:
																				_lowerCAmelCase										=scale * h, size

														_lowerCAmelCase										=int((1333 / 800) * size				)
														if max(__A		,						__A				) > max_size:
																				_lowerCAmelCase										=max_size / max(__A		,						__A				)
																				_lowerCAmelCase										=newh * scale
																				_lowerCAmelCase										=neww * scale

														_lowerCAmelCase										=int(newh + 0.5				), int(neww + 0.5				)
														_lowerCAmelCase										=(
														    newh // self.size_divisor * self.size_divisor,
														    neww // self.size_divisor * self.size_divisor,
														)

								else:
														_lowerCAmelCase										=[]
														for image in image_inputs:
																				_lowerCAmelCase										=self.get_expected_values([image]				)
																				expected_values.append((expected_height, expected_width)				)
														_lowerCAmelCase										=max(__A		,						key=lambda __A				: item[0]				)[0]
														_lowerCAmelCase										=max(__A		,						key=lambda __A				: item[1]				)[1]

								return expected_height, expected_width

@require_torch
@require_vision
class   SCREAMING_SNAKE_CASE			(						_A    ,			unittest.TestCase):







		"""simple docstring"""
		lowercase   :      Dict       =							BridgeTowerImageProcessor if is_vision_available() else None






		def 		UpperCamelCase__       (   self				) ->     List[str]:
								_lowerCAmelCase										=BridgeTowerImageProcessingTester(self				)






		@property
		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								return self.image_processor_tester.prepare_image_processor_dict()






		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								_lowerCAmelCase										=self.image_processing_class(**self.image_processor_dict				)
								self.assertTrue(hasattr(__A		,						'image_mean'				)				)
								self.assertTrue(hasattr(__A		,						'image_std'				)				)
								self.assertTrue(hasattr(__A		,						'do_normalize'				)				)
								self.assertTrue(hasattr(__A		,						'do_resize'				)				)
								self.assertTrue(hasattr(__A		,						'size'				)				)
								self.assertTrue(hasattr(__A		,						'size_divisor'				)				)






		def 		UpperCamelCase__       (   self				) ->     Union[str, Any]:
								pass






		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								# Initialize image processor
								_lowerCAmelCase										=self.image_processing_class(**self.image_processor_dict				)
								# create random PIL images
								_lowerCAmelCase										=prepare_image_inputs(self.image_processor_tester		,						equal_resolution=__A				)
								for image in image_inputs:
														self.assertIsInstance(__A		,						Image.Image				)

								# Test not batched input
								_lowerCAmelCase										=image_processing(image_inputs[0]		,						return_tensors='pt'				).pixel_values

								_lowerCAmelCase										=self.image_processor_tester.get_expected_values(__A				)
								self.assertEqual(
								    encoded_images.shape		,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,						)

								# Test batched
								_lowerCAmelCase										=image_processing(__A		,						return_tensors='pt'				).pixel_values

								_lowerCAmelCase										=self.image_processor_tester.get_expected_values(__A		,						batched=__A				)
								self.assertEqual(
								    encoded_images.shape		,						(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    )		,						)






		def 		UpperCamelCase__       (   self				) ->     List[str]:
								# Initialize image processor
								_lowerCAmelCase										=self.image_processing_class(**self.image_processor_dict				)
								# create random numpy tensors
								_lowerCAmelCase										=prepare_image_inputs(self.image_processor_tester		,						equal_resolution=__A		,						numpify=__A				)
								for image in image_inputs:
														self.assertIsInstance(__A		,						np.ndarray				)

								# Test not batched input
								_lowerCAmelCase										=image_processing(image_inputs[0]		,						return_tensors='pt'				).pixel_values

								_lowerCAmelCase										=self.image_processor_tester.get_expected_values(__A				)
								self.assertEqual(
								    encoded_images.shape		,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,						)

								# Test batched
								_lowerCAmelCase										=image_processing(__A		,						return_tensors='pt'				).pixel_values

								_lowerCAmelCase										=self.image_processor_tester.get_expected_values(__A		,						batched=__A				)
								self.assertEqual(
								    encoded_images.shape		,						(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    )		,						)






		def 		UpperCamelCase__       (   self				) ->     List[str]:
								# Initialize image processor
								_lowerCAmelCase										=self.image_processing_class(**self.image_processor_dict				)
								# create random PyTorch tensors
								_lowerCAmelCase										=prepare_image_inputs(self.image_processor_tester		,						equal_resolution=__A		,						torchify=__A				)
								for image in image_inputs:
														self.assertIsInstance(__A		,						torch.Tensor				)

								# Test not batched input
								_lowerCAmelCase										=image_processing(image_inputs[0]		,						return_tensors='pt'				).pixel_values

								_lowerCAmelCase										=self.image_processor_tester.get_expected_values(__A				)
								self.assertEqual(
								    encoded_images.shape		,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,						)

								# Test batched
								_lowerCAmelCase										=image_processing(__A		,						return_tensors='pt'				).pixel_values

								_lowerCAmelCase										=self.image_processor_tester.get_expected_values(__A		,						batched=__A				)
								self.assertEqual(
								    encoded_images.shape		,						(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    )		,						)






'''simple docstring'''

import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


lowercase_     		= logging.get_logger(__name__)

lowercase_     		= {
    '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''',
}
class   SCREAMING_SNAKE_CASE			(						__lowercase):







		"""simple docstring"""
		lowercase   :      Tuple       =							'blip_2_vision_model'






		def __init__(   self		,						__A=1408		,						__A=6144		,						__A=39		,						__A=16		,						__A=224		,						__A=14		,						__A="gelu"		,						__A=0.00_001		,						__A=0.0		,						__A=1E-10		,						__A=True		,						**__A		,						) ->     int:
								super().__init__(**__A				)

								_lowerCAmelCase										=hidden_size
								_lowerCAmelCase										=intermediate_size
								_lowerCAmelCase										=num_hidden_layers
								_lowerCAmelCase										=num_attention_heads
								_lowerCAmelCase										=patch_size
								_lowerCAmelCase										=image_size
								_lowerCAmelCase										=initializer_range
								_lowerCAmelCase										=attention_dropout
								_lowerCAmelCase										=layer_norm_eps
								_lowerCAmelCase										=hidden_act
								_lowerCAmelCase										=qkv_bias






		@classmethod
		def 		UpperCamelCase__       (   cls		,						__A		,						**__A				) ->     "PretrainedConfig":
								cls._set_token_in_kwargs(__A				)

								_lowerCAmelCase						,				_lowerCAmelCase										=cls.get_config_dict(__A		,						**__A				)

								# get the vision config dict if we are loading from Blip2Config
								if config_dict.get('model_type'				) == "blip-2":
														_lowerCAmelCase										=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(__A		,						**__A				)

class   SCREAMING_SNAKE_CASE			(						__lowercase):







		"""simple docstring"""
		lowercase   :      int       =							'blip_2_qformer'






		def __init__(   self		,						__A=3_0522		,						__A=768		,						__A=12		,						__A=12		,						__A=3072		,						__A="gelu"		,						__A=0.1		,						__A=0.1		,						__A=512		,						__A=0.02		,						__A=1E-12		,						__A=0		,						__A="absolute"		,						__A=2		,						__A=1408		,						**__A		,						) ->     List[str]:
								super().__init__(pad_token_id=__A		,						**__A				)

								_lowerCAmelCase										=vocab_size
								_lowerCAmelCase										=hidden_size
								_lowerCAmelCase										=num_hidden_layers
								_lowerCAmelCase										=num_attention_heads
								_lowerCAmelCase										=hidden_act
								_lowerCAmelCase										=intermediate_size
								_lowerCAmelCase										=hidden_dropout_prob
								_lowerCAmelCase										=attention_probs_dropout_prob
								_lowerCAmelCase										=max_position_embeddings
								_lowerCAmelCase										=initializer_range
								_lowerCAmelCase										=layer_norm_eps
								_lowerCAmelCase										=position_embedding_type
								_lowerCAmelCase										=cross_attention_frequency
								_lowerCAmelCase										=encoder_hidden_size






		@classmethod
		def 		UpperCamelCase__       (   cls		,						__A		,						**__A				) ->     "PretrainedConfig":
								cls._set_token_in_kwargs(__A				)

								_lowerCAmelCase						,				_lowerCAmelCase										=cls.get_config_dict(__A		,						**__A				)

								# get the qformer config dict if we are loading from Blip2Config
								if config_dict.get('model_type'				) == "blip-2":
														_lowerCAmelCase										=config_dict['qformer_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(__A		,						**__A				)

class   SCREAMING_SNAKE_CASE			(						__lowercase):







		"""simple docstring"""
		lowercase   :      Optional[int]       =							'blip-2'
		lowercase   :      Any       =							True






		def __init__(   self		,						__A=None		,						__A=None		,						__A=None		,						__A=32		,						**__A				) ->     int:
								super().__init__(**__A				)

								if vision_config is None:
														_lowerCAmelCase										={}
														logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.'				)

								if qformer_config is None:
														_lowerCAmelCase										={}
														logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.'				)

								if text_config is None:
														_lowerCAmelCase										={}
														logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).'				)

								_lowerCAmelCase										=BlipaVisionConfig(**__A				)
								_lowerCAmelCase										=BlipaQFormerConfig(**__A				)
								_lowerCAmelCase										=text_config['model_type'] if 'model_type' in text_config else 'opt'
								_lowerCAmelCase										=CONFIG_MAPPING[text_model_type](**__A				)

								_lowerCAmelCase										=self.text_config.tie_word_embeddings
								_lowerCAmelCase										=self.text_config.is_encoder_decoder

								_lowerCAmelCase										=num_query_tokens
								_lowerCAmelCase										=self.vision_config.hidden_size
								_lowerCAmelCase										=self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
								_lowerCAmelCase										=1.0
								_lowerCAmelCase										=0.02






		@classmethod
		def 		UpperCamelCase__       (   cls		,						__A		,						__A		,						__A		,						**__A		,						) ->     Any:
								return cls(
								    vision_config=vision_config.to_dict()		,						qformer_config=qformer_config.to_dict()		,						text_config=text_config.to_dict()		,						**__A		,						)






		def 		UpperCamelCase__       (   self				) ->     Tuple:
								_lowerCAmelCase										=copy.deepcopy(self.__dict__				)
								_lowerCAmelCase										=self.vision_config.to_dict()
								_lowerCAmelCase										=self.qformer_config.to_dict()
								_lowerCAmelCase										=self.text_config.to_dict()
								_lowerCAmelCase										=self.__class__.model_type
								return output





