





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

from ...utils import logging


a__:      str									=		logging.get_logger(__name__)


def 	UpperCamelCase__(       UpperCamelCase__			:       Any ,     UpperCamelCase__			:       Union[str, Any]  )->Optional[Any]:
       A__											=						nn.functional.normalize(__snake_case  )
       A__											=						nn.functional.normalize(__snake_case  )
       return torch.mm(__snake_case ,     normalized_text_embeds.t()  )




class     SCREAMING_SNAKE_CASE__ (						a__      ):
 __SCREAMING_SNAKE_CASE							       =	CLIPConfig

 __SCREAMING_SNAKE_CASE							       =	['''CLIPEncoderLayer''']



 def __init__(							self,__lowerCamelCase ):
        super().__init__(_UpperCAmelCase )

        A__											=						CLIPVisionModel(config.vision_config )
        A__											=						nn.Linear(config.vision_config.hidden_size,config.projection_dim,bias=_UpperCAmelCase )

        A__											=						nn.Parameter(torch.ones(17,config.projection_dim ),requires_grad=_UpperCAmelCase )
        A__											=						nn.Parameter(torch.ones(3,config.projection_dim ),requires_grad=_UpperCAmelCase )

        A__											=						nn.Parameter(torch.ones(17 ),requires_grad=_UpperCAmelCase )
        A__											=						nn.Parameter(torch.ones(3 ),requires_grad=_UpperCAmelCase )



 @torch.no_grad()
 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase ):
        A__											=						self.vision_model(_UpperCAmelCase )[1]  # pooled_output
        A__											=						self.visual_projection(_UpperCAmelCase )

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

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

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

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

               result.append(_UpperCAmelCase )

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

        return images, has_nsfw_concepts




 @torch.no_grad()
 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase ):
        A__											=						self.vision_model(_UpperCAmelCase )[1]  # pooled_output
        A__											=						self.visual_projection(_UpperCAmelCase )

        A__											=						cosine_distance(_UpperCAmelCase,self.special_care_embeds )
        A__											=						cosine_distance(_UpperCAmelCase,self.concept_embeds )

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

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

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

        return images, has_nsfw_concepts












'''simple docstring'''




lowercase__    :      Dict						=    {
    '''Pillow''': '''Pillow''',
    '''accelerate''': '''accelerate>=0.11.0''',
    '''compel''': '''compel==0.1.8''',
    '''black''': '''black~=23.1''',
    '''datasets''': '''datasets''',
    '''filelock''': '''filelock''',
    '''flax''': '''flax>=0.4.1''',
    '''hf-doc-builder''': '''hf-doc-builder>=0.3.0''',
    '''huggingface-hub''': '''huggingface-hub>=0.13.2''',
    '''requests-mock''': '''requests-mock==1.10.0''',
    '''importlib_metadata''': '''importlib_metadata''',
    '''invisible-watermark''': '''invisible-watermark''',
    '''isort''': '''isort>=5.5.4''',
    '''jax''': '''jax>=0.2.8,!=0.3.2''',
    '''jaxlib''': '''jaxlib>=0.1.65''',
    '''Jinja2''': '''Jinja2''',
    '''k-diffusion''': '''k-diffusion>=0.0.12''',
    '''torchsde''': '''torchsde''',
    '''note_seq''': '''note_seq''',
    '''librosa''': '''librosa''',
    '''numpy''': '''numpy''',
    '''omegaconf''': '''omegaconf''',
    '''parameterized''': '''parameterized''',
    '''protobuf''': '''protobuf>=3.20.3,<4''',
    '''pytest''': '''pytest''',
    '''pytest-timeout''': '''pytest-timeout''',
    '''pytest-xdist''': '''pytest-xdist''',
    '''ruff''': '''ruff>=0.0.241''',
    '''safetensors''': '''safetensors''',
    '''sentencepiece''': '''sentencepiece>=0.1.91,!=0.1.92''',
    '''scipy''': '''scipy''',
    '''onnx''': '''onnx''',
    '''regex''': '''regex!=2019.12.17''',
    '''requests''': '''requests''',
    '''tensorboard''': '''tensorboard''',
    '''torch''': '''torch>=1.4''',
    '''torchvision''': '''torchvision''',
    '''transformers''': '''transformers>=4.25.1''',
    '''urllib3''': '''urllib3<=2.0.0''',
}