


import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


snake_case       :					List[str]        =  logging.get_logger(__name__)
def        __lowerCamelCase		(      UpperCAmelCase_		:	Dict				,						UpperCAmelCase_		:	str		):




      """simple docstring"""





      a		:List[str]											= nn.functional.normalize(snake_case_		)
      a		:str											= nn.functional.normalize(snake_case_		)
      return torch.mm(snake_case_				,						normalized_text_embeds.t()		)







class 	_snake_case						(   UpperCamelCase_							):
 SCREAMING_SNAKE_CASE__   = CLIPConfig

 SCREAMING_SNAKE_CASE__   = ['CLIPEncoderLayer']




 def __init__(	self      ,						_lowerCamelCase					):
       super().__init__(__UpperCamelCase					)

       a		:Optional[int]											= CLIPVisionModel(config.vision_config					)
       a		:Union[str, Any]											= nn.Linear(config.vision_config.hidden_size      ,						config.projection_dim      ,						bias=__UpperCamelCase					)

       a		:int											= nn.Parameter(torch.ones(17      ,						config.projection_dim					)      ,						requires_grad=__UpperCamelCase					)
       a		:Dict											= nn.Parameter(torch.ones(3      ,						config.projection_dim					)      ,						requires_grad=__UpperCamelCase					)

       a		:Optional[Any]											= nn.Parameter(torch.ones(17					)      ,						requires_grad=__UpperCamelCase					)
       a		:Any											= nn.Parameter(torch.ones(3					)      ,						requires_grad=__UpperCamelCase					)




 @torch.no_grad()
 def  SCREAMING_SNAKE_CASE__       (	self      ,						_lowerCamelCase      ,						_lowerCamelCase					):
       a		:Union[str, Any]											= self.vision_model(__UpperCamelCase					)[1]  # pooled_output
       a		:Any											= self.visual_projection(__UpperCamelCase					)

       # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
       a		:Optional[Any]											= cosine_distance(__UpperCamelCase      ,						self.special_care_embeds					).cpu().float().numpy()
       a		:Any											= cosine_distance(__UpperCamelCase      ,						self.concept_embeds					).cpu().float().numpy()

       a		:Tuple											= []
       a		:List[str]											= image_embeds.shape[0]
       for i in range(__UpperCamelCase					):
             a		:List[Any]											= {'''special_scores''': {}, '''special_care''': [], '''concept_scores''': {}, '''bad_concepts''': []}

             # increase this value to create a stronger `nfsw` filter
             # at the cost of increasing the possibility of filtering benign images
             a		:Union[str, Any]											= 0.0

             for concept_idx in range(len(special_cos_dist[0]					)					):
                   a		:int											= special_cos_dist[i][concept_idx]
                   a		:int											= self.special_care_embeds_weights[concept_idx].item()
                   a		:int											= round(concept_cos - concept_threshold + adjustment      ,						3					)
                   if result_img["special_scores"][concept_idx] > 0:
                         result_img["special_care"].append({concept_idx, result_img['''special_scores'''][concept_idx]}					)
                         a		:Dict											= 0.01

             for concept_idx in range(len(cos_dist[0]					)					):
                   a		:Any											= cos_dist[i][concept_idx]
                   a		:Any											= self.concept_embeds_weights[concept_idx].item()
                   a		:Optional[int]											= round(concept_cos - concept_threshold + adjustment      ,						3					)
                   if result_img["concept_scores"][concept_idx] > 0:
                         result_img["bad_concepts"].append(__UpperCamelCase					)

             result.append(__UpperCamelCase					)

       a		:Optional[int]											= [len(res['''bad_concepts''']					) > 0 for res in result]

       for idx, has_nsfw_concept in enumerate(__UpperCamelCase					):
             if has_nsfw_concept:
                   if torch.is_tensor(__UpperCamelCase					) or torch.is_tensor(images[0]					):
                         a		:Optional[int]											= torch.zeros_like(images[idx]					)  # black image
                   else:
                         a		:Optional[int]											= np.zeros(images[idx].shape					)  # black image

       if any(__UpperCamelCase					):
             logger.warning(
                 '''Potential NSFW content was detected in one or more images. A black image will be returned instead.'''
                 ''' Try again with a different prompt and/or seed.'''					)

       return images, has_nsfw_concepts




 @torch.no_grad()
 def  SCREAMING_SNAKE_CASE__       (	self      ,						_lowerCamelCase      ,						_lowerCamelCase					):
       a		:Tuple											= self.vision_model(__UpperCamelCase					)[1]  # pooled_output
       a		:int											= self.visual_projection(__UpperCamelCase					)

       a		:List[str]											= cosine_distance(__UpperCamelCase      ,						self.special_care_embeds					)
       a		:Dict											= cosine_distance(__UpperCamelCase      ,						self.concept_embeds					)

       # increase this value to create a stronger `nsfw` filter
       # at the cost of increasing the possibility of filtering benign images
       a		:Union[str, Any]											= 0.0

       a		:List[str]											= special_cos_dist - self.special_care_embeds_weights + adjustment
       # special_scores = special_scores.round(decimals=3)
       a		:Dict											= torch.any(special_scores > 0      ,						dim=1					)
       a		:Optional[int]											= special_care * 0.01
       a		:List[Any]											= special_adjustment.unsqueeze(1					).expand(-1      ,						cos_dist.shape[1]					)

       a		:Optional[int]											= (cos_dist - self.concept_embeds_weights) + special_adjustment
       # concept_scores = concept_scores.round(decimals=3)
       a		:Any											= torch.any(concept_scores > 0      ,						dim=1					)

       a		:List[Any]											= 0.0  # black image

       return images, has_nsfw_concepts









