

'''simple docstring'''


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

from ...utils import logging


lowerCAmelCase__      				=			logging.get_logger(__name__)







def     SCREAMING_SNAKE_CASE(	UpperCamelCase ,UpperCamelCase	)     ->     str:
	UpperCAmelCase_		:   Optional[int]													=       nn.functional.normalize(UpperCamelCase	)
	UpperCAmelCase_		:   Union[str, Any]													=       nn.functional.normalize(UpperCamelCase	)
	return torch.mm(UpperCamelCase ,normalized_text_embeds.t()	)







class        lowercase    (	a_			):
							_lowerCamelCase		:   Dict= CLIPConfig

							_lowerCamelCase		:   Any= ["CLIPEncoderLayer"]


							def __init__(      self     ,      _snake_case)				->					Optional[Any]:
								super().__init__(_snake_case)

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

								UpperCAmelCase_		:   Optional[int]													=       nn.Parameter(torch.ones(17     ,      config.projection_dim)     ,      requires_grad=_snake_case)
								UpperCAmelCase_		:   Dict													=       nn.Parameter(torch.ones(3     ,      config.projection_dim)     ,      requires_grad=_snake_case)

								UpperCAmelCase_		:   Optional[int]													=       nn.Parameter(torch.ones(17)     ,      requires_grad=_snake_case)
								UpperCAmelCase_		:   List[str]													=       nn.Parameter(torch.ones(3)     ,      requires_grad=_snake_case)


							@torch.no_grad()
							def     _snake_case				(      self     ,      _snake_case     ,      _snake_case)				->					int:
								UpperCAmelCase_		:   Optional[int]													=       self.vision_model(_snake_case)[1]  # pooled_output
								UpperCAmelCase_		:   Optional[int]													=       self.visual_projection(_snake_case)

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

								UpperCAmelCase_		:   Dict													=       []
								UpperCAmelCase_		:   List[Any]													=       image_embeds.shape[0]
								for i in range(_snake_case):
									UpperCAmelCase_		:   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
									UpperCAmelCase_		:   Any													=       0.0

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

									for concept_idx in range(len(cos_dist[0])):
										UpperCAmelCase_		:   Optional[int]													=       cos_dist[i][concept_idx]
										UpperCAmelCase_		:   List[Any]													=       self.concept_embeds_weights[concept_idx].item()
										UpperCAmelCase_		:   Union[str, Any]													=       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_		:   Optional[Any]													=       [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_		:   int													=       torch.zeros_like(images[idx])  # black image
										else:
											UpperCAmelCase_		:   Optional[int]													=       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     _snake_case				(      self     ,      _snake_case     ,      _snake_case)				->					List[str]:
								UpperCAmelCase_		:   List[Any]													=       self.vision_model(_snake_case)[1]  # pooled_output
								UpperCAmelCase_		:   List[Any]													=       self.visual_projection(_snake_case)

								UpperCAmelCase_		:   int													=       cosine_distance(_snake_case     ,      self.special_care_embeds)
								UpperCAmelCase_		:   int													=       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_		:   List[str]													=       0.0

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

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

								UpperCAmelCase_		:   List[str]													=       0.0  # black image

								return images, has_nsfw_concepts









'''simple docstring'''


from __future__ import annotations

from collections.abc import Iterable, Iterator
from typing import Any, Generic, TypeVar

lowerCAmelCase__      				=			TypeVar("T", bound=bool)



class        lowercase    (	Generic[T]			):


							def __init__(      self     ,      _snake_case)				->					None:
								UpperCAmelCase_		:   T													=       value
								UpperCAmelCase_		:   SkewNode[T] | None													=       None
								UpperCAmelCase_		:   SkewNode[T] | None													=       None


							@property
							def     _snake_case				(      self)				->					T:
								return self._value





							@staticmethod
							def     _snake_case				(      _snake_case     ,      _snake_case)				->					SkewNode[T] | None:
								if not roota:
									return roota

								if not roota:
									return roota

								if roota.value > roota.value:
									UpperCAmelCase_						,     UpperCAmelCase_		:   Union[str, Any]													=       roota, roota

								UpperCAmelCase_		:   Dict													=       roota
								UpperCAmelCase_		:   Dict													=       roota.right
								UpperCAmelCase_		:   Optional[int]													=       roota.left
								UpperCAmelCase_		:   Dict													=       SkewNode.merge(_snake_case     ,      _snake_case)

								return result



class        lowercase    (	Generic[T]			):


							def __init__(      self     ,      _snake_case = ())				->					None:
								UpperCAmelCase_		:   SkewNode[T] | None													=       None
								if data:
									for item in data:
										self.insert(_snake_case)


							def __bool__(      self)				->					bool:
								return self._root is not None


							def __iter__(      self)				->					Iterator[T]:
								UpperCAmelCase_		:   list[Any]													=       []
								while self:
									result.append(self.pop())

								# Pushing items back to the heap not to clear it.
								for item in result:
									self.insert(_snake_case)

								return iter(_snake_case)


							def     _snake_case				(      self     ,      _snake_case)				->					None:
								UpperCAmelCase_		:   Any													=       SkewNode.merge(self._root     ,      SkewNode(_snake_case))


							def     _snake_case				(      self)				->					T | None:
								UpperCAmelCase_		:   Union[str, Any]													=       self.top()
								UpperCAmelCase_		:   Tuple													=       (
								    SkewNode.merge(self._root.left     ,      self._root.right) if self._root else None
								)

								return result


							def     _snake_case				(      self)				->					T:
								if not self._root:
									raise IndexError('Can\'t get top element for the empty heap.')
								return self._root.value





							def     _snake_case				(      self)				->					None:
								UpperCAmelCase_		:   Union[str, Any]													=       None


if __name__ == "__main__":
						import doctest

						doctest.testmod()






