




from collections.abc import Generator
from math import sin







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			bytes:



       """simple docstring"""

       if len(lowercase_		) != 32:
              raise ValueError('''Input must be of length 32'''		)

       A__ 					=       b''''''
       for i in [3, 2, 1, 0]:
              little_endian += string_aa[8 * i : 8 * i + 8]
       return little_endian







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			bytes:



       """simple docstring"""

       if i < 0:
              raise ValueError('''Input must be non-negative'''		)

       A__ 					=       format(lowercase_					,							'''08x'''		)[-8:]
       A__ 					=       b''''''
       for i in [3, 2, 1, 0]:
              little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8'''		)
       return little_endian_hex







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			bytes:



       """simple docstring"""

       A__ 					=       b''''''
       for char in message:
              bit_string += format(lowercase_					,							'''08b'''		).encode('''utf-8'''		)
       A__ 					=       format(len(lowercase_		)					,							'''064b'''		).encode('''utf-8'''		)

       # Pad bit_string to a multiple of 512 chars
       bit_string += b"1"
       while len(lowercase_		) % 512 != 448:
              bit_string += b"0"
       bit_string += to_little_endian(start_len[32:]		) + to_little_endian(start_len[:32]		)

       return bit_string







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			Generator[list[int], None, None]:



       """simple docstring"""

       if len(lowercase_		) % 512 != 0:
              raise ValueError('''Input must have length that\'s a multiple of 512'''		)

       for pos in range(0					,							len(lowercase_		)					,							512		):
              A__ 					=       bit_string[pos : pos + 512]
              A__ 					=       []
              for i in range(0					,							512					,							32		):
                     block_words.append(int(to_little_endian(block[i : i + 32]		)					,							2		)		)
              yield block_words







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			int:



       """simple docstring"""

       if i < 0:
              raise ValueError('''Input must be non-negative'''		)

       A__ 					=       format(lowercase_					,							'''032b'''		)
       A__ 					=       ''''''
       for c in i_str:
              new_str += "1" if c == "0" else "0"
       return int(lowercase_					,							2		)







def SCREAMING_SNAKE_CASE							(			lowercase_					,							lowercase_		)  ->			int:



       """simple docstring"""

       return (a + b) % 2**32







def SCREAMING_SNAKE_CASE							(			lowercase_					,							lowercase_		)  ->			int:



       """simple docstring"""

       if i < 0:
              raise ValueError('''Input must be non-negative'''		)
       if shift < 0:
              raise ValueError('''Shift must be non-negative'''		)
       return ((i << shift) ^ (i >> (32 - shift))) % 2**32







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			bytes:



       """simple docstring"""

       A__ 					=       preprocess(lowercase_		)

       A__ 					=       [int(2**32 * abs(sin(i + 1		)		)		) for i in range(64		)]

       # Starting states
       A__ 					=       0x67_452_301
       A__ 					=       0xEF_CDA_B89
       A__ 					=       0x98_BAD_CFE
       A__ 					=       0x10_325_476

       A__ 					=       [
           7,
           12,
           17,
           22,
           7,
           12,
           17,
           22,
           7,
           12,
           17,
           22,
           7,
           12,
           17,
           22,
           5,
           9,
           14,
           20,
           5,
           9,
           14,
           20,
           5,
           9,
           14,
           20,
           5,
           9,
           14,
           20,
           4,
           11,
           16,
           23,
           4,
           11,
           16,
           23,
           4,
           11,
           16,
           23,
           4,
           11,
           16,
           23,
           6,
           10,
           15,
           21,
           6,
           10,
           15,
           21,
           6,
           10,
           15,
           21,
           6,
           10,
           15,
           21,
       ]

       # Process bit string in chunks, each with 16 32-char words
       for block_words in get_block_words(lowercase_		):
              A__ 					=       aa
              A__ 					=       ba
              A__ 					=       ca
              A__ 					=       da

              # Hash current chunk
              for i in range(64		):
                     if i <= 15:
                            # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
                            A__ 					=       d ^ (b & (c ^ d))
                            A__ 					=       i
                     elif i <= 31:
                            # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
                            A__ 					=       c ^ (d & (b ^ c))
                            A__ 					=       (5 * i + 1) % 16
                     elif i <= 47:
                            A__ 					=       b ^ c ^ d
                            A__ 					=       (3 * i + 5) % 16
                     else:
                            A__ 					=       c ^ (b | not_aa(lowercase_		))
                            A__ 					=       (7 * i) % 16
                     A__ 					=       (f + a + added_consts[i] + block_words[g]) % 2**32
                     A__ 					=       d
                     A__ 					=       c
                     A__ 					=       b
                     A__ 					=       sum_aa(lowercase_					,							left_rotate_aa(lowercase_					,							shift_amounts[i]		)		)

              # Add hashed chunk to running total
              A__ 					=       sum_aa(lowercase_					,							lowercase_		)
              A__ 					=       sum_aa(lowercase_					,							lowercase_		)
              A__ 					=       sum_aa(lowercase_					,							lowercase_		)
              A__ 					=       sum_aa(lowercase_					,							lowercase_		)

       A__ 					=       reformat_hex(lowercase_		) + reformat_hex(lowercase_		) + reformat_hex(lowercase_		) + reformat_hex(lowercase_		)
       return digest


