
'''simple docstring'''
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


lowercase__						       =      logging.get_logger(__name__)




def    _UpperCamelCase						(       SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__			)  ->							Optional[int]:


		'''simple docstring'''


		snake_case  :       int     			=						nn.functional.normalize(SCREAMING_SNAKE_CASE__			)
		snake_case  :       Optional[Any]     			=						nn.functional.normalize(SCREAMING_SNAKE_CASE__			)
		return torch.mm(SCREAMING_SNAKE_CASE__ ,       normalized_text_embeds.t()			)






class 	snake_case__       (      __SCREAMING_SNAKE_CASE					):







		"""simple docstring"""

		lowerCamelCase     							=						CLIPConfig

		lowerCamelCase     							=						["""CLIPEncoderLayer"""]



		def __init__(      self				:			str  ,	UpperCamelCase__				:			CLIPConfig      )						->			Dict:






				"""simple docstring"""







				super().__init__(UpperCamelCase__      )

				snake_case  :       Dict     			=						CLIPVisionModel(config.vision_config      )
				snake_case  :       Any     			=						nn.Linear(config.vision_config.hidden_size  ,	config.projection_dim  ,	bias=UpperCamelCase__      )

				snake_case  :       Dict     			=						nn.Parameter(torch.ones(17  ,	config.projection_dim      )  ,	requires_grad=UpperCamelCase__      )
				snake_case  :       Optional[Any]     			=						nn.Parameter(torch.ones(3  ,	config.projection_dim      )  ,	requires_grad=UpperCamelCase__      )

				snake_case  :       Tuple     			=						nn.Parameter(torch.ones(17      )  ,	requires_grad=UpperCamelCase__      )
				snake_case  :       Optional[Any]     			=						nn.Parameter(torch.ones(3      )  ,	requires_grad=UpperCamelCase__      )



		@torch.no_grad()
		def       lowerCAmelCase				(      self				:			Union[str, Any]  ,	UpperCamelCase__				:			str  ,	UpperCamelCase__				:			Any      )						->			Optional[int]:






				"""simple docstring"""







				snake_case  :       Union[str, Any]     			=						self.vision_model(UpperCamelCase__      )[1]  # pooled_output
				snake_case  :       str     			=						self.visual_projection(UpperCamelCase__      )

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

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

						for concept_idx in range(len(special_cos_dist[0]      )      ):
								snake_case  :       Tuple     			=						special_cos_dist[i][concept_idx]
								snake_case  :       Union[str, Any]     			=						self.special_care_embeds_weights[concept_idx].item()
								snake_case  :       List[str]     			=						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  :       Dict     			=						0.01

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

						result.append(UpperCamelCase__      )

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

				return images, has_nsfw_concepts



		@torch.no_grad()
		def       lowerCAmelCase				(      self				:			Optional[int]  ,	UpperCamelCase__				:			torch.FloatTensor  ,	UpperCamelCase__				:			torch.FloatTensor      )						->			Union[str, Any]:






				"""simple docstring"""







				snake_case  :       List[str]     			=						self.vision_model(UpperCamelCase__      )[1]  # pooled_output
				snake_case  :       Optional[int]     			=						self.visual_projection(UpperCamelCase__      )

				snake_case  :       Optional[Any]     			=						cosine_distance(UpperCamelCase__  ,	self.special_care_embeds      )
				snake_case  :       Optional[Any]     			=						cosine_distance(UpperCamelCase__  ,	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  :       str     			=						0.0

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

				snake_case  :       List[Any]     			=						(cos_dist - self.concept_embeds_weights) + special_adjustment
				# concept_scores = concept_scores.round(decimals=3)
				snake_case  :       Tuple     			=						torch.any(concept_scores > 0  ,	dim=1      )

				return images, has_nsfw_concepts




'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowercase__						       =      {"configuration_encoder_decoder": ["EncoderDecoderConfig"]}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowercase__						       =      ["EncoderDecoderModel"]

try:
						if not is_tf_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowercase__						       =      ["TFEncoderDecoderModel"]

try:
						if not is_flax_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowercase__						       =      ["FlaxEncoderDecoderModel"]

if TYPE_CHECKING:
						from .configuration_encoder_decoder import EncoderDecoderConfig

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_encoder_decoder import EncoderDecoderModel

						try:
												if not is_tf_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_tf_encoder_decoder import TFEncoderDecoderModel

						try:
												if not is_flax_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel

else:
						import sys

						lowercase__						       =      _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


