
"""simple docstring"""



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_snake_case          =						logging.get_logger(__name__)

_snake_case          =						{
    '''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json''',
    '''BridgeTower/bridgetower-base-itm-mlm''': (
        '''https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json'''
    ),
}
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Tuple							=					"bridgetower_vision_model"


				def __init__(					self	:			List[str]				,     UpperCAmelCase_	:			int=768				,     UpperCAmelCase_	:			Optional[Any]=12				,     UpperCAmelCase_	:			int=3				,     UpperCAmelCase_	:			Dict=16				,     UpperCAmelCase_	:			Optional[Any]=288				,     UpperCAmelCase_	:			int=1				,     UpperCAmelCase_	:			Tuple=1E-0_5				,     UpperCAmelCase_	:			int=False				,     UpperCAmelCase_	:			Tuple=True				,     UpperCAmelCase_	:			Dict=False				,     **UpperCAmelCase_	:			List[Any]				,     )		->  int:







											"""simple docstring"""




											super().__init__(**UpperCAmelCase_  )
											_lowerCAmelCase  	=			hidden_size
											_lowerCAmelCase  	=			num_hidden_layers
											_lowerCAmelCase  	=			num_channels
											_lowerCAmelCase  	=			patch_size
											_lowerCAmelCase  	=			image_size
											_lowerCAmelCase  	=			initializer_factor
											_lowerCAmelCase  	=			layer_norm_eps
											_lowerCAmelCase  	=			stop_gradient
											_lowerCAmelCase  	=			share_layernorm
											_lowerCAmelCase  	=			remove_last_layer







				@classmethod
				def 				__lowerCamelCase	(					cls	:			Tuple				,     UpperCAmelCase_	:			Union[str, os.PathLike]				,     **UpperCAmelCase_	:			Optional[Any]  )		->  "PretrainedConfig":







											"""simple docstring"""




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

											if config_dict.get('model_type'  ) == "bridgetower":
																		_lowerCAmelCase  	=			config_dict['text_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(UpperCAmelCase_				,     **UpperCAmelCase_  )






class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Tuple							=					"bridgetower_text_model"


				def __init__(					self	:			str				,     UpperCAmelCase_	:			Optional[Any]=50_265				,     UpperCAmelCase_	:			Dict=768				,     UpperCAmelCase_	:			Optional[Any]=12				,     UpperCAmelCase_	:			Dict=12				,     UpperCAmelCase_	:			Tuple=1				,     UpperCAmelCase_	:			str=3_072				,     UpperCAmelCase_	:			Tuple="gelu"				,     UpperCAmelCase_	:			Optional[Any]=0.1				,     UpperCAmelCase_	:			List[Any]=0.1				,     UpperCAmelCase_	:			str=514				,     UpperCAmelCase_	:			List[str]=1				,     UpperCAmelCase_	:			Optional[int]=1E-0_5				,     UpperCAmelCase_	:			Optional[int]=1				,     UpperCAmelCase_	:			List[str]=0				,     UpperCAmelCase_	:			List[str]=2				,     UpperCAmelCase_	:			Dict="absolute"				,     UpperCAmelCase_	:			int=True				,     **UpperCAmelCase_	:			Tuple				,     )		->  Optional[int]:







											"""simple docstring"""




											super().__init__(**UpperCAmelCase_  )

											_lowerCAmelCase  	=			vocab_size
											_lowerCAmelCase  	=			hidden_size
											_lowerCAmelCase  	=			num_hidden_layers
											_lowerCAmelCase  	=			num_attention_heads
											_lowerCAmelCase  	=			hidden_act
											_lowerCAmelCase  	=			initializer_factor
											_lowerCAmelCase  	=			intermediate_size
											_lowerCAmelCase  	=			hidden_dropout_prob
											_lowerCAmelCase  	=			attention_probs_dropout_prob
											_lowerCAmelCase  	=			max_position_embeddings
											_lowerCAmelCase  	=			type_vocab_size
											_lowerCAmelCase  	=			layer_norm_eps
											_lowerCAmelCase  	=			position_embedding_type
											_lowerCAmelCase  	=			use_cache
											_lowerCAmelCase  	=			pad_token_id
											_lowerCAmelCase  	=			bos_token_id
											_lowerCAmelCase  	=			eos_token_id







				@classmethod
				def 				__lowerCamelCase	(					cls	:			Union[str, Any]				,     UpperCAmelCase_	:			Union[str, os.PathLike]				,     **UpperCAmelCase_	:			List[str]  )		->  "PretrainedConfig":







											"""simple docstring"""




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

											if config_dict.get('model_type'  ) == "bridgetower":
																		_lowerCAmelCase  	=			config_dict['text_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(UpperCAmelCase_				,     **UpperCAmelCase_  )






class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Union[str, Any]							=					"bridgetower"


				def __init__(					self	:			Tuple				,     UpperCAmelCase_	:			Tuple=True				,     UpperCAmelCase_	:			Tuple="gelu"				,     UpperCAmelCase_	:			Union[str, Any]=768				,     UpperCAmelCase_	:			List[str]=1				,     UpperCAmelCase_	:			List[str]=1E-0_5				,     UpperCAmelCase_	:			Optional[Any]=False				,     UpperCAmelCase_	:			Optional[int]="add"				,     UpperCAmelCase_	:			List[Any]=12				,     UpperCAmelCase_	:			Any=6				,     UpperCAmelCase_	:			int=False				,     UpperCAmelCase_	:			str=False				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			List[str]=None				,     **UpperCAmelCase_	:			List[Any]				,     )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			kwargs.pop('text_config_dict'				,     UpperCAmelCase_  )
											_lowerCAmelCase  	=			kwargs.pop('vision_config_dict'				,     UpperCAmelCase_  )

											super().__init__(**UpperCAmelCase_  )
											_lowerCAmelCase  	=			share_cross_modal_transformer_layers
											_lowerCAmelCase  	=			hidden_act
											_lowerCAmelCase  	=			hidden_size
											_lowerCAmelCase  	=			initializer_factor
											_lowerCAmelCase  	=			layer_norm_eps
											_lowerCAmelCase  	=			share_link_tower_layers
											_lowerCAmelCase  	=			link_tower_type
											_lowerCAmelCase  	=			num_attention_heads
											_lowerCAmelCase  	=			num_hidden_layers
											_lowerCAmelCase  	=			tie_word_embeddings
											_lowerCAmelCase  	=			init_layernorm_from_vision_encoder

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

											if vision_config is None:
																		_lowerCAmelCase  	=			{}
																		logger.info('`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.'  )

											_lowerCAmelCase  	=			BridgeTowerTextConfig(**UpperCAmelCase_  )
											_lowerCAmelCase  	=			BridgeTowerVisionConfig(**UpperCAmelCase_  )


				@classmethod
				def 				__lowerCamelCase	(					cls	:			List[Any]				,     UpperCAmelCase_	:			BridgeTowerTextConfig				,     UpperCAmelCase_	:			BridgeTowerVisionConfig				,     **UpperCAmelCase_	:			List[Any]  )		->  List[str]:







											"""simple docstring"""




											return cls(text_config=text_config.to_dict()				,     vision_config=vision_config.to_dict()				,     **UpperCAmelCase_  )







				def 				__lowerCamelCase	(					self	:			Optional[Any]  )		->  List[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			copy.deepcopy(self.__dict__  )
											_lowerCAmelCase  	=			self.text_config.to_dict()
											_lowerCAmelCase  	=			self.vision_config.to_dict()
											_lowerCAmelCase  	=			self.__class__.model_type
											return output








"""simple docstring"""



import unittest

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


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import ChineseCLIPImageProcessor
class        _SCREAMING_SNAKE_CASE  (  unittest.TestCase							):






				'''simple docstring'''



				def __init__(					self	:			Optional[Any]				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			Dict=7				,     UpperCAmelCase_	:			List[Any]=3				,     UpperCAmelCase_	:			Tuple=18				,     UpperCAmelCase_	:			List[str]=30				,     UpperCAmelCase_	:			Union[str, Any]=400				,     UpperCAmelCase_	:			Optional[Any]=True				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Optional[int]=True				,     UpperCAmelCase_	:			Any=None				,     UpperCAmelCase_	:			Tuple=True				,     UpperCAmelCase_	:			List[Any]=[0.48145466, 0.4578275, 0.40821073]				,     UpperCAmelCase_	:			List[Any]=[0.26862954, 0.26130258, 0.27577711]				,     UpperCAmelCase_	:			Optional[int]=True				,     )		->  Tuple:







											"""simple docstring"""




											_lowerCAmelCase  	=			size if size is not None else {'height': 224, 'width': 224}
											_lowerCAmelCase  	=			crop_size if crop_size is not None else {'height': 18, 'width': 18}
											_lowerCAmelCase  	=			parent
											_lowerCAmelCase  	=			batch_size
											_lowerCAmelCase  	=			num_channels
											_lowerCAmelCase  	=			image_size
											_lowerCAmelCase  	=			min_resolution
											_lowerCAmelCase  	=			max_resolution
											_lowerCAmelCase  	=			do_resize
											_lowerCAmelCase  	=			size
											_lowerCAmelCase  	=			do_center_crop
											_lowerCAmelCase  	=			crop_size
											_lowerCAmelCase  	=			do_normalize
											_lowerCAmelCase  	=			image_mean
											_lowerCAmelCase  	=			image_std
											_lowerCAmelCase  	=			do_convert_rgb


				def 				__lowerCamelCase	(					self	:			Optional[int]  )		->  int:







											"""simple docstring"""




											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_convert_rgb": self.do_convert_rgb,
											}







				def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			Dict=False				,     UpperCAmelCase_	:			int=False				,     UpperCAmelCase_	:			Dict=False  )		->  str:







											"""simple docstring"""




											assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

											if equal_resolution:
																		_lowerCAmelCase  	=			[]
																		for i in range(self.batch_size  ):
																									image_inputs.append(
																									    np.random.randint(
																									        255				,     size=(self.num_channels, self.max_resolution, self.max_resolution)				,     dtype=np.uinta  )  )
											else:
																		_lowerCAmelCase  	=			[]
																		for i in range(self.batch_size  ):
																									_lowerCAmelCase	,		_lowerCAmelCase  	=			np.random.choice(np.arange(self.min_resolution				,     self.max_resolution  )				,     2  )
																									image_inputs.append(np.random.randint(255				,     size=(self.num_channels, width, height)				,     dtype=np.uinta  )  )

											if not numpify and not torchify:
																		# PIL expects the channel dimension as last dimension
																		_lowerCAmelCase  	=			[Image.fromarray(np.moveaxis(UpperCAmelCase_				,     0				,     -1  )  ) for x in image_inputs]

											if torchify:
																		_lowerCAmelCase  	=			[torch.from_numpy(UpperCAmelCase_  ) for x in image_inputs]

											return image_inputs






@require_torch
@require_vision
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							List[Any]							=					ChineseCLIPImageProcessor if is_vision_available() else None


				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			ChineseCLIPImageProcessingTester(self				,     do_center_crop=UpperCAmelCase_  )


				@property
				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  int:







											"""simple docstring"""




											return self.image_processor_tester.prepare_image_processor_dict()


				def 				__lowerCamelCase	(					self	:			List[str]  )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_resize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'size'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_normalize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_mean'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_std'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_convert_rgb'  )  )


				def 				__lowerCamelCase	(					self	:			Dict  )		->  Tuple:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class.from_dict(self.image_processor_dict  )
											self.assertEqual(image_processor.size				,     {'height': 224, 'width': 224}  )
											self.assertEqual(image_processor.crop_size				,     {'height': 18, 'width': 18}  )

											_lowerCAmelCase  	=			self.image_processing_class.from_dict(self.image_processor_dict				,     size=42				,     crop_size=84  )
											self.assertEqual(image_processor.size				,     {'shortest_edge': 42}  )
											self.assertEqual(image_processor.crop_size				,     {'height': 84, 'width': 84}  )


				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  List[str]:







											"""simple docstring"""




											pass


				def 				__lowerCamelCase	(					self	:			Optional[Any]  )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random PIL images
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     Image.Image  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )


				def 				__lowerCamelCase	(					self	:			List[str]  )		->  int:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random numpy tensors
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_				,     numpify=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     np.ndarray  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )







				def 				__lowerCamelCase	(					self	:			List[Any]  )		->  Dict:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random PyTorch tensors
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_				,     torchify=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     torch.Tensor  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )






@require_torch
@require_vision
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							str							=					ChineseCLIPImageProcessor if is_vision_available() else None


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







											"""simple docstring"""




											_lowerCAmelCase  	=			ChineseCLIPImageProcessingTester(self				,     num_channels=4				,     do_center_crop=UpperCAmelCase_  )
											_lowerCAmelCase  	=			3


				@property
				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  Dict:







											"""simple docstring"""




											return self.image_processor_tester.prepare_image_processor_dict()


				def 				__lowerCamelCase	(					self	:			Optional[Any]  )		->  Dict:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_resize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'size'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_normalize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_mean'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_std'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_convert_rgb'  )  )


				def 				__lowerCamelCase	(					self	:			List[Any]  )		->  Optional[int]:







											"""simple docstring"""




											pass







				def 				__lowerCamelCase	(					self	:			int  )		->  List[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random PIL images
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     Image.Image  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.expected_encoded_image_num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.expected_encoded_image_num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )






