






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

from ...utils import logging


lowerCamelCase__							=     logging.get_logger(__name__)






def   UpperCamelCase  (       snake_case__     :   Dict	,snake_case__     :   List[str]  ):




     '''simple docstring'''






     __snake_case			:Tuple          =						nn.functional.normalize(snake_case__  )
     __snake_case			:Union[str, Any]          =						nn.functional.normalize(snake_case__  )
     return torch.mm(snake_case__	,normalized_text_embeds.t()  )






class 			snake_case__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				Any 				= CLIPConfig

       lowerCamelCase							:				List[Any] 				= ["CLIPEncoderLayer"]



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






            '''simple docstring'''





            super().__init__(a__    )

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

            __snake_case			:Tuple          =						nn.Parameter(torch.ones(17			,						config.projection_dim    )			,						requires_grad=a__    )
            __snake_case			:Union[str, Any]          =						nn.Parameter(torch.ones(3			,						config.projection_dim    )			,						requires_grad=a__    )

            __snake_case			:Union[str, Any]          =						nn.Parameter(torch.ones(17    )			,						requires_grad=a__    )
            __snake_case			:Any          =						nn.Parameter(torch.ones(3    )			,						requires_grad=a__    )



       @torch.no_grad()
       def 					__lowercase						(							self			,						a__			,						a__    ) ->      str:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						self.vision_model(a__    )[1]  # pooled_output
            __snake_case			:Dict          =						self.visual_projection(a__    )

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

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

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

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

                 result.append(a__    )

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

            return images, has_nsfw_concepts



       @torch.no_grad()
       def 					__lowercase						(							self			,						a__			,						a__    ) ->      int:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.vision_model(a__    )[1]  # pooled_output
            __snake_case			:Any          =						self.visual_projection(a__    )

            __snake_case			:Dict          =						cosine_distance(a__			,						self.special_care_embeds    )
            __snake_case			:Dict          =						cosine_distance(a__			,						self.concept_embeds    )

            # increase this value to create a stronger `nsfw` filter
            # at the cost of increasing the possibility of filtering benign images
            __snake_case			:Optional[Any]          =						0.0

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

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

            return images, has_nsfw_concepts










def   UpperCamelCase  (       snake_case__     :   str  ):




     '''simple docstring'''






     __snake_case			:List[Any]          =						hex_num.strip()
     if not hex_num:
          raise ValueError("""No value was passed to the function"""  )

     __snake_case			:str          =						hex_num[0] == """-"""
     if is_negative:
          __snake_case			:List[Any]          =						hex_num[1:]

     try:
          __snake_case			:Tuple          =						int(snake_case__	,16  )
     except ValueError:
          raise ValueError("""Invalid value was passed to the function"""  )

     __snake_case			:int          =						""""""
     while int_num > 0:
          __snake_case			:Optional[int]          =						str(int_num % 2  ) + bin_str
          int_num >>= 1

     return int(("""-""" + bin_str) if is_negative else bin_str  )


if __name__ == "__main__":
     import doctest

     doctest.testmod()


