

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

from ...utils import logging


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







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						SCREAMING_SNAKE_CASE_: Optional[Any]  		=       nn.functional.normalize(_UpperCAmelCase    )
						SCREAMING_SNAKE_CASE_: List[Any]  		=       nn.functional.normalize(_UpperCAmelCase    )
						return torch.mm(_UpperCAmelCase				,	normalized_text_embeds.t()    )



class   __lowercase				( UpperCAmelCase_	):




			"""simple docstring"""







			_UpperCAmelCase   :							str										=     CLIPConfig

			_UpperCAmelCase   :							Optional[int]										=     ['''CLIPEncoderLayer''']



			def __init__( self  :     List[Any]   ,						lowerCAmelCase__  :     CLIPConfig):
									super().__init__(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       CLIPVisionModel(config.vision_config)
									SCREAMING_SNAKE_CASE_: List[str]  		=       nn.Linear(config.vision_config.hidden_size   ,						config.projection_dim   ,						bias=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       nn.Parameter(torch.ones(17   ,						config.projection_dim)   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       nn.Parameter(torch.ones(3   ,						config.projection_dim)   ,						requires_grad=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       nn.Parameter(torch.ones(17)   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Tuple  		=       nn.Parameter(torch.ones(3)   ,						requires_grad=lowerCAmelCase__)



			@torch.no_grad()
			def        _SCREAMING_SNAKE_CASE			( self  :     int   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.visual_projection(lowerCAmelCase__)

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

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       []
									SCREAMING_SNAKE_CASE_: List[Any]  		=       image_embeds.shape[0]
									for i in range(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_: Dict  		=       {"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
															SCREAMING_SNAKE_CASE_: List[Any]  		=       0.0

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

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

															result.append(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Tuple  		=       [len(res["bad_concepts"]) > 0 for res in result]

									return images, has_nsfw_concepts




			@torch.no_grad()
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]   ,						lowerCAmelCase__  :     torch.FloatTensor   ,						lowerCAmelCase__  :     torch.FloatTensor):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.visual_projection(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Any  		=       cosine_distance(lowerCAmelCase__   ,						self.special_care_embeds)
									SCREAMING_SNAKE_CASE_: str  		=       cosine_distance(lowerCAmelCase__   ,						self.concept_embeds)

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

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

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

									return images, has_nsfw_concepts









import argparse
import hashlib  # hashlib is only used inside the Test class
import struct







class 						__magic_name__			:

   '''simple docstring'''




   def __init__(				self,    lowercase_       )							->    List[str]:






     """simple docstring"""






     a__  =data
     a__  =[0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0]



   @staticmethod
   def  _UpperCAmelCase (				lowercase_,    lowercase_       )							->    Union[str, Any]:






     """simple docstring"""






     return ((n << b) | (n >> (32 - b))) & 0Xffffffff



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






     """simple docstring"""






     a__  =b'''\x80''' + b'''\x00''' * (63 - (len(self.data       ) + 8) % 64)
     a__  =self.data + padding + struct.pack('''>Q''',    8 * len(self.data       )       )
     return padded_data



   def  _UpperCAmelCase (				self       )							->    Any:






     """simple docstring"""






     return [
         self.padded_data[i : i + 64] for i in range(0,    len(self.padded_data       ),    64       )
     ]



   def  _UpperCAmelCase (				self,    lowercase_       )							->    List[Any]:






     """simple docstring"""






     a__  =list(struct.unpack('''>16L''',    lowercase_       )       ) + [0] * 64
     for i in range(16,    80       ):
       a__  =self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]),    1       )
     return w



   def  _UpperCAmelCase (				self       )							->    Any:






     """simple docstring"""






     a__  =self.padding()
     a__  =self.split_blocks()
     for block in self.blocks:
       a__  =self.expand_block(lowercase_       )
       a__,      a__,      a__,      a__,      a__  =self.h
       for i in range(0,    80       ):
         if 0 <= i < 20:
           a__  =(b & c) | ((~b) & d)
           a__  =0X5a827999
         elif 20 <= i < 40:
           a__  =b ^ c ^ d
           a__  =0X6ed9eba1
         elif 40 <= i < 60:
           a__  =(b & c) | (b & d) | (c & d)
           a__  =0X8f1bbcdc
         elif 60 <= i < 80:
           a__  =b ^ c ^ d
           a__  =0Xca62c1d6
         a__,      a__,      a__,      a__,      a__  =(
             self.rotate(lowercase_,    5       ) + f + e + k + expanded_block[i] & 0Xffffffff,
             a,
             self.rotate(lowercase_,    30       ),
             c,
             d,
         )
       a__  =(
           self.h[0] + a & 0Xffffffff,
           self.h[1] + b & 0Xffffffff,
           self.h[2] + c & 0Xffffffff,
           self.h[3] + d & 0Xffffffff,
           self.h[4] + e & 0Xffffffff,
       )
     return ("{:08x}" * 5).format(*self.h       )





def 			UpperCAmelCase__				(			):





  '''simple docstring'''







  a__  =b'''Test String'''
  assert SHAaHash(_A							).final_hash() == hashlib.shaa(_A							).hexdigest()  # noqa: S324




def 			UpperCAmelCase__				(			):





  '''simple docstring'''







  a__  =argparse.ArgumentParser(description='''Process some strings or files'''							)
  parser.add_argument(
      '''--string'''	,      dest='''input_string'''	,      default='''Hello World!! Welcome to Cryptography'''	,      help='''Hash the string'''	,      )
  parser.add_argument('''--file'''	,      dest='''input_file'''	,      help='''Hash contents of a file'''							)
  a__  =parser.parse_args()
  a__  =args.input_string
  # In any case hash input should be a bytestring
  if args.input_file:
    with open(args.input_file	,      '''rb'''							) as f:
      a__  =f.read()
  else:
    a__  =bytes(_A	,      '''utf-8'''							)
  print(SHAaHash(_A							).final_hash()							)


if __name__ == "__main__":
       main()
       import doctest

       doctest.testmod()
