






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


UpperCamelCase 				=	logging.get_logger(__name__)

UpperCamelCase 				=	{
    '''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''',
}



class       __UpperCAmelCase		(lowerCamelCase_    ):
			__snake_case				:      Union[str, Any] 						=							'''instructblip_vision_model'''







			def __init__(	self:  Optional[int]      ,	UpperCAmelCase_:  List[Any]=1_408      ,	UpperCAmelCase_:  int=6_144      ,	UpperCAmelCase_:  List[Any]=39      ,	UpperCAmelCase_:  Optional[int]=16      ,	UpperCAmelCase_:  List[str]=224      ,	UpperCAmelCase_:  List[Any]=14      ,	UpperCAmelCase_:  Tuple="gelu"      ,	UpperCAmelCase_:  int=1E-6      ,	UpperCAmelCase_:  Dict=0.0      ,	UpperCAmelCase_:  Tuple=1E-10      ,	UpperCAmelCase_:  Any=True      ,	**UpperCAmelCase_:  Any      ,	):







									'''simple docstring'''




									super().__init__(**__snake_case     )

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







			@classmethod
			def 							UpperCamelCase      (	cls:  Optional[Any]      ,	UpperCAmelCase_:  Union[str, os.PathLike]      ,	**UpperCAmelCase_:  Any     ):







									'''simple docstring'''




									cls._set_token_in_kwargs(__snake_case     )

									_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE	      =  cls.get_config_dict(__snake_case      ,	**__snake_case     )

									# get the vision config dict if we are loading from InstructBlipConfig
									if config_dict.get("""model_type"""     ) == "instructblip":
															_SCREAMING_SNAKE_CASE	      =  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(__snake_case      ,	**__snake_case     )



class       __UpperCAmelCase		(lowerCamelCase_    ):
			__snake_case				:      Optional[int] 						=							'''instructblip_qformer'''







			def __init__(	self:  Optional[int]      ,	UpperCAmelCase_:  Union[str, Any]=30_522      ,	UpperCAmelCase_:  int=768      ,	UpperCAmelCase_:  List[str]=12      ,	UpperCAmelCase_:  Optional[Any]=12      ,	UpperCAmelCase_:  Tuple=3_072      ,	UpperCAmelCase_:  Any="gelu"      ,	UpperCAmelCase_:  Optional[Any]=0.1      ,	UpperCAmelCase_:  Dict=0.1      ,	UpperCAmelCase_:  Dict=512      ,	UpperCAmelCase_:  Optional[int]=0.02      ,	UpperCAmelCase_:  str=1E-12      ,	UpperCAmelCase_:  List[str]=0      ,	UpperCAmelCase_:  Union[str, Any]="absolute"      ,	UpperCAmelCase_:  Optional[Any]=2      ,	UpperCAmelCase_:  Tuple=1_408      ,	**UpperCAmelCase_:  str      ,	):







									'''simple docstring'''




									super().__init__(pad_token_id=__snake_case      ,	**__snake_case     )

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







			@classmethod
			def 							UpperCamelCase      (	cls:  Optional[Any]      ,	UpperCAmelCase_:  Union[str, os.PathLike]      ,	**UpperCAmelCase_:  Union[str, Any]     ):







									'''simple docstring'''




									cls._set_token_in_kwargs(__snake_case     )

									_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE	      =  cls.get_config_dict(__snake_case      ,	**__snake_case     )

									# get the qformer config dict if we are loading from InstructBlipConfig
									if config_dict.get("""model_type"""     ) == "instructblip":
															_SCREAMING_SNAKE_CASE	      =  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(__snake_case      ,	**__snake_case     )



