"""simple docstring"""







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

from ...utils import logging


_a					:					List[Any]=			logging.get_logger(__name__)
def   __UpperCAmelCase    (   UpperCAmelCase_   :    str      ,							UpperCAmelCase_   :    List[Any]  )							->      str:

	'''simple docstring'''





	__snake_case      :							Optional[Any]						=			nn.functional.normalize(UpperCamelCase__  )
	__snake_case      :							List[Any]						=			nn.functional.normalize(UpperCamelCase__  )
	return torch.mm(UpperCamelCase__      ,							normalized_text_embeds.t()  )

class 		UpperCamelCase      (   lowercase						):
				UpperCAmelCase    :				Dict   =		CLIPConfig

				UpperCAmelCase    :				int   =		["""CLIPEncoderLayer"""]



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

					__snake_case      :							Any						=			CLIPVisionModel(config.vision_config)
					__snake_case      :							Optional[int]						=			nn.Linear(config.vision_config.hidden_size     ,  config.projection_dim     ,  bias=_A)

					__snake_case      :							Optional[Any]						=			nn.Parameter(torch.ones(17     ,  config.projection_dim)     ,  requires_grad=_A)
					__snake_case      :							int						=			nn.Parameter(torch.ones(3     ,  config.projection_dim)     ,  requires_grad=_A)

					__snake_case      :							str						=			nn.Parameter(torch.ones(17)     ,  requires_grad=_A)
					__snake_case      :							Any						=			nn.Parameter(torch.ones(3)     ,  requires_grad=_A)



				@torch.no_grad()
				def  _lowercase					(self    :				List[str]     ,  _A    :				Tuple     ,  _A    :				Union[str, Any])   ->     List[Any]:
					__snake_case      :							str						=			self.vision_model(_A)[1]  # pooled_output
					__snake_case      :							Any						=			self.visual_projection(_A)

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

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

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

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

						result.append(_A)

					__snake_case      :							List[str]						=			[len(res['bad_concepts']) > 0 for res in result]

					return images, has_nsfw_concepts






				@torch.no_grad()
				def  _lowercase					(self    :				Any     ,  _A    :				Tuple     ,  _A    :				Optional[Any])   ->     List[Any]:
					__snake_case      :							Dict						=			self.vision_model(_A)[1]  # pooled_output
					__snake_case      :							Any						=			self.visual_projection(_A)

					__snake_case      :							Optional[Any]						=			cosine_distance(_A     ,  self.special_care_embeds)
					__snake_case      :							List[Any]						=			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
					__snake_case      :							int						=			0.0

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

					__snake_case      :							Optional[int]						=			(cos_dist - self.concept_embeds_weights) + special_adjustment
					# concept_scores = concept_scores.round(decimals=3)
					__snake_case      :							str						=			torch.any(concept_scores > 0     ,  dim=1)

					return images, has_nsfw_concepts



"""simple docstring"""







import warnings

from ...utils import logging
from .image_processing_clip import CLIPImageProcessor


_a					:					Dict=			logging.get_logger(__name__)

class 		UpperCamelCase      (   lowercase						):



				def __init__(self    :				List[str]     ,  *_A    :				Dict     ,  **_A    :				Optional[Any])   ->     None:
					warnings.warn(
					    'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
					    ' use CLIPImageProcessor instead.'     ,  _A     ,  )
					super().__init__(*_A     ,  **_A)





