



"""simple docstring"""


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

from ...utils import logging


snake_case_				     =       logging.get_logger(__name__)

def  _lowerCAmelCase      (   lowercase_		,	lowercase_						):
						UpperCAmelCase             = nn.functional.normalize(lowercase_						)
						UpperCAmelCase             = nn.functional.normalize(lowercase_						)
						return torch.mm(lowercase_		,	normalized_text_embeds.t()						)







class       A_			(     SCREAMING_SNAKE_CASE_				):



						"""simple docstring"""
						__UpperCamelCase						=							CLIPConfig

						__UpperCamelCase						=							["""CLIPEncoderLayer"""]






						def __init__(					self :Union[str, Any]   ,  lowercase_ :CLIPConfig					)				->			Dict:
												super().__init__(lowercase_					)

												UpperCAmelCase             = CLIPVisionModel(config.vision_config					)
												UpperCAmelCase             = nn.Linear(config.vision_config.hidden_size   ,  config.projection_dim   ,  bias=lowercase_					)

												UpperCAmelCase             = nn.Parameter(torch.ones(17   ,  config.projection_dim					)   ,  requires_grad=lowercase_					)
												UpperCAmelCase             = nn.Parameter(torch.ones(3   ,  config.projection_dim					)   ,  requires_grad=lowercase_					)

												UpperCAmelCase             = nn.Parameter(torch.ones(17					)   ,  requires_grad=lowercase_					)
												UpperCAmelCase             = nn.Parameter(torch.ones(3					)   ,  requires_grad=lowercase_					)






						@torch.no_grad()
						def 	UpperCAmelCase__     (					self :Any   ,  lowercase_ :Dict   ,  lowercase_ :Union[str, Any]					)				->			Optional[int]:
												UpperCAmelCase             = self.vision_model(lowercase_					)[1]  # pooled_output
												UpperCAmelCase             = self.visual_projection(lowercase_					)

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

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

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

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

																		result.append(lowercase_					)

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

												return images, has_nsfw_concepts






						@torch.no_grad()
						def 	UpperCAmelCase__     (					self :Any   ,  lowercase_ :torch.FloatTensor   ,  lowercase_ :torch.FloatTensor					)				->			List[Any]:
												UpperCAmelCase             = self.vision_model(lowercase_					)[1]  # pooled_output
												UpperCAmelCase             = self.visual_projection(lowercase_					)

												UpperCAmelCase             = cosine_distance(lowercase_   ,  self.special_care_embeds					)
												UpperCAmelCase             = cosine_distance(lowercase_   ,  self.concept_embeds					)

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

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

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

												return images, has_nsfw_concepts











"""simple docstring"""


from ..utils import DummyObject, requires_backends






class 					lowercase(     metaclass=__a ):







 '''simple docstring'''





 lowercase__ 					=					["note_seq"]


 def __init__(				self:		Dict,      *a_:		Union[str, Any],      **a_:		List[str]		):




   '''simple docstring'''



   requires_backends(self,      ["""note_seq"""]		)


 @classmethod
 def  UpperCamelCase_   (				cls:		Optional[int],      *a_:		Any,      **a_:		Optional[Any]		):




   '''simple docstring'''



   requires_backends(cls,      ["""note_seq"""]		)


 @classmethod
 def  UpperCamelCase_   (				cls:		Tuple,      *a_:		Optional[Any],      **a_:		List[str]		):




   '''simple docstring'''



   requires_backends(cls,      ["""note_seq"""]		)