if __name__ == "__main__":
  import doctest

  doctest.testmod()





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

from ...utils import logging


lowercase_   							=  logging.get_logger(__name__)
def 	a (     A__      :  Optional[int] ,  A__      :  Union[str, Any]	)       -> int:





      """simple docstring"""



      _lowercase      			=nn.functional.normalize(A__	)
      _lowercase      			=nn.functional.normalize(A__	)
      return torch.mm(A__ ,  normalized_text_embeds.t()	)







class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):
  _a		     =    CLIPConfig

  _a		     =    ["""CLIPEncoderLayer"""]




  def __init__(							self				,  lowerCAmelCase   )    ->					Union[str, Any]:
        '''simple docstring'''






        super().__init__(lowerCAmelCase   )

        _lowercase      			=CLIPVisionModel(config.vision_config   )
        _lowercase      			=nn.Linear(config.vision_config.hidden_size				,  config.projection_dim				,  bias=lowerCAmelCase   )

        _lowercase      			=nn.Parameter(torch.ones(17				,  config.projection_dim   )				,  requires_grad=lowerCAmelCase   )
        _lowercase      			=nn.Parameter(torch.ones(3				,  config.projection_dim   )				,  requires_grad=lowerCAmelCase   )

        _lowercase      			=nn.Parameter(torch.ones(17   )				,  requires_grad=lowerCAmelCase   )
        _lowercase      			=nn.Parameter(torch.ones(3   )				,  requires_grad=lowerCAmelCase   )




  @torch.no_grad()
  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Optional[int]:
        '''simple docstring'''






        _lowercase      			=self.vision_model(lowerCAmelCase   )[1]  # pooled_output
        _lowercase      			=self.visual_projection(lowerCAmelCase   )

        # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.special_care_embeds   ).cpu().float().numpy()
        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.concept_embeds   ).cpu().float().numpy()

        _lowercase      			=[]
        _lowercase      			=image_embeds.shape[0]
        for i in range(lowerCAmelCase   ):
              _lowercase      			={'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
              _lowercase      			=0.0

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

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

              result.append(lowerCAmelCase   )

        _lowercase      			=[len(res['bad_concepts']   ) > 0 for res in result]

        return images, has_nsfw_concepts




  @torch.no_grad()
  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=self.vision_model(lowerCAmelCase   )[1]  # pooled_output
        _lowercase      			=self.visual_projection(lowerCAmelCase   )

        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.special_care_embeds   )
        _lowercase      			=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
        _lowercase      			=0.0

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

        _lowercase      			=(cos_dist - self.concept_embeds_weights) + special_adjustment
        # concept_scores = concept_scores.round(decimals=3)
        _lowercase      			=torch.any(concept_scores > 0				,  dim=1   )

        return images, has_nsfw_concepts


