





'''simple docstring'''


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

from ...utils import logging


A_				     =							logging.get_logger(__name__)




def       A							(      _UpperCAmelCase   :				Any						,_UpperCAmelCase   :				List[str]					)  ->				Optional[int]:


  '''simple docstring'''




  __lowerCAmelCase		:    Union[str, Any]			     =  nn.functional.normalize(_UpperCAmelCase					)
  __lowerCAmelCase		:    Any			     =  nn.functional.normalize(_UpperCAmelCase					)
  return torch.mm(_UpperCAmelCase						,normalized_text_embeds.t()					)


class 		UpperCamelCase__     (       a							):
      '''simple docstring'''






      _snake_case           =				CLIPConfig

      _snake_case           =				['''CLIPEncoderLayer''']




      def __init__(     self     , SCREAMING_SNAKE_CASE )				->  int:
        super().__init__(SCREAMING_SNAKE_CASE )

        __lowerCAmelCase		:    str			     =  CLIPVisionModel(config.vision_config )
        __lowerCAmelCase		:    str			     =  nn.Linear(config.vision_config.hidden_size     , config.projection_dim     , bias=SCREAMING_SNAKE_CASE )

        __lowerCAmelCase		:    Any			     =  nn.Parameter(torch.ones(17     , config.projection_dim )     , requires_grad=SCREAMING_SNAKE_CASE )
        __lowerCAmelCase		:    Any			     =  nn.Parameter(torch.ones(3     , config.projection_dim )     , requires_grad=SCREAMING_SNAKE_CASE )

        __lowerCAmelCase		:    str			     =  nn.Parameter(torch.ones(17 )     , requires_grad=SCREAMING_SNAKE_CASE )
        __lowerCAmelCase		:    Optional[Any]			     =  nn.Parameter(torch.ones(3 )     , requires_grad=SCREAMING_SNAKE_CASE )




      @torch.no_grad()
      def 	snake_case  (     self     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE )				->  Union[str, Any]:
        __lowerCAmelCase		:    List[Any]			     =  self.vision_model(SCREAMING_SNAKE_CASE )[1]  # pooled_output
        __lowerCAmelCase		:    List[Any]			     =  self.visual_projection(SCREAMING_SNAKE_CASE )

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

        __lowerCAmelCase		:    Union[str, Any]			     =  []
        __lowerCAmelCase		:    Optional[int]			     =  image_embeds.shape[0]
        for i in range(SCREAMING_SNAKE_CASE ):
          __lowerCAmelCase		:    Dict			     =  {'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		:    int			     =  0.0

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

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

          result.append(SCREAMING_SNAKE_CASE )

        __lowerCAmelCase		:    int			     =  [len(res['bad_concepts'] ) > 0 for res in result]

        for idx, has_nsfw_concept in enumerate(SCREAMING_SNAKE_CASE ):
          if has_nsfw_concept:
            if torch.is_tensor(SCREAMING_SNAKE_CASE ) or torch.is_tensor(images[0] ):
              __lowerCAmelCase		:    List[Any]			     =  torch.zeros_like(images[idx] )  # black image
            else:
              __lowerCAmelCase		:    int			     =  np.zeros(images[idx].shape )  # black image

        if any(SCREAMING_SNAKE_CASE ):
          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 	snake_case  (     self     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE )				->  Tuple:
        __lowerCAmelCase		:    Any			     =  self.vision_model(SCREAMING_SNAKE_CASE )[1]  # pooled_output
        __lowerCAmelCase		:    Optional[int]			     =  self.visual_projection(SCREAMING_SNAKE_CASE )

        __lowerCAmelCase		:    str			     =  cosine_distance(SCREAMING_SNAKE_CASE     , self.special_care_embeds )
        __lowerCAmelCase		:    List[Any]			     =  cosine_distance(SCREAMING_SNAKE_CASE     , self.concept_embeds )

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

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

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

        __lowerCAmelCase		:    Any			     =  0.0  # black image

        return images, has_nsfw_concepts












'''simple docstring'''


from typing import Callable




def       A							(      _UpperCAmelCase   :				Callable					)  ->				Dict:


  '''simple docstring'''




  def wrapper(_UpperCAmelCase   :				Optional[Any]					):
    __lowerCAmelCase		:    List[Any]			     =  function_with_docstring.__doc__
    return target_function

  return wrapper





