






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

from ...utils import logging


_a   			=						logging.get_logger(__name__)


def __A					(   __lowerCAmelCase				,	__lowerCAmelCase			)->						Optional[Any]:





						"""simple docstring"""



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





class __lowerCamelCase				(   snake_case__):





	"""simple docstring"""






	UpperCamelCase__			=   CLIPConfig

	UpperCamelCase__			=   ["CLIPEncoderLayer"]

	def __init__(							self ,					UpperCAmelCase					):
							"""simple docstring"""







							super().__init__(UpperCAmelCase					)

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

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

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

	@torch.no_grad()
	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







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

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

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

													result.append(UpperCAmelCase					)

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

							for idx, has_nsfw_concept in enumerate(UpperCAmelCase					):
													if has_nsfw_concept:
																			if torch.is_tensor(UpperCAmelCase					) 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(UpperCAmelCase					):
													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 ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







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

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













import math
from timeit import timeit


def __A					(   __lowerCAmelCase			)->						int:





						"""simple docstring"""



						_UpperCAmelCase             =    0
						_UpperCAmelCase             =    abs(__lowerCAmelCase			)
						while True:
												_UpperCAmelCase             =    n // 10
												digits += 1
												if n == 0:
																		break
						return digits


def __A					(   __lowerCAmelCase			)->						int:





						"""simple docstring"""



						return 1 if n == 0 else math.floor(math.log(abs(__lowerCAmelCase			)				,	10			) + 1			)


def __A					(   __lowerCAmelCase			)->						int:





						"""simple docstring"""



						return len(str(abs(__lowerCAmelCase			)			)			)


def __A					(   )->						None:





						"""simple docstring"""



						from collections.abc import Callable

						def benchmark_a_function(__lowerCAmelCase				,	__lowerCAmelCase			) -> None:
												_UpperCAmelCase             =    F"""{func.__name__}({value})"""
												_UpperCAmelCase             =    timeit(F"""__main__.{call}"""				,	setup='import __main__'			)
												print(F"""{call}: {func(__lowerCAmelCase			)} -- {timing} seconds"""			)

						for value in (262_144, 1_125_899_906_842_624, 1_267_650_600_228_229_401_496_703_205_376):
												for func in (num_digits, num_digits_fast, num_digits_faster):
																		benchmark_a_function(__lowerCAmelCase				,	__lowerCAmelCase			)
												print()


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		benchmark()
