


"""simple docstring"""




import copy
import os
from typing import Union

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


__magic_name__						: Any    =				logging.get_logger(__name__)

__magic_name__						: Any    =				{
    '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 			__snake_case   (lowerCamelCase  ):
							__a					 =       'bridgetower_vision_model'




							def __init__(     self:    Optional[int]     ,							A_:    str=7_68     ,							A_:    Optional[Any]=12     ,							A_:    str=3     ,							A_:    Union[str, Any]=16     ,							A_:    Optional[int]=2_88     ,							A_:    Optional[int]=1     ,							A_:    Tuple=1E-05     ,							A_:    Optional[Any]=False     ,							A_:    List[str]=True     ,							A_:    int=False     ,							**A_:    int     ,							):
										super().__init__(**SCREAMING_SNAKE_CASE_   )
										__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   __a   (     cls:    Any     ,							A_:    Union[str, os.PathLike]     ,							**A_:    List[Any]   ):
										__lowerCamelCase     ,__lowerCamelCase          =      cls.get_config_dict(SCREAMING_SNAKE_CASE_     ,							**SCREAMING_SNAKE_CASE_   )

										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(SCREAMING_SNAKE_CASE_     ,							**SCREAMING_SNAKE_CASE_   )




class 			__snake_case   (lowerCamelCase  ):
							__a					 =       'bridgetower_text_model'




							def __init__(     self:    Any     ,							A_:    List[str]=5_02_65     ,							A_:    List[Any]=7_68     ,							A_:    Any=12     ,							A_:    Dict=12     ,							A_:    Optional[Any]=1     ,							A_:    Union[str, Any]=30_72     ,							A_:    Tuple="gelu"     ,							A_:    Tuple=0.1     ,							A_:    Optional[Any]=0.1     ,							A_:    Tuple=5_14     ,							A_:    List[str]=1     ,							A_:    Optional[Any]=1E-05     ,							A_:    Optional[Any]=1     ,							A_:    Dict=0     ,							A_:    Union[str, Any]=2     ,							A_:    Optional[int]="absolute"     ,							A_:    Tuple=True     ,							**A_:    Optional[int]     ,							):
										super().__init__(**SCREAMING_SNAKE_CASE_   )

										__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   __a   (     cls:    Optional[Any]     ,							A_:    Union[str, os.PathLike]     ,							**A_:    Any   ):
										__lowerCamelCase     ,__lowerCamelCase          =      cls.get_config_dict(SCREAMING_SNAKE_CASE_     ,							**SCREAMING_SNAKE_CASE_   )

										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(SCREAMING_SNAKE_CASE_     ,							**SCREAMING_SNAKE_CASE_   )




class 			__snake_case   (lowerCamelCase  ):
							__a					 =       'bridgetower'




							def __init__(     self:    Dict     ,							A_:    str=True     ,							A_:    Tuple="gelu"     ,							A_:    int=7_68     ,							A_:    Any=1     ,							A_:    Any=1E-05     ,							A_:    List[Any]=False     ,							A_:    Any="add"     ,							A_:    List[Any]=12     ,							A_:    List[Any]=6     ,							A_:    Union[str, Any]=False     ,							A_:    List[Any]=False     ,							A_:    Union[str, Any]=None     ,							A_:    str=None     ,							**A_:    Dict     ,							):
										# TODO: remove this once the Hub files are updated.
										__lowerCamelCase          =      kwargs.pop("""text_config_dict"""     ,							SCREAMING_SNAKE_CASE_   )
										__lowerCamelCase          =      kwargs.pop("""vision_config_dict"""     ,							SCREAMING_SNAKE_CASE_   )

										super().__init__(**SCREAMING_SNAKE_CASE_   )
										__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(**SCREAMING_SNAKE_CASE_   )
										__lowerCamelCase          =      BridgeTowerVisionConfig(**SCREAMING_SNAKE_CASE_   )




							@classmethod
							def   __a   (     cls:    str     ,							A_:    BridgeTowerTextConfig     ,							A_:    BridgeTowerVisionConfig     ,							**A_:    Optional[int]   ):
										return cls(text_config=text_config.to_dict()     ,							vision_config=vision_config.to_dict()     ,							**SCREAMING_SNAKE_CASE_   )




							def   __a   (     self:    Optional[int]   ):
										__lowerCamelCase          =      copy.deepcopy(self.__dict__   )
										__lowerCamelCase          =      self.text_config.to_dict()
										__lowerCamelCase          =      self.vision_config.to_dict()
										__lowerCamelCase          =      self.__class__.model_type
										return output






__a         =   'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'




def 							a		(				snake_case__:   bytes   ):


				'''simple docstring'''
				# Make sure the supplied data is a bytes-like object
				if not isinstance(snake_case__		,  snake_case__   ):
								lowercase_	    =   F'''a bytes-like object is required, not \'{data.__class__.__name__}\''''
								raise TypeError(snake_case__   )

				lowercase_	    =   ''''''.join(bin(snake_case__   )[2:].zfill(8   ) for byte in data   )

				lowercase_	    =   len(snake_case__   ) % 6 != 0

				if padding_needed:
								# The padding that will be added later
								lowercase_	    =   B'''=''' * ((6 - len(snake_case__   ) % 6) // 2)

								# Append binary_stream with arbitrary binary digits (0's by default) to make its
								# length a multiple of 6.
								binary_stream += "0" * (6 - len(snake_case__   ) % 6)
				else:
								lowercase_	    =   B''''''

				# Encode every 6 binary digits to their corresponding Base64 character
				return (
				    "".join(
				        B64_CHARSET[int(binary_stream[index : index + 6]		,  2   )]
				        for index in range(0		,  len(snake_case__   )		,  6   )   ).encode()
				    + padding
				)




def 							a		(				snake_case__:   str   ):


				'''simple docstring'''
				# Make sure encoded_data is either a string or a bytes-like object
				if not isinstance(snake_case__		,  snake_case__   ) and not isinstance(snake_case__		,  snake_case__   ):
								lowercase_	    =   (
								    '''argument should be a bytes-like object or ASCII string, '''
								    F'''not \'{encoded_data.__class__.__name__}\''''
								)
								raise TypeError(snake_case__   )

				# In case encoded_data is a bytes-like object, make sure it contains only
				# ASCII characters so we convert it to a string object
				if isinstance(snake_case__		,  snake_case__   ):
								try:
												lowercase_	    =   encoded_data.decode('''utf-8'''   )
								except UnicodeDecodeError:
												raise ValueError('''base64 encoded data should only contain ASCII characters'''   )

				lowercase_	    =   encoded_data.count('''='''   )

				# Check if the encoded string contains non base64 characters
				if padding:
								assert all(
								    char in B64_CHARSET for char in encoded_data[:-padding]   ), "Invalid base64 character(s) found."
				else:
								assert all(
								    char in B64_CHARSET for char in encoded_data   ), "Invalid base64 character(s) found."

				# Check the padding
				assert len(snake_case__   ) % 4 == 0 and padding < 3, "Incorrect padding"

				if padding:
								# Remove padding if there is one
								lowercase_	    =   encoded_data[:-padding]

								lowercase_	    =   ''''''.join(
								    bin(B64_CHARSET.index(snake_case__   )   )[2:].zfill(6   ) for char in encoded_data   )[: -padding * 2]
				else:
								lowercase_	    =   ''''''.join(
								    bin(B64_CHARSET.index(snake_case__   )   )[2:].zfill(6   ) for char in encoded_data   )

				lowercase_	    =   [
				    int(binary_stream[index : index + 8]		,  2   )
				    for index in range(0		,  len(snake_case__   )		,  8   )
				]

				return bytes(snake_case__   )


if __name__ == "__main__":
						import doctest

						doctest.testmod()




