



import numpy as np
def 	UpperCamelCase			(     snake_case__ :					List[Any] ,  snake_case__ :					List[Any]="utf-8" ,  snake_case__ :					Optional[Any]="surrogatepass"			)			->  List[str]:
   UpperCamelCase					:						Dict					=			bin(int.from_bytes(text.encode(UpperCamelCase__ ,  UpperCamelCase__			) ,  'big'			)			)[2:]
   return bits.zfill(8 * ((len(UpperCamelCase__			) + 7) // 8)			)
def 	UpperCamelCase			(     snake_case__ :					Tuple ,  snake_case__ :					List[Any]="utf-8" ,  snake_case__ :					Tuple="surrogatepass"			)			->  Union[str, Any]:
   UpperCamelCase					:						int					=			int(UpperCamelCase__ ,  2			)
   return n.to_bytes((n.bit_length() + 7) // 8 ,  'big'			).decode(UpperCamelCase__ ,  UpperCamelCase__			) or "\0"
def 	UpperCamelCase			(     snake_case__ :					Optional[Any] ,  snake_case__ :					Optional[int]			)			->  str:
   if size_par + len(UpperCamelCase__			) <= 2**size_par - (len(UpperCamelCase__			) - 1):
      raise ValueError('size of parity don\'t match with size of data'			)

   UpperCamelCase					:						int					=			[]
   UpperCamelCase					:						str					=			[]
   UpperCamelCase					:						int					=			[bin(UpperCamelCase__			)[2:] for x in range(1 ,  size_par + len(UpperCamelCase__			) + 1			)]

   # sorted information data for the size of the output data
   UpperCamelCase					:						Tuple					=			[]
   # data position template + parity
   UpperCamelCase					:						Any					=			[]
   # parity bit counter
   UpperCamelCase					:						Optional[Any]					=			0
   # counter position of data bits
   UpperCamelCase					:						Dict					=			0

   for x in range(1 ,  size_par + len(UpperCamelCase__			) + 1			):
      # Performs a template of bit positions - who should be given,
      # and who should be parity
      if qtd_bp < size_par:
         if (np.log(UpperCamelCase__			) / np.log(2			)).is_integer():
            data_out_gab.append('P'			)
            UpperCamelCase					:						int					=			qtd_bp + 1
         else:
            data_out_gab.append('D'			)
      else:
         data_out_gab.append('D'			)

      # Sorts the data to the new output size
      if data_out_gab[-1] == "D":
         data_ord.append(data[cont_data]			)
         cont_data += 1
      else:
         data_ord.append(UpperCamelCase__			)

    # Calculates parity
   UpperCamelCase					:						str					=			0  # parity bit counter
   for bp in range(1 ,  size_par + 1			):
      # Bit counter one for a given parity
      UpperCamelCase					:						Any					=			0
      # counter to control the loop reading
      UpperCamelCase					:						Optional[Any]					=			0
      for x in data_ord:
         if x is not None:
            try:
               UpperCamelCase					:						Optional[int]					=			(bin_pos[cont_loop])[-1 * (bp)]
            except IndexError:
               UpperCamelCase					:						Optional[Any]					=			"0"
            if aux == "1" and x == "1":
               cont_bo += 1
         cont_loop += 1
      parity.append(cont_bo % 2			)

      qtd_bp += 1

   # Mount the message
   UpperCamelCase					:						Any					=			0  # parity bit counter
   for x in range(0 ,  size_par + len(UpperCamelCase__			)			):
      if data_ord[x] is None:
         data_out.append(str(parity[cont_bp]			)			)
         cont_bp += 1
      else:
         data_out.append(data_ord[x]			)

   return data_out


def 	UpperCamelCase			(     snake_case__ :					Any ,  snake_case__ :					str			)			->  Dict:
   UpperCamelCase					:						Optional[Any]					=			[]
   # Parity bit counter
   UpperCamelCase					:						List[Any]					=			0
   # Counter p data bit reading
   UpperCamelCase					:						int					=			0
   # list of parity received
   UpperCamelCase					:						List[str]					=			[]
   UpperCamelCase					:						Optional[Any]					=			[]

   for x in range(1 ,  len(UpperCamelCase__			) + 1			):
      # Performs a template of bit positions - who should be given,
      #  and who should be parity
      if qtd_bp < size_par and (np.log(UpperCamelCase__			) / np.log(2			)).is_integer():
         data_out_gab.append('P'			)
         UpperCamelCase					:						Optional[Any]					=			qtd_bp + 1
      else:
         data_out_gab.append('D'			)

      # Sorts the data to the new output size
      if data_out_gab[-1] == "D":
         data_output.append(data[cont_data]			)
      else:
         parity_received.append(data[cont_data]			)
      cont_data += 1

   # -----------calculates the parity with the data
   UpperCamelCase					:						Union[str, Any]					=			[]
   UpperCamelCase					:						List[Any]					=			[]
   UpperCamelCase					:						Dict					=			[bin(UpperCamelCase__			)[2:] for x in range(1 ,  size_par + len(UpperCamelCase__			) + 1			)]

   #  sorted information data for the size of the output data
   UpperCamelCase					:						Union[str, Any]					=			[]
   # Data position feedback + parity
   UpperCamelCase					:						Union[str, Any]					=			[]
   # Parity bit counter
   UpperCamelCase					:						Dict					=			0
   # Counter p data bit reading
   UpperCamelCase					:						Union[str, Any]					=			0

   for x in range(1 ,  size_par + len(UpperCamelCase__			) + 1			):
      # Performs a template position of bits - who should be given,
      # and who should be parity
      if qtd_bp < size_par and (np.log(UpperCamelCase__			) / np.log(2			)).is_integer():
         data_out_gab.append('P'			)
         UpperCamelCase					:						Union[str, Any]					=			qtd_bp + 1
      else:
         data_out_gab.append('D'			)

      # Sorts the data to the new output size
      if data_out_gab[-1] == "D":
         data_ord.append(data_output[cont_data]			)
         cont_data += 1
      else:
         data_ord.append(UpperCamelCase__			)

    # Calculates parity
   UpperCamelCase					:						int					=			0  # parity bit counter
   for bp in range(1 ,  size_par + 1			):
      # Bit counter one for a certain parity
      UpperCamelCase					:						Dict					=			0
      # Counter to control loop reading
      UpperCamelCase					:						Dict					=			0
      for x in data_ord:
         if x is not None:
            try:
               UpperCamelCase					:						Optional[int]					=			(bin_pos[cont_loop])[-1 * (bp)]
            except IndexError:
               UpperCamelCase					:						Union[str, Any]					=			"0"
            if aux == "1" and x == "1":
               cont_bo += 1
         cont_loop += 1
      parity.append(str(cont_bo % 2			)			)

      qtd_bp += 1

   # Mount the message
   UpperCamelCase					:						List[str]					=			0  # Parity bit counter
   for x in range(0 ,  size_par + len(UpperCamelCase__			)			):
      if data_ord[x] is None:
         data_out.append(str(parity[cont_bp]			)			)
         cont_bp += 1
      else:
         data_out.append(data_ord[x]			)

   UpperCamelCase					:						Tuple					=			parity_received == parity
   return data_output, ack








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

from ...utils import logging


__UpperCAmelCase      = logging.get_logger(__name__)
def 	UpperCamelCase			(     snake_case__ :					List[str] ,  snake_case__ :					str			)			->  Dict:
   UpperCamelCase					:						int					=			nn.functional.normalize(snake_case__			)
   UpperCamelCase					:						Union[str, Any]					=			nn.functional.normalize(snake_case__			)
   return torch.mm(snake_case__ ,  normalized_text_embeds.t()			)



class        lowerCAmelCase_	(						a__							):
       UpperCAmelCase__       :      int       =						CLIPConfig

       UpperCAmelCase__       :      Union[str, Any]       =						["CLIPEncoderLayer"]
       def __init__(    self,    SCREAMING_SNAKE_CASE_ )  ->	List[str]:
          super().__init__(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						int					=			CLIPVisionModel(config.vision_config )
          UpperCamelCase					:						int					=			nn.Linear(config.vision_config.hidden_size,    config.projection_dim,    bias=SCREAMING_SNAKE_CASE_ )

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

          UpperCamelCase					:						Dict					=			nn.Parameter(torch.ones(17 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
          UpperCamelCase					:						Optional[Any]					=			nn.Parameter(torch.ones(3 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
       @torch.no_grad()
       def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Union[str, Any]:
          UpperCamelCase					:						Optional[int]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
          UpperCamelCase					:						int					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )

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

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

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

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

             result.append(SCREAMING_SNAKE_CASE_ )

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

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

          if any(SCREAMING_SNAKE_CASE_ ):
             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       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Optional[int]:
          UpperCamelCase					:						Union[str, Any]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
          UpperCamelCase					:						str					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						str					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.special_care_embeds )
          UpperCamelCase					:						Any					=			cosine_distance(SCREAMING_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
          UpperCamelCase					:						Dict					=			0.0

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

          UpperCamelCase					:						List[str]					=			(cos_dist - self.concept_embeds_weights) + special_adjustment
          # concept_scores = concept_scores.round(decimals=3)
          UpperCamelCase					:						Tuple					=			torch.any(concept_scores > 0,    dim=1 )

          UpperCamelCase					:						Any					=			0.0  # black image

          return images, has_nsfw_concepts