class       __UpperCAmelCase		(lowerCamelCase_    ):
			__snake_case				:      Optional[int] 						=							'''instructblip'''
			__snake_case				:      Any 						=							True







			def __init__(	self:  Any      ,	UpperCAmelCase_:  Optional[int]=None      ,	UpperCAmelCase_:  Optional[int]=None      ,	UpperCAmelCase_:  Optional[Any]=None      ,	UpperCAmelCase_:  Any=32      ,	**UpperCAmelCase_:  str     ):







									'''simple docstring'''




									super().__init__(**__snake_case     )

									if vision_config is None:
															_SCREAMING_SNAKE_CASE	      =  {}
															logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values."""     )

									if qformer_config is None:
															_SCREAMING_SNAKE_CASE	      =  {}
															logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values."""     )

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

									_SCREAMING_SNAKE_CASE	      =  InstructBlipVisionConfig(**__snake_case     )
									_SCREAMING_SNAKE_CASE	      =  InstructBlipQFormerConfig(**__snake_case     )
									_SCREAMING_SNAKE_CASE	      =  text_config["""model_type"""] if """model_type""" in text_config else """opt"""
									_SCREAMING_SNAKE_CASE	      =  CONFIG_MAPPING[text_model_type](**__snake_case     )

									_SCREAMING_SNAKE_CASE	      =  self.text_config.tie_word_embeddings
									_SCREAMING_SNAKE_CASE	      =  self.text_config.is_encoder_decoder

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







			@classmethod
			def 							UpperCamelCase      (	cls:  Union[str, Any]      ,	UpperCAmelCase_:  InstructBlipVisionConfig      ,	UpperCAmelCase_:  InstructBlipQFormerConfig      ,	UpperCAmelCase_:  PretrainedConfig      ,	**UpperCAmelCase_:  Optional[Any]      ,	):







									'''simple docstring'''




									return cls(
									    vision_config=vision_config.to_dict()      ,	qformer_config=qformer_config.to_dict()      ,	text_config=text_config.to_dict()      ,	**__snake_case      ,	)







			def 							UpperCamelCase      (	self:  Optional[Any]     ):







									'''simple docstring'''




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





import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812






def 							__lowercase   ( ):
							print('Making key files...'   )
							make_key_files('rsa'					,    1_0_2_4   )
							print('Key files generation successful.'   )






def 							__lowercase   ( __lowerCAmelCase							:				int   ):
							print('Generating prime p...'   )
							a__             =     rabinMiller.generate_large_prime(__lowerCAmelCase   )
							print('Generating prime q...'   )
							a__             =     rabinMiller.generate_large_prime(__lowerCAmelCase   )
							a__             =     p * q

							print('Generating e that is relatively prime to (p - 1) * (q - 1)...'   )
							while True:
														a__             =     random.randrange(2 ** (key_size - 1)					,    2 ** (key_size)   )
														if cryptoMath.gcd(__lowerCAmelCase					,    (p - 1) * (q - 1)   ) == 1:
																					break

							print('Calculating d that is mod inverse of e...'   )
							a__             =     cryptoMath.find_mod_inverse(__lowerCAmelCase					,    (p - 1) * (q - 1)   )

							a__             =     (n, e)
							a__             =     (n, d)
							return (public_key, private_key)






def 							__lowercase   ( __lowerCAmelCase							:				str					,    __lowerCAmelCase							:				int   ):
							if os.path.exists(F'{name}_pubkey.txt'   ) or os.path.exists(F'{name}_privkey.txt'   ):
														print('\nWARNING:'   )
														print(
														    F'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'
														    'Use a different name or delete these files and re-run this program.'   )
														sys.exit()

							a__      ,					a__             =     generate_key(__lowerCAmelCase   )
							print(F'\nWriting public key to file {name}_pubkey.txt...'   )
							with open(F'{name}_pubkey.txt'					,    'w'   ) as out_file:
														out_file.write(F'{key_size},{public_key[0]},{public_key[1]}'   )

							print(F'Writing private key to file {name}_privkey.txt...'   )
							with open(F'{name}_privkey.txt'					,    'w'   ) as out_file:
														out_file.write(F'{key_size},{private_key[0]},{private_key[1]}'   )


if __name__ == "__main__":
						main()