import os
import sys

from . import rsa_key_generator as rkg

snake_case       :					int        =  1_28
snake_case       :					Any        =  2_56
def        __lowerCamelCase		(				UpperCAmelCase_		:	str				,						UpperCAmelCase_		:	int = DEFAULT_BLOCK_SIZE		):




      """simple docstring"""





      a		:Union[str, Any]											= message.encode('''ascii'''		)

      a		:List[Any]											= []
      for block_start in range(0				,						len(UpperCAmelCase_		)				,						UpperCAmelCase_		):
            a		:List[str]											= 0
            for i in range(UpperCAmelCase_				,						min(block_start + block_size				,						len(UpperCAmelCase_		)		)		):
                  block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
            block_ints.append(UpperCAmelCase_		)
      return block_ints
def        __lowerCamelCase		(				UpperCAmelCase_		:	list[int]				,						UpperCAmelCase_		:	int				,						UpperCAmelCase_		:	int = DEFAULT_BLOCK_SIZE		):




      """simple docstring"""





      a		:list[str]											= []
      for block_int in block_ints:
            a		:list[str]											= []
            for i in range(block_size - 1				,						-1				,						-1		):
                  if len(UpperCAmelCase_		) + i < message_length:
                        a		:List[str]											= block_int // (BYTE_SIZE**i)
                        a		:List[str]											= block_int % (BYTE_SIZE**i)
                        block_message.insert(0				,						chr(UpperCAmelCase_		)		)
            message.extend(UpperCAmelCase_		)
      return "".join(UpperCAmelCase_		)
def        __lowerCamelCase		(				UpperCAmelCase_		:	str				,						UpperCAmelCase_		:	tuple[int, int]				,						UpperCAmelCase_		:	int = DEFAULT_BLOCK_SIZE		):




      """simple docstring"""





      a		:Tuple											= []
      a							,       a		:Any											= key

      for block in get_blocks_from_text(UpperCAmelCase_				,						UpperCAmelCase_		):
            encrypted_blocks.append(pow(UpperCAmelCase_				,						UpperCAmelCase_				,						UpperCAmelCase_		)		)
      return encrypted_blocks
def        __lowerCamelCase		(				UpperCAmelCase_		:	list[int]				,						UpperCAmelCase_		:	int				,						UpperCAmelCase_		:	tuple[int, int]				,						UpperCAmelCase_		:	int = DEFAULT_BLOCK_SIZE				,						):




      """simple docstring"""





      a		:Optional[Any]											= []
      a							,       a		:int											= key
      for block in encrypted_blocks:
            decrypted_blocks.append(pow(UpperCAmelCase_				,						UpperCAmelCase_				,						UpperCAmelCase_		)		)
      return get_text_from_blocks(UpperCAmelCase_				,						UpperCAmelCase_				,						UpperCAmelCase_		)
