




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    lowerCamelCase__			(		A__			:   Optional[int]    ,     A__			:   Any      ):





       '''simple docstring'''



       __lowerCamelCase  =		nn.functional.normalize(A__      )
       __lowerCamelCase  =		nn.functional.normalize(A__      )
       return torch.mm(A__    ,     normalized_text_embeds.t()      )





class        lowerCamelCase__(   __lowerCamelCase):
      UpperCAmelCase__ :      int       						=  CLIPConfig

      UpperCAmelCase__ :      Union[str, Any]       						=  ['CLIPEncoderLayer']
      def __init__(							self:					Tuple       ,			UpperCamelCase_:					CLIPConfig  ):
             super().__init__(UpperCamelCase_  )

             __lowerCamelCase  =		CLIPVisionModel(config.vision_config  )
             __lowerCamelCase  =		nn.Linear(config.vision_config.hidden_size       ,			config.projection_dim       ,			bias=UpperCamelCase_  )

             __lowerCamelCase  =		nn.Parameter(torch.ones(17       ,			config.projection_dim  )       ,			requires_grad=UpperCamelCase_  )
             __lowerCamelCase  =		nn.Parameter(torch.ones(3       ,			config.projection_dim  )       ,			requires_grad=UpperCamelCase_  )

             __lowerCamelCase  =		nn.Parameter(torch.ones(17  )       ,			requires_grad=UpperCamelCase_  )
             __lowerCamelCase  =		nn.Parameter(torch.ones(3  )       ,			requires_grad=UpperCamelCase_  )
      @torch.no_grad()
      def      lowerCAmelCase__		(							self:					List[str]       ,			UpperCamelCase_:					Dict       ,			UpperCamelCase_:					Union[str, Any]  ):
             __lowerCamelCase  =		self.vision_model(UpperCamelCase_  )[1]  # pooled_output
             __lowerCamelCase  =		self.visual_projection(UpperCamelCase_  )

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

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

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

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

                    result.append(UpperCamelCase_  )

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

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

             if any(UpperCamelCase_  ):
                    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      lowerCAmelCase__		(							self:					int       ,			UpperCamelCase_:					torch.FloatTensor       ,			UpperCamelCase_:					torch.FloatTensor  ):
             __lowerCamelCase  =		self.vision_model(UpperCamelCase_  )[1]  # pooled_output
             __lowerCamelCase  =		self.visual_projection(UpperCamelCase_  )

             __lowerCamelCase  =		cosine_distance(UpperCamelCase_       ,			self.special_care_embeds  )
             __lowerCamelCase  =		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
             __lowerCamelCase  =		0.0

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

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

             __lowerCamelCase  =		0.0  # black image

             return images, has_nsfw_concepts







from typing import Callable




def    lowerCamelCase__			(		A__			:   Callable      ):





       '''simple docstring'''



       def wrapper(A__			:   int      ):
              __lowerCamelCase  =		function_with_docstring.__doc__
              return target_function

       return wrapper

