




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

from ...utils import logging


UpperCAmelCase_		:					List[str]          =  logging.get_logger(__name__)




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase ):
				__magic_name__						:						Tuple										=nn.functional.normalize(lowerCamelCase )
				__magic_name__						:						Optional[int]										=nn.functional.normalize(lowerCamelCase )
				return torch.mm(lowerCamelCase						,  normalized_text_embeds.t() )




class 		__A   (      UpperCamelCase__      ):
						UpperCamelCase      =       CLIPConfig

						UpperCamelCase      =       ["""CLIPEncoderLayer"""]

						def __init__(		self :Any     ,			__snake_case :CLIPConfig			):
										'''simple docstring'''

										super().__init__(__snake_case			)

										__magic_name__						:						Optional[Any]										=CLIPVisionModel(config.vision_config			)
										__magic_name__						:						Any										=nn.Linear(config.vision_config.hidden_size     ,			config.projection_dim     ,			bias=__snake_case			)

										__magic_name__						:						List[Any]										=nn.Parameter(torch.ones(17     ,			config.projection_dim			)     ,			requires_grad=__snake_case			)
										__magic_name__						:						int										=nn.Parameter(torch.ones(3     ,			config.projection_dim			)     ,			requires_grad=__snake_case			)

										__magic_name__						:						List[str]										=nn.Parameter(torch.ones(17			)     ,			requires_grad=__snake_case			)
										__magic_name__						:						Tuple										=nn.Parameter(torch.ones(3			)     ,			requires_grad=__snake_case			)

						@torch.no_grad()
						def      A__    (		self :Optional[Any]     ,			__snake_case :List[Any]     ,			__snake_case :str			):
										'''simple docstring'''

										__magic_name__						:						Union[str, Any]										=self.vision_model(__snake_case			)[1]  # pooled_output
										__magic_name__						:						Tuple										=self.visual_projection(__snake_case			)

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

										__magic_name__						:						Dict										=[]
										__magic_name__						:						Any										=image_embeds.shape[0]
										for i in range(__snake_case			):
														__magic_name__						:						Optional[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
														__magic_name__						:						Dict										=0.0

														for concept_idx in range(len(special_cos_dist[0]			)			):
																		__magic_name__						:						Optional[Any]										=special_cos_dist[i][concept_idx]
																		__magic_name__						:						Any										=self.special_care_embeds_weights[concept_idx].item()
																		__magic_name__						:						Tuple										=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]}			)
																						__magic_name__						:						int										=0.01

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

														result.append(__snake_case			)

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

										return images, has_nsfw_concepts


						@torch.no_grad()
						def      A__    (		self :Tuple     ,			__snake_case :torch.FloatTensor     ,			__snake_case :torch.FloatTensor			):
										'''simple docstring'''

										__magic_name__						:						Dict										=self.vision_model(__snake_case			)[1]  # pooled_output
										__magic_name__						:						Union[str, Any]										=self.visual_projection(__snake_case			)

										__magic_name__						:						Optional[Any]										=cosine_distance(__snake_case     ,			self.special_care_embeds			)
										__magic_name__						:						str										=cosine_distance(__snake_case     ,			self.concept_embeds			)

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

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

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

										return images, has_nsfw_concepts








'''simple docstring'''






def lowerCamelCase__     (		__lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  Dict				       =''
   for ch in key:
      if ch == " " or ch not in key_no_dups and ch.isalpha():
         key_no_dups += ch
   return key_no_dups





def lowerCamelCase__     (		__lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  List[str]				       =[chr(i + 6_5				) for i in range(2_6				)]
   # Remove duplicate characters from key
   _UpperCAmelCase  :  Any				       =remove_duplicates(key.upper()				)
   _UpperCAmelCase  :  Optional[Any]				       =len(__lowerCamelCase				)
   # First fill cipher with key characters
   _UpperCAmelCase  :  List[Any]				       ={alphabet[i]: char for i, char in enumerate(__lowerCamelCase				)}
   # Then map remaining characters in alphabet to
   # the alphabet from the beginning
   for i in range(len(__lowerCamelCase				)			,       2_6				):
      _UpperCAmelCase  :  Union[str, Any]				       =alphabet[i - offset]
      # Ensure we are not mapping letters to letters previously mapped
      while char in key:
         offset -= 1
         _UpperCAmelCase  :  str				       =alphabet[i - offset]
      _UpperCAmelCase  :  Any				       =char
   return cipher_alphabet





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				dict[str, str]				):







   '''simple docstring'''




   return "".join(cipher_map.get(__lowerCamelCase			,       __lowerCamelCase				) for ch in message.upper()				)





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				dict[str, str]				):







   '''simple docstring'''




   _UpperCAmelCase  :  List[str]				       ={v: k for k, v in cipher_map.items()}
   return "".join(rev_cipher_map.get(__lowerCamelCase			,       __lowerCamelCase				) for ch in message.upper()				)





def lowerCamelCase__     (		):







   '''simple docstring'''




   _UpperCAmelCase  :  Union[str, Any]				       =input('Enter message to encode or decode: '				).strip()
   _UpperCAmelCase  :  int				       =input('Enter keyword: '				).strip()
   _UpperCAmelCase  :  int				       =input('Encipher or decipher? E/D:'				).strip()[0].lower()
   try:
      _UpperCAmelCase  :  Tuple				       ={'e': encipher, 'd': decipher}[option]
   except KeyError:
      raise KeyError('invalid input option'				)
   _UpperCAmelCase  :  List[str]				       =create_cipher_map(__lowerCamelCase				)
   print(func(__lowerCamelCase			,       __lowerCamelCase				)				)


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 main()

