





'''simple docstring'''


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

from ...utils import logging


_lowerCamelCase					:						Tuple					     =							logging.get_logger(__name__)




def  __a			(  UpperCAmelCase							,      UpperCAmelCase     )   ->List[str]:



	"""simple docstring"""







	A					=   nn.functional.normalize(UpperCAmelCase     )
	A					=   nn.functional.normalize(UpperCAmelCase     )
	return torch.mm(UpperCAmelCase							,      normalized_text_embeds.t()     )



class 				__UpperCAmelCase	(							_SCREAMING_SNAKE_CASE    ):







		'''simple docstring'''







		__lowerCAmelCase								=     CLIPConfig

		__lowerCAmelCase								=     ['''CLIPEncoderLayer''']







		def __init__(self    :   Optional[Any]   ,   _lowerCAmelCase    :   Optional[int]   ):
			super().__init__(__A   )

			A					=   CLIPVisionModel(config.vision_config   )
			A					=   nn.Linear(config.vision_config.hidden_size   ,   config.projection_dim   ,   bias=__A   )

			A					=   nn.Parameter(torch.ones(17   ,   config.projection_dim   )   ,   requires_grad=__A   )
			A					=   nn.Parameter(torch.ones(3   ,   config.projection_dim   )   ,   requires_grad=__A   )

			A					=   nn.Parameter(torch.ones(17   )   ,   requires_grad=__A   )
			A					=   nn.Parameter(torch.ones(3   )   ,   requires_grad=__A   )







		@torch.no_grad()
		def 							A  (self    :   Optional[Any]   ,   _lowerCAmelCase    :   Union[str, Any]   ,   _lowerCAmelCase    :   List[Any]   ):
			A					=   self.vision_model(__A   )[1]  # pooled_output
			A					=   self.visual_projection(__A   )

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

			A					=   []
			A					=   image_embeds.shape[0]
			for i in range(__A   ):
				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(__A   )

				result.append(__A   )

			A					=   [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]   ):
						A					=   torch.zeros_like(images[idx]   )  # black image
					else:
						A					=   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 							A  (self    :   Optional[int]   ,   _lowerCAmelCase    :   Any   ,   _lowerCAmelCase    :   Optional[int]   ):
			A					=   self.vision_model(__A   )[1]  # pooled_output
			A					=   self.visual_projection(__A   )

			A					=   cosine_distance(__A   ,   self.special_care_embeds   )
			A					=   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
			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   )

			A					=   0.0  # black image

			return images, has_nsfw_concepts





"""simple docstring"""







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

from ...utils import logging


lowerCamelCase_  :  Tuple     		=    logging.get_logger(__name__)
def _A		(		lowercase			,       lowercase						):







    """simple docstring"""
    a											=nn.functional.normalize(lowercase						)
    a											=nn.functional.normalize(lowercase						)
    return torch.mm(lowercase			,       normalized_text_embeds.t()						)






class  __A							(			_SCREAMING_SNAKE_CASE     ):






 """simple docstring"""




 __lowerCAmelCase					   =    CLIPConfig

 __lowerCAmelCase					   =    ["CLIPEncoderLayer"]


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

     a											=CLIPVisionModel(config.vision_config		)
     a											=nn.Linear(config.vision_config.hidden_size					,       config.projection_dim					,       bias=__A		)

     a											=nn.Parameter(torch.ones(17					,       config.projection_dim		)					,       requires_grad=__A		)
     a											=nn.Parameter(torch.ones(3					,       config.projection_dim		)					,       requires_grad=__A		)

     a											=nn.Parameter(torch.ones(17		)					,       requires_grad=__A		)
     a											=nn.Parameter(torch.ones(3		)					,       requires_grad=__A		)


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

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

     a											=[]
     a											=image_embeds.shape[0]
     for i in range(__A		):
         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(__A		)

         result.append(__A		)

     a											=[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]		):
                 a											=torch.zeros_like(images[idx]		)  # black image
             else:
                 a											=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  SCREAMING_SNAKE_CASE				(						self					,       __A					,       __A		)   ->	str:
     a											=self.vision_model(__A		)[1]  # pooled_output
     a											=self.visual_projection(__A		)

     a											=cosine_distance(__A					,       self.special_care_embeds		)
     a											=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
     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		)

     a											=0.0  # black image

     return images, has_nsfw_concepts