




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

from ...utils import logging


lowercase_      :							Optional[int]    							=					logging.get_logger(__name__)


def 				__SCREAMING_SNAKE_CASE    (     snake_case_      ,       snake_case_		):

						'''simple docstring'''


						_UpperCAmelCase						=	nn.functional.normalize(snake_case_		)
						_UpperCAmelCase						=	nn.functional.normalize(snake_case_		)
						return torch.mm(snake_case_      ,       normalized_text_embeds.t()		)






class        __lowerCAmelCase					(			a_					):
			snake_case_ :					Dict						=	CLIPConfig

			snake_case_ :					Any						=	["CLIPEncoderLayer"]







			def __init__(			self       :     Any       ,       snake_case__       :     Tuple ):




									"""simple docstring"""


									super().__init__(_snake_case )

									_UpperCAmelCase						=	CLIPVisionModel(config.vision_config )
									_UpperCAmelCase						=	nn.Linear(config.vision_config.hidden_size       ,       config.projection_dim       ,       bias=_snake_case )

									_UpperCAmelCase						=	nn.Parameter(torch.ones(17       ,       config.projection_dim )       ,       requires_grad=_snake_case )
									_UpperCAmelCase						=	nn.Parameter(torch.ones(3       ,       config.projection_dim )       ,       requires_grad=_snake_case )

									_UpperCAmelCase						=	nn.Parameter(torch.ones(17 )       ,       requires_grad=_snake_case )
									_UpperCAmelCase						=	nn.Parameter(torch.ones(3 )       ,       requires_grad=_snake_case )







			@torch.no_grad()
			def UpperCamelCase     (			self       :     List[str]       ,       snake_case__       :     Optional[Any]       ,       snake_case__       :     int ):




									"""simple docstring"""


									_UpperCAmelCase						=	self.vision_model(_snake_case )[1]  # pooled_output
									_UpperCAmelCase						=	self.visual_projection(_snake_case )

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

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

															result.append(_snake_case )

									_UpperCAmelCase						=	[len(res["bad_concepts"] ) > 0 for res in result]

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

									if any(_snake_case ):
															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 UpperCamelCase     (			self       :     List[Any]       ,       snake_case__       :     Any       ,       snake_case__       :     Tuple ):




									"""simple docstring"""


									_UpperCAmelCase						=	self.vision_model(_snake_case )[1]  # pooled_output
									_UpperCAmelCase						=	self.visual_projection(_snake_case )

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

									_UpperCAmelCase						=	0.0  # black image

									return images, has_nsfw_concepts







'''simple docstring'''


from __future__ import annotations







def     SCREAMING_SNAKE_CASE(	UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase	)     ->     int:

	# Base Case
	if counter == 0 or capacity == 0:
		return 0

	# If weight of the nth item is more than Knapsack of capacity,
	#   then this item cannot be included in the optimal solution,
	# else return the maximum of two cases:
	#   (1) nth item included
	#   (2) not included
	if weights[counter - 1] > capacity:
		return knapsack(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,counter - 1	)
	else:
		UpperCAmelCase_		:   int													=       capacity - weights[counter - 1]
		UpperCAmelCase_		:   Optional[int]													=       values[counter - 1] + knapsack(
		    UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,counter - 1	)
		UpperCAmelCase_		:   Any													=       knapsack(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,counter - 1	)
		return max(UpperCamelCase ,UpperCamelCase	)


if __name__ == "__main__":
						import doctest

						doctest.testmod()






