




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

from ...utils import logging


lowerCamelCase__				:     Any			       =							logging.get_logger(__name__)

def       UpperCAmelCase_							(   __UpperCAmelCase		:			List[str]    ,    __UpperCAmelCase		:			Dict							)      ->				Tuple:
      SCREAMING_SNAKE_CASE_					=    nn.functional.normalize(__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_					=    nn.functional.normalize(__UpperCAmelCase							)
      return torch.mm(__UpperCAmelCase    ,    normalized_text_embeds.t()							)





class  lowerCamelCase_							(   _SCREAMING_SNAKE_CASE      ):


 '''simple docstring'''







 lowercase_       					=					CLIPConfig

 lowercase_       					=					["CLIPEncoderLayer"]



 def __init__(							self						:	int       ,       _lowerCAmelCase						:	CLIPConfig		):
       super().__init__(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    CLIPVisionModel(config.vision_config		)
       SCREAMING_SNAKE_CASE_					=    nn.Linear(config.vision_config.hidden_size       ,       config.projection_dim       ,       bias=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    nn.Parameter(torch.ones(17       ,       config.projection_dim		)       ,       requires_grad=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_					=    nn.Parameter(torch.ones(3       ,       config.projection_dim		)       ,       requires_grad=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    nn.Parameter(torch.ones(17		)       ,       requires_grad=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_					=    nn.Parameter(torch.ones(3		)       ,       requires_grad=_lowerCAmelCase		)



 @torch.no_grad()
 def    lowerCAmelCase_						(							self						:	Optional[int]       ,       _lowerCAmelCase						:	Tuple       ,       _lowerCAmelCase						:	Union[str, Any]		):
       SCREAMING_SNAKE_CASE_					=    self.vision_model(_lowerCAmelCase		)[1]  # pooled_output
       SCREAMING_SNAKE_CASE_					=    self.visual_projection(_lowerCAmelCase		)

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

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

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

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

             result.append(_lowerCAmelCase		)

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

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

       if any(_lowerCAmelCase		):
             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						:	Dict       ,       _lowerCAmelCase						:	torch.FloatTensor       ,       _lowerCAmelCase						:	torch.FloatTensor		):
       SCREAMING_SNAKE_CASE_					=    self.vision_model(_lowerCAmelCase		)[1]  # pooled_output
       SCREAMING_SNAKE_CASE_					=    self.visual_projection(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    cosine_distance(_lowerCAmelCase       ,       self.special_care_embeds		)
       SCREAMING_SNAKE_CASE_					=    cosine_distance(_lowerCAmelCase       ,       self.concept_embeds		)

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

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

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

       SCREAMING_SNAKE_CASE_					=    0.0  # black image

       return images, has_nsfw_concepts





import warnings

from ...utils import logging
from .image_processing_detr import DetrImageProcessor


lowerCamelCase__				:     Optional[Any]			       =							logging.get_logger(__name__)





class  lowerCamelCase_							(   _SCREAMING_SNAKE_CASE      ):


 '''simple docstring'''







 def __init__(							self						:	Dict       ,       *_lowerCAmelCase						:	str       ,       **_lowerCAmelCase						:	List[str]		):
       warnings.warn(
           'The class DetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
           ' Please use DetrImageProcessor instead.'       ,       _lowerCAmelCase       ,       )
       super().__init__(*_lowerCAmelCase       ,       **_lowerCAmelCase		)