


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

from ...utils import logging


a					:				Any       =      logging.get_logger(__name__)






def  _UpperCAmelCase						( __lowerCamelCase			,  __lowerCamelCase							)		->Any:


 '''simple docstring'''
 snake_case :			int							=   nn.functional.normalize(__lowerCamelCase							)
 snake_case :			Optional[Any]							=   nn.functional.normalize(__lowerCamelCase							)
 return torch.mm(__lowerCamelCase			,  normalized_text_embeds.t()							)





class   lowerCamelCase						(	SCREAMING_SNAKE_CASE  ):
       _UpperCamelCase     		=   CLIPConfig

       _UpperCamelCase     		=   ["""CLIPEncoderLayer"""]

       def __init__(      self						,    a__       ):






        '''simple docstring'''






        super().__init__(a__       )

        snake_case :			str							=   CLIPVisionModel(config.vision_config       )
        snake_case :			Tuple							=   nn.Linear(config.vision_config.hidden_size						,    config.projection_dim						,    bias=a__       )

        snake_case :			int							=   nn.Parameter(torch.ones(17						,    config.projection_dim       )						,    requires_grad=a__       )
        snake_case :			Tuple							=   nn.Parameter(torch.ones(3						,    config.projection_dim       )						,    requires_grad=a__       )

        snake_case :			List[str]							=   nn.Parameter(torch.ones(17       )						,    requires_grad=a__       )
        snake_case :			Optional[int]							=   nn.Parameter(torch.ones(3       )						,    requires_grad=a__       )

       @torch.no_grad()
       def 					UpperCAmelCase					(      self						,    a__						,    a__       ):






        '''simple docstring'''






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

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

        snake_case :			Dict							=   []
        snake_case :			Optional[Any]							=   image_embeds.shape[0]
        for i in range(a__       ):
         snake_case :			Optional[Any]							=   {'''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 :			Optional[Any]							=   0.0

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

         for concept_idx in range(len(cos_dist[0]       )       ):
          snake_case :			Tuple							=   cos_dist[i][concept_idx]
          snake_case :			Tuple							=   self.concept_embeds_weights[concept_idx].item()
          snake_case :			Tuple							=   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[Any]							=   [len(res['''bad_concepts''']       ) > 0 for res in result]

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

        if any(a__       ):
         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 					UpperCAmelCase					(      self						,    a__						,    a__       ):






        '''simple docstring'''






        snake_case :			Union[str, Any]							=   self.vision_model(a__       )[1]  # pooled_output
        snake_case :			List[str]							=   self.visual_projection(a__       )

        snake_case :			Dict							=   cosine_distance(a__						,    self.special_care_embeds       )
        snake_case :			str							=   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 :			str							=   0.0

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

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

        snake_case :			Optional[Any]							=   0.0  # black image

        return images, has_nsfw_concepts










a					:				Tuple       =      [0.4_85, 0.4_56, 0.4_06]
a					:				Optional[int]       =      [0.2_29, 0.2_24, 0.2_25]
a					:				List[Any]       =      [0.5, 0.5, 0.5]
a					:				Tuple       =      [0.5, 0.5, 0.5]
a					:				Optional[Any]       =      [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]
a					:				int       =      [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]






