


'''simple docstring'''





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

from ...utils import logging


__a     =			logging.get_logger(__name__)
def   _UpperCamelCase				(						lowerCAmelCase_  ,						lowerCAmelCase_   )						->List[str]:
   UpperCAmelCase							=     nn.functional.normalize(__UpperCamelCase   )
   UpperCAmelCase							=     nn.functional.normalize(__UpperCamelCase   )
   return torch.mm(__UpperCamelCase  ,						normalized_text_embeds.t()   )







class   __lowercase				(  SCREAMING_SNAKE_CASE__  ):
      UpperCamelCase								=       CLIPConfig

      UpperCamelCase								=       ['''CLIPEncoderLayer''']





      def __init__(		self						:					List[Any]					,       __lowerCamelCase						:					Optional[Any]       )    ->   Union[str, Any]:






         """simple docstring"""







         super().__init__(_lowercase       )

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

         UpperCAmelCase							=     nn.Parameter(torch.ones(1_7					,       config.projection_dim       )					,       requires_grad=_lowercase       )
         UpperCAmelCase							=     nn.Parameter(torch.ones(3					,       config.projection_dim       )					,       requires_grad=_lowercase       )

         UpperCAmelCase							=     nn.Parameter(torch.ones(1_7       )					,       requires_grad=_lowercase       )
         UpperCAmelCase							=     nn.Parameter(torch.ones(3       )					,       requires_grad=_lowercase       )





      @torch.no_grad()
      def        _lowercase				(		self						:					List[Any]					,       __lowerCamelCase						:					int					,       __lowerCamelCase						:					Optional[Any]       )    ->   Any:






         """simple docstring"""







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

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

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

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

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

            result.append(_lowercase       )

         UpperCAmelCase							=     [len(res["""bad_concepts"""]       ) > 0 for res in result]

         return images, has_nsfw_concepts





      @torch.no_grad()
      def        _lowercase				(		self						:					str					,       __lowerCamelCase						:					List[Any]					,       __lowerCamelCase						:					List[str]       )    ->   Tuple:






         """simple docstring"""







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

         UpperCAmelCase							=     cosine_distance(_lowercase					,       self.special_care_embeds       )
         UpperCAmelCase							=     cosine_distance(_lowercase					,       self.concept_embeds       )

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

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

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

         return images, has_nsfw_concepts







def   _UpperCamelCase				(						lowerCAmelCase_  ,						lowerCAmelCase_   )						->int:
   return int((input_a, input_a).count(0   ) == 0   )
def   _UpperCamelCase				(						)						->None:
   assert and_gate(0  ,						0   ) == 0
   assert and_gate(0  ,						1   ) == 0
   assert and_gate(1  ,						0   ) == 0
   assert and_gate(1  ,						1   ) == 1


if __name__ == "__main__":
 test_and_gate()
 print(and_gate(1, 0))
 print(and_gate(0, 0))
 print(and_gate(0, 1))
 print(and_gate(1, 1))