def        __lowerCamelCase		(				UpperCAmelCase_		:	str		):




      """simple docstring"""





      with open(UpperCAmelCase_		) as fo:
            a		:Dict											= fo.read()
      a							,       a							,       a		:Tuple											= content.split(''','''		)
      return (int(UpperCAmelCase_		), int(UpperCAmelCase_		), int(UpperCAmelCase_		))
def        __lowerCamelCase		(				UpperCAmelCase_		:	str				,						UpperCAmelCase_		:	str				,						UpperCAmelCase_		:	str				,						UpperCAmelCase_		:	int = DEFAULT_BLOCK_SIZE				,						):




      """simple docstring"""





      a							,       a							,       a		:List[str]											= read_key_file(UpperCAmelCase_		)
      if key_size < block_size * 8:
            sys.exit(
                '''ERROR: Block size is {} bits and key size is {} bits. The RSA cipher '''
                '''requires the block size to be equal to or greater than the key size. '''
                '''Either decrease the block size or use different keys.'''.format(
                    block_size * 8				,						UpperCAmelCase_		)		)

      a		:int											= [str(UpperCAmelCase_		) for i in encrypt_message(UpperCAmelCase_				,						(n, e)				,						UpperCAmelCase_		)]

      a		:str											= ''','''.join(UpperCAmelCase_		)
      a		:Optional[Any]											= F'''{len(UpperCAmelCase_		)}_{block_size}_{encrypted_content}'''
      with open(UpperCAmelCase_				,						'''w'''		) as fo:
            fo.write(UpperCAmelCase_		)
      return encrypted_content
def        __lowerCamelCase		(				UpperCAmelCase_		:	str				,						UpperCAmelCase_		:	str		):




      """simple docstring"""





      a							,       a							,       a		:List[Any]											= read_key_file(UpperCAmelCase_		)
      with open(UpperCAmelCase_		) as fo:
            a		:int											= fo.read()
      a							,       a							,       a		:List[str]											= content.split('''_'''		)
      a		:List[str]											= int(UpperCAmelCase_		)
      a		:List[str]											= int(UpperCAmelCase_		)

      if key_size < block_size * 8:
            sys.exit(
                '''ERROR: Block size is {} bits and key size is {} bits. The RSA cipher '''
                '''requires the block size to be equal to or greater than the key size. '''
                '''Did you specify the correct key file and encrypted file?'''.format(
                    block_size * 8				,						UpperCAmelCase_		)		)

      a		:Dict											= []
      for block in encrypted_message.split(''','''		):
            encrypted_blocks.append(int(UpperCAmelCase_		)		)

      return decrypt_message(UpperCAmelCase_				,						UpperCAmelCase_				,						(n, d)				,						UpperCAmelCase_		)
def        __lowerCamelCase		(				):




      """simple docstring"""





      a		:Union[str, Any]											= '''encrypted_file.txt'''
      a		:List[Any]											= input(R'''Encrypt\Decrypt [e\d]: '''		)

      if response.lower().startswith('''e'''		):
            a		:int											= '''encrypt'''
      elif response.lower().startswith('''d'''		):
            a		:Optional[Any]											= '''decrypt'''

      if mode == "encrypt":
            if not os.path.exists('''rsa_pubkey.txt'''		):
                  rkg.make_key_files('''rsa'''				,						1024		)

            a		:List[str]											= input('''\nEnter message: '''		)
            a		:str											= '''rsa_pubkey.txt'''
            print(F'''Encrypting and writing to {filename}...'''		)
            a		:Optional[int]											= encrypt_and_write_to_file(UpperCAmelCase_				,						UpperCAmelCase_				,						UpperCAmelCase_		)

            print('''\nEncrypted text:'''		)
            print(UpperCAmelCase_		)

      elif mode == "decrypt":
            a		:str											= '''rsa_privkey.txt'''
            print(F'''Reading from {filename} and decrypting...'''		)
            a		:Optional[int]											= read_from_file_and_decrypt(UpperCAmelCase_				,						UpperCAmelCase_		)
            print('''writing decryption to rsa_decryption.txt...'''		)
            with open('''rsa_decryption.txt'''				,						'''w'''		) as dec:
                  dec.write(UpperCAmelCase_		)

            print('''\nDecryption:'''		)
            print(UpperCAmelCase_		)


if __name__ == "__main__":
     main()





